当前位置: 首页>>代码示例>>Java>>正文


Java BinaryData类代码示例

本文整理汇总了Java中org.hawkular.bus.common.BinaryData的典型用法代码示例。如果您正苦于以下问题:Java BinaryData类的具体用法?Java BinaryData怎么用?Java BinaryData使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


BinaryData类属于org.hawkular.bus.common包,在下文中一共展示了BinaryData类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testMessageWithExtraData

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Test
public void testMessageWithExtraData() {
    // serialize a message and some extra data
    final String testMessage = "this is the message";
    final String testExtraData = "this is extra data";

    GenericSuccessResponse msg = new GenericSuccessResponse();
    msg.setMessage(testMessage);
    ByteArrayInputStream extraData = new ByteArrayInputStream(testExtraData.getBytes());
    BinaryData fullData = ApiDeserializer.toHawkularFormat(msg, extraData);

    // now deserialize the data
    ApiDeserializer ad = new ApiDeserializer();
    BasicMessageWithExtraData<GenericSuccessResponse> deserializedFullData = ad.deserialize(fullData);
    GenericSuccessResponse deserializedMessage = deserializedFullData.getBasicMessage();
    BinaryData deserializedExtraData = deserializedFullData.getBinaryData();
    String deserializedExtraDataString = new Scanner(deserializedExtraData, "UTF-8").useDelimiter("\\A").next();

    // make sure the deserialized data matches what we serialized
    Assert.assertEquals(testMessage, deserializedMessage.getMessage());
    Assert.assertEquals(testExtraData, deserializedExtraDataString);

}
 
开发者ID:hawkular,项目名称:hawkular-commons,代码行数:24,代码来源:ApiDeserializerTest.java

示例2: testReadFromInputStreamWithNoExtraData

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Test
public void testReadFromInputStreamWithNoExtraData() throws IOException {
    ApiDeserializer ad = new ApiDeserializer();

    String nameAndJson = EchoRequest.class.getName() + "={\"echoMessage\":\"msg\"}";
    ByteArrayInputStream in = new UncloseableByteArrayInputStream(nameAndJson.getBytes());

    BasicMessageWithExtraData<AbstractMessage> map = ad.deserialize(in);
    AbstractMessage request = map.getBasicMessage();
    Assert.assertTrue(request instanceof EchoRequest);
    EchoRequest echoRequest = (EchoRequest) request;
    Assert.assertEquals("msg", echoRequest.getEchoMessage());

    // now make sure the stream is empty
    BinaryData leftover = map.getBinaryData();
    Assert.assertEquals(0, leftover.available());
    Assert.assertEquals(0, in.available());
}
 
开发者ID:hawkular,项目名称:hawkular-commons,代码行数:19,代码来源:ApiDeserializerTest.java

示例3: textMessageWithBinary

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Test
public void textMessageWithBinary() throws JMSException, IOException, InterruptedException {
    assertNotNull(connectionFactory);

    Endpoint endpoint = new Endpoint(Type.QUEUE, TEST_QUEUE);

    try (MessageReceiver receiver = new MessageReceiver(connectionFactory, endpoint)) {
        byte[] bytesSent = "deadbeef".getBytes("utf-8");

        SimpleBasicMessage messageSent = new SimpleBasicMessage("textMessageWithBinary");
        BasicMessageWithExtraData<SimpleBasicMessage> envelopeSent =
                new BasicMessageWithExtraData<SimpleBasicMessage>(messageSent,
                        new BinaryData(bytesSent, new ByteArrayInputStream(new byte[0])));
        try (ConnectionContextFactory ccf = new ConnectionContextFactory(connectionFactory)) {
            ProducerConnectionContext pcc = ccf.createProducerConnectionContext(endpoint);
            MessageId mid =
                    new MessageProcessor().send(pcc, envelopeSent,
                            Collections.singletonMap(TEST_HEADER, TEST_VALUE));
            log.infof("Sent message [%s] with messageId [%s]", messageSent, mid);
        }

        BasicMessageWithExtraData<BasicMessage> envelopeReceived =
                receiver.receivedMessages.poll(15, TimeUnit.SECONDS);
        Assert.assertNotNull("No message received", envelopeReceived);
        Assert.assertEquals(envelopeSent.getBasicMessage().toJSON(), envelopeReceived.getBasicMessage().toJSON());

        ByteArrayOutputStream bytesReceived = new ByteArrayOutputStream(bytesSent.length);
        copy(envelopeReceived.getBinaryData(), bytesReceived);

        Assert.assertArrayEquals(bytesSent, bytesReceived.toByteArray());
    }
}
 
开发者ID:hawkular,项目名称:hawkular-bus,代码行数:33,代码来源:BusTest.java

示例4: textMessageWithBinary

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Test(groups = { GROUP })
public void textMessageWithBinary() throws JMSException, IOException, InterruptedException {
    Assert.assertNotNull(connectionFactory);

    Endpoint endpoint = new Endpoint(Type.QUEUE, TEST_QUEUE);

    try (MessageReceiver receiver = new MessageReceiver(connectionFactory, endpoint)) {
        byte[] bytesSent = "deadbeef".getBytes("utf-8");

        SimpleBasicMessage messageSent = new SimpleBasicMessage("textMessageWithBinary");
        BasicMessageWithExtraData<SimpleBasicMessage> envelopeSent =
                new BasicMessageWithExtraData<SimpleBasicMessage>(messageSent,
                        new BinaryData(bytesSent, new ByteArrayInputStream(new byte[0])));
        try (ConnectionContextFactory ccf = new ConnectionContextFactory(connectionFactory)) {
            ProducerConnectionContext pcc = ccf.createProducerConnectionContext(endpoint);
            MessageId mid =
                    new MessageProcessor().send(pcc, envelopeSent,
                            Collections.singletonMap(TEST_HEADER, TEST_VALUE));
            log.infof("Sent message [%s] with messageId [%s]", messageSent, mid);
        }

        BasicMessageWithExtraData<BasicMessage> envelopeReceived =
                receiver.receivedMessages.poll(15, TimeUnit.SECONDS);
        Assert.assertNotNull(envelopeReceived, "No message received");
        Assert.assertEquals(envelopeReceived.getBasicMessage().toJSON(), envelopeSent.getBasicMessage().toJSON());

        ByteArrayOutputStream bytesReceived = new ByteArrayOutputStream(bytesSent.length);
        copy(envelopeReceived.getBinaryData(), bytesReceived);

        Assert.assertEquals(bytesReceived.toByteArray(), bytesSent);
    }
}
 
开发者ID:hawkular,项目名称:hawkular-commons,代码行数:33,代码来源:BusITest.java

示例5: testMessageWithLargeExtraData

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Test
public void testMessageWithLargeExtraData() throws Exception {
    // serialize a message and some extra data
    final String testMessage = "this is the message";
    final String testExtraData;

    // stream [0, 1, 2, ..., 255], repeat that 10 times
    byte[] bytes = new byte[0xff * 10];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = (byte) (i % 256);
    }
    testExtraData = new String(bytes, "UTF-8");

    GenericSuccessResponse msg = new GenericSuccessResponse();
    msg.setMessage(testMessage);
    ByteArrayInputStream extraData = new ByteArrayInputStream(testExtraData.getBytes("UTF-8"));
    BinaryData fullData = ApiDeserializer.toHawkularFormat(msg, extraData);

    // now deserialize the data
    ApiDeserializer ad = new ApiDeserializer();
    BasicMessageWithExtraData<GenericSuccessResponse> deserializedFullData = ad.deserialize(fullData);
    GenericSuccessResponse deserializedMessage = deserializedFullData.getBasicMessage();
    BinaryData deserializedExtraData = deserializedFullData.getBinaryData();
    String deserializedExtraDataString = new Scanner(deserializedExtraData, "UTF-8").useDelimiter("\\A").next();

    // make sure the deserialized data matches what we serialized
    Assert.assertEquals(testMessage, deserializedMessage.getMessage());
    Assert.assertEquals(testExtraData, deserializedExtraDataString);

}
 
开发者ID:hawkular,项目名称:hawkular-commons,代码行数:31,代码来源:ApiDeserializerTest.java

示例6: testReadFromInputStreamWithExtraData

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Test
public void testReadFromInputStreamWithExtraData() throws IOException {
    // tests that this can extract the JSON even if more data follows in the stream
    ApiDeserializer ad = new ApiDeserializer();

    String nameAndJson = EchoRequest.class.getName() + "={\"echoMessage\":\"msg\"}";
    String extra = "This is some extra data";
    String nameAndJsonPlusExtra = nameAndJson + extra;

    ByteArrayInputStream in = new UncloseableByteArrayInputStream(nameAndJsonPlusExtra.getBytes());

    BasicMessageWithExtraData<AbstractMessage> map = ad.deserialize(in);
    AbstractMessage request = map.getBasicMessage();
    Assert.assertTrue(request instanceof EchoRequest);
    EchoRequest echoRequest = (EchoRequest) request;
    Assert.assertEquals("msg", echoRequest.getEchoMessage());

    // now make sure the stream still has our extra data that we can read now
    BinaryData leftover = map.getBinaryData();
    byte[] leftoverByteArray = new byte[leftover.available()];
    leftover.read(leftoverByteArray);

    String totalRemaining = new String(leftoverByteArray, "UTF-8");
    Assert.assertEquals(extra.length(), totalRemaining.length());
    Assert.assertEquals(extra, totalRemaining);

    // as a quick test, show that an exception results if we give bogus data in the input stream
    in = new UncloseableByteArrayInputStream("this is not valid data".getBytes());
    try {
        ad.deserialize(in);
        Assert.fail("Should have thrown an exception - the stream had invalid data");
    } catch (Exception expected) {
    }
}
 
开发者ID:hawkular,项目名称:hawkular-commons,代码行数:35,代码来源:ApiDeserializerTest.java

示例7: execute

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Override
public void execute(BasicMessageWithExtraData<EchoRequest> message, WsCommandContext context) throws IOException {
    EchoRequest echoRequest = message.getBasicMessage();
    BinaryData binaryData = message.getBinaryData();
    String echo = String.format("ECHO [%s]", echoRequest.getEchoMessage());

    // return the response
    EchoResponse echoResponse = new EchoResponse();
    echoResponse.setReply(echo);
    BasicMessageWithExtraData<EchoResponse> result = new BasicMessageWithExtraData<>(echoResponse, binaryData);
    new WebSocketHelper().sendSync(context.getSession(), result);
}
 
开发者ID:hawkular,项目名称:hawkular-commons,代码行数:13,代码来源:EchoCommand.java

示例8: sendSync

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
/**
 * Delegates to either {@link #sendBasicMessageSync(Session, BasicMessage)} or
 * {@link #sendBinarySync(Session, InputStream)} based on {@code message.getBinaryData() == null}.
 *
 * @param session the session to send to
 * @param message the message to send
 * @throws IOException
 */
public void sendSync(Session session, BasicMessageWithExtraData<? extends BasicMessage> message)
        throws IOException {
    BinaryData binary = message.getBinaryData();
    if (binary == null) {
        sendBasicMessageSync(session, message.getBasicMessage());
    } else {
        // there is binary data to stream back - do it ourselves and don't return anything
        BinaryData serialized = ApiDeserializer.toHawkularFormat(message.getBasicMessage(),
                message.getBinaryData());
        sendBinarySync(session, serialized);
    }
}
 
开发者ID:hawkular,项目名称:hawkular-commons,代码行数:21,代码来源:WebSocketHelper.java

示例9: emitToSink

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
private void emitToSink(BinaryData in, BufferedSink out) throws RuntimeException {
    int bufferSize = 32768;
    try {
        InputStream input = new BufferedInputStream(in, bufferSize);
        byte[] buffer = new byte[bufferSize];
        for (int bytesRead = input.read(buffer); bytesRead != -1; bytesRead = input.read(buffer)) {
            out.write(buffer, 0, bytesRead);
            out.flush();
        }
    } catch (IOException ioe) {
        throw new RuntimeException("Failed to emit to sink", ioe);
    }
}
 
开发者ID:hawkular,项目名称:hawkular-agent,代码行数:14,代码来源:FeedCommProcessor.java

示例10: execute

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
/**
 * @see org.hawkular.agent.monitor.cmd.AbstractDMRResourcePathCommand#execute(org.hawkular.dmrclient.JBossASClient,
 *      EndpointService, java.lang.String,
 *      org.hawkular.cmdgw.api.ResourcePathRequest, org.hawkular.cmdgw.api.ResourcePathResponse,
 *      org.hawkular.agent.monitor.cmd.CommandContext, DMRSession)
 */
@Override
protected BinaryData execute(ModelControllerClient controllerClient,
        EndpointService<DMRNodeLocation, DMRSession> endpointService,
        String modelNodePath,
        BasicMessageWithExtraData<AddJdbcDriverRequest> envelope, AddJdbcDriverResponse response,
        CommandContext context, DMRSession dmrContext) throws Exception {
    AddJdbcDriverRequest request = envelope.getBasicMessage();
    response.setDriverName(request.getDriverName());

    ModuleResource jarResource = new ModuleResource(envelope.getBinaryData(),
            request.getDriverJarName());

    AddModuleRequest addModuleRequest = new AddModuleRequest(request.getModuleName(), (String) null, (String) null,
            Collections.singleton(jarResource), DEFAULT_DRIVER_MODULE_DEPENDENCIES, null);
    new Modules(Modules.findModulesDir()).add(addModuleRequest);

    OperationResult<?> opResult = OperationBuilder.add()
            .address().subsystemDatasources().segment(JDBC_DRIVER, request.getDriverName()).parentBuilder()
            .attribute(JdbcDriverNodeConstants.DRIVER_NAME, request.getDriverName())
            .attribute(JdbcDriverNodeConstants.DRIVER_MODULE_NAME, request.getModuleName())
            .attribute(JdbcDriverNodeConstants.DRIVER_CLASS_NAME, request.getDriverClass())
            .attribute(JdbcDriverNodeConstants.DRIVER_MAJOR_VERSION, request.getDriverMajorVersion())
            .attribute(JdbcDriverNodeConstants.DRIVER_MINOR_VERSION, request.getDriverMinorVersion())
            .attribute(JdbcDriverNodeConstants.DRIVER_XA_DATASOURCE_CLASS_NAME,
                    request.getDriverXaDatasourceClassName())
            .attribute(JdbcDriverNodeConstants.JDBC_COMPLIANT, request.getJdbcCompliant())
            .execute(controllerClient)
            .assertSuccess();
    setServerRefreshIndicator(opResult, response);

    endpointService.discoverAll();

    return null;
}
 
开发者ID:hawkular,项目名称:hawkular-agent,代码行数:41,代码来源:AddJdbcDriverCommand.java

示例11: testWithSimpleInputStream

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Test
public void testWithSimpleInputStream() throws Exception {
    ConnectionContextFactory consumerFactory = null;
    ConnectionContextFactory producerFactory = null;

    TCPEmbeddedBrokerWrapper broker = new TCPEmbeddedBrokerWrapper();
    broker.start();

    String storageLocation = getTmpDirectory();

    try {
        String brokerURL = broker.getBrokerURL();
        brokerURL += "?jms.blobTransferPolicy.uploadUrl=file:" + storageLocation;
        Endpoint endpoint = new Endpoint(Type.QUEUE, "testq");

        // mimic server-side
        consumerFactory = new ConnectionContextFactory(brokerURL);
        ConsumerConnectionContext consumerContext = consumerFactory.createConsumerConnectionContext(endpoint);
        MessageWithExtraDataTestListener<SpecificMessage> listener;
        listener = new MessageWithExtraDataTestListener<SpecificMessage>(SpecificMessage.class);
        MessageProcessor serverSideProcessor = new MessageProcessor();
        serverSideProcessor.listen(consumerContext, listener);

        // mimic client side
        producerFactory = new ConnectionContextFactory(brokerURL);
        ProducerConnectionContext producerContext = producerFactory.createProducerConnectionContext(endpoint);
        MessageProcessor clientSideProcessor = new MessageProcessor();

        // send with an input stream
        SpecificMessage specificMessage = new SpecificMessage("hello", null, "specific text");
        String outgoingExtraData = "1234567890";
        ByteArrayInputStream input = new ByteArrayInputStream(outgoingExtraData.getBytes());
        clientSideProcessor.sendWithBinaryData(producerContext, specificMessage, input);

        // wait for the message to flow and check that it and the streamed data arrived
        listener.waitForMessage(3);
        BasicMessageWithExtraData<SpecificMessage> receivedMsgWithData = listener
                .getReceivedMessageWithExtraData();
        SpecificMessage receivedMsg = receivedMsgWithData.getBasicMessage();
        assertEquals("Should have received the message", receivedMsg.getSpecific(), "specific text");

        BinaryData binaryData = receivedMsgWithData.getBinaryData();
        byte[] incomingExtraData = new byte[outgoingExtraData.length()];
        Assert.assertEquals(outgoingExtraData.length(), binaryData.read(incomingExtraData));
        Assert.assertEquals(outgoingExtraData, new String(incomingExtraData, "UTF-8"));

        // make sure the data has been removed from the uploadUrl storage location
        binaryData.close(); // closing will force the backing file to be removed
        File[] blobsStillAround = new File(storageLocation).listFiles();
        Assert.assertEquals("Still have blobs: " + Arrays.asList(blobsStillAround), 0, blobsStillAround.length);

    } finally {
        // close everything
        producerFactory.close();
        consumerFactory.close();
        broker.stop();

        // clean the storage location
        File doomedDir = new File(storageLocation);
        File[] doomedFiles = doomedDir.listFiles();
        for (File doomedFile : (doomedFiles == null) ? new File[0] : doomedFiles) {
            doomedFile.delete();
        }
        doomedDir.delete();
    }

}
 
开发者ID:hawkular,项目名称:hawkular-bus,代码行数:68,代码来源:LargeDataTest.java

示例12: execute

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Override
protected BinaryData execute(
        ModelControllerClient controllerClient,
        EndpointService<DMRNodeLocation, DMRSession> endpointService,
        String modelNodePath,
        BasicMessageWithExtraData<EnableApplicationRequest> envelope,
        EnableApplicationResponse response,
        CommandContext context,
        DMRSession dmrContext)
                throws Exception {

    EnableApplicationRequest request = envelope.getBasicMessage();

    final String resourcePath = request.getResourceId();
    final String destFileName = request.getDestinationFileName();
    final Set<String> serverGroups = convertCsvToSet(request.getServerGroups());

    String resourceId = resourcePath;

    ResourceManager<DMRNodeLocation> resourceManager = endpointService.getResourceManager();
    Resource<DMRNodeLocation> resource = resourceManager.getResource(new ID(resourceId));
    if (resource == null) {
        throw new IllegalArgumentException(
                String.format("Cannot enable application: unknown resource [%s]", resourcePath));
    }

    Collection<Operation<DMRNodeLocation>> ops = resource.getResourceType().getOperations();
    boolean canPerform = false;
    log.tracef("Searching for [%s] operation among operations [%s] for resource [%s].", NAME, ops,
            resource.getID());
    for (Operation<DMRNodeLocation> op : ops) {
        if (NAME.equals(op.getName().getNameString())) {
            canPerform = true;
            break;
        }
    }

    if (!canPerform) {
        throw new IllegalArgumentException(
                String.format("Cannot [%s] from [%s]. The operation is undefined.", NAME, resource));
    }

    MessageUtils.prepareResourceResponse(request, response);
    response.setDestinationFileName(request.getDestinationFileName());

    // don't close this wrapper client
    DeploymentJBossASClient client = new DeploymentJBossASClient(dmrContext.getClient());
    client.enableDeployment(destFileName, serverGroups);

    // run discovery now so we can quickly show the app has been removed
    endpointService.discoverAll();
    return null;
}
 
开发者ID:hawkular,项目名称:hawkular-agent,代码行数:54,代码来源:EnableApplicationCommand.java

示例13: execute

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Override
protected BinaryData execute(
        ModelControllerClient controllerClient,
        EndpointService<DMRNodeLocation, DMRSession> endpointService,
        String modelNodePath,
        BasicMessageWithExtraData<DisableApplicationRequest> envelope,
        DisableApplicationResponse response,
        CommandContext context,
        DMRSession dmrContext)
                throws Exception {

    DisableApplicationRequest request = envelope.getBasicMessage();

    final String resourcePath = request.getResourceId();
    final String destFileName = request.getDestinationFileName();
    final Set<String> serverGroups = convertCsvToSet(request.getServerGroups());

    String resourceId = resourcePath;

    ResourceManager<DMRNodeLocation> resourceManager = endpointService.getResourceManager();
    Resource<DMRNodeLocation> resource = resourceManager.getResource(new ID(resourceId));
    if (resource == null) {
        throw new IllegalArgumentException(
                String.format("Cannot disable application: unknown resource [%s]", resourcePath));
    }

    Collection<Operation<DMRNodeLocation>> ops = resource.getResourceType().getOperations();
    boolean canPerform = false;
    log.tracef("Searching for [%s] operation among operations [%s] for resource [%s].", NAME, ops,
            resource.getID());
    for (Operation<DMRNodeLocation> op : ops) {
        if (NAME.equals(op.getName().getNameString())) {
            canPerform = true;
            break;
        }
    }

    if (!canPerform) {
        throw new IllegalArgumentException(
                String.format("Cannot [%s] from [%s]. The operation is undefined.", NAME, resource));
    }

    MessageUtils.prepareResourceResponse(request, response);
    response.setDestinationFileName(request.getDestinationFileName());

    // don't close this wrapper client
    DeploymentJBossASClient client = new DeploymentJBossASClient(dmrContext.getClient());
    client.disableDeployment(destFileName, serverGroups);

    // run discovery now so we can quickly show the app has been removed
    endpointService.discoverAll();
    return null;
}
 
开发者ID:hawkular,项目名称:hawkular-agent,代码行数:54,代码来源:DisableApplicationCommand.java

示例14: execute

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Override
protected BinaryData execute(
        ModelControllerClient controllerClient,
        EndpointService<DMRNodeLocation, DMRSession> endpointService,
        String modelNodePath,
        BasicMessageWithExtraData<AddDatasourceRequest> envelope,
        AddDatasourceResponse response,
        CommandContext context,
        DMRSession dmrContext) throws Exception {
    AddDatasourceRequest request = envelope.getBasicMessage();
    response.setDatasourceName(request.getDatasourceName());
    response.setXaDatasource(request.isXaDatasource());

    Map<String, String> props = request.getDatasourceProperties();
    final String dsDmrResourceType;
    final String dsPropsDmrResourceType;
    final ModelNode dsAdr;
    final CompositeOperationBuilder<?> batch;
    if (request.isXaDatasource()) {
        dsDmrResourceType = XA_DATASOURCE;
        dsPropsDmrResourceType = XA_DATASOURCE_PROPERTIES;
        dsAdr = OperationBuilder.address().subsystemDatasources()
                .segment(dsDmrResourceType, request.getDatasourceName()).build();

        batch = OperationBuilder.composite() //
                .add() //
                .address(dsAdr) //
                .attribute(JNDI_NAME, request.getJndiName()) //
                .attribute(DRIVER_NAME, request.getDriverName()) //
                .attribute(XA_DATASOURCE_CLASS, request.getXaDataSourceClass()) //
                .attribute(USER_NAME, request.getUserName()) //
                .attribute(PASSWORD, request.getPassword()) //
                .attribute(STATISTICS_ENABLED, true) //
                .parentBuilder();
    } else {
        dsDmrResourceType = DATASOURCE;
        dsPropsDmrResourceType = CONNECTION_PROPERTIES;
        dsAdr = OperationBuilder.address().subsystemDatasources()
                .segment(dsDmrResourceType, request.getDatasourceName()).build();

        batch = OperationBuilder.composite() //
                .add() //
                .address(dsAdr) //
                .attribute(JNDI_NAME, request.getJndiName()) //
                .attribute(DRIVER_NAME, request.getDriverName()) //
                .attribute(DRIVER_CLASS, request.getDriverClass()) //
                .attribute(CONNECTION_URL, request.getConnectionUrl()) //
                .attribute(USER_NAME, request.getUserName()) //
                .attribute(PASSWORD, request.getPassword()) //
                .attribute(STATISTICS_ENABLED, true) //
                .parentBuilder();

    }
    if (props!=null && !props.isEmpty()) {
        for (Entry<String, String> prop : props.entrySet()) {
            batch.add() //
                    .address().segments(dsAdr).segment(dsPropsDmrResourceType, prop.getKey()).parentBuilder() //
                    .attribute(ModelDescriptionConstants.VALUE, prop.getValue()).parentBuilder();
        }
    }

    OperationResult<?> opResult = batch.execute(controllerClient).assertSuccess();
    setServerRefreshIndicator(opResult, response);

    // discover the new datasource so it gets placed into inventory
    endpointService.discoverAll();

    return null;
}
 
开发者ID:hawkular,项目名称:hawkular-agent,代码行数:70,代码来源:AddDatasourceCommand.java

示例15: execute

import org.hawkular.bus.common.BinaryData; //导入依赖的package包/类
@Override
protected BinaryData execute(
        EndpointService<JMXNodeLocation, JMXSession> endpointService,
        String resourceId,
        BasicMessageWithExtraData<ExecuteOperationRequest> envelope,
        ExecuteOperationResponse response,
        CommandContext context) throws Exception {

    ExecuteOperationRequest request = envelope.getBasicMessage();

    ResourceManager<JMXNodeLocation> resourceManager = endpointService.getResourceManager();
    Resource<JMXNodeLocation> resource = resourceManager.getResource(new ID(resourceId));
    if (resource == null) {
        throw new IllegalArgumentException(
                String.format("Cannot execute operation: unknown resource [%s]", request.getResourceId()));
    }

    // find the operation we need to execute - make sure it exists and get the address for the resource to invoke
    JMXNodeLocation opLocation = null;
    Operation<JMXNodeLocation> theOperation = null;

    try (JMXSession session = endpointService.openSession()) {
        String requestedOpName = request.getOperationName();
        Collection<Operation<JMXNodeLocation>> ops = resource.getResourceType().getOperations();
        log.tracef("Searching for operation [%s] among operations [%s] for resource [%s].", requestedOpName, ops,
                resource.getID());
        for (Operation<JMXNodeLocation> op : ops) {
            if (requestedOpName.equals(op.getName().getNameString())) {
                opLocation = session.getLocationResolver().absolutize(resource.getLocation(), op.getLocation());
                theOperation = op;
                if (op.getModifies()) {
                    if (context.getAgentCoreEngine().isImmutable()) {
                        throw new IllegalStateException(
                                "Operation [" + requestedOpName + "] not allowed because the agent is immutable");
                    }
                }
                break;
            }
        }

        if (opLocation == null) {
            throw new IllegalArgumentException(
                    String.format("Cannot execute operation: unknown operation [%s] for resource [%s]",
                            request.getOperationName(), resource));
        }

        response.setOperationName(request.getOperationName());

        Map<String, String> argsMap = request.getParameters();
        if (argsMap == null) {
            argsMap = Collections.emptyMap();
        }
        List<OperationParam> opSignature = theOperation.getParameters();
        Object[] args = new Object[opSignature == null ? 0 : opSignature.size()];
        Class<?>[] signature = new Class<?>[opSignature == null ? 0 : opSignature.size()];

        int i = 0;
        for (OperationParam opParam : opSignature) {
            guessJavaType(opParam, argsMap.get(opParam.getName()), i++, args, signature);
        }

        ObjectName targetMBean = opLocation.getObjectName();
        String internalOpName = theOperation.getInternalName();
        JMXDriver jmxDriver = (JMXDriver) session.getDriver();
        Object results = jmxDriver.executeOperation(targetMBean, internalOpName, args, signature);
        if (results != null) {
            response.setMessage(results.toString());
        }
    }

    // because we don't know if the effects of the operation will alter inventory,
    // let's request a full discovery scan just in case.
    endpointService.discoverAll();

    return null;
}
 
开发者ID:hawkular,项目名称:hawkular-agent,代码行数:77,代码来源:ExecuteJMXOperationCommand.java


注:本文中的org.hawkular.bus.common.BinaryData类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。