/*
  * (non-Javadoc)
  *
  * @see javax.servlet.GenericServlet#init()
  */
 @Override
 public void init() throws ServletException {
   super.init();
   try {
     LoadTest.start();
     LOGGER.info("Server started successfully.");
     LoadTest.getLoadTestServer().logState();
   } catch (ServerStartupException e) {
     LoadTest.getLoadTestServer().setServerStartupError(e);
     List<String> messages = new ArrayList<String>();
     messages.add("!!!! SiteWhere Load Test Node Failed to Start !!!!");
     messages.add("");
     messages.add("Component: " + e.getDescription());
     messages.add("Error: " + e.getComponent().getLifecycleError().getMessage());
     String message = StringMessageUtils.getBoilerPlate(messages, '*', 60);
     LOGGER.info("\n" + message + "\n");
   } catch (SiteWhereException e) {
     List<String> messages = new ArrayList<String>();
     messages.add("!!!! SiteWhere Load Test Node Failed to Start !!!!");
     messages.add("");
     messages.add("Error: " + e.getMessage());
     String message = StringMessageUtils.getBoilerPlate(messages, '*', 60);
     LOGGER.info("\n" + message + "\n");
   } catch (Throwable e) {
     List<String> messages = new ArrayList<String>();
     messages.add("!!!! Unhandled Exception !!!!");
     messages.add("");
     messages.add("Error: " + e.getMessage());
     String message = StringMessageUtils.getBoilerPlate(messages, '*', 60);
     LOGGER.info("\n" + message + "\n");
   }
 }
示例#2
0
  public static Message invalidResourceType(Class expectedClass, Object object) {
    Class actualClass = null;
    if (object != null) {
      actualClass = object.getClass();
    }

    return factory.createMessage(
        BUNDLE_PATH,
        12,
        StringMessageUtils.toString(expectedClass),
        StringMessageUtils.toString(actualClass));
  }
示例#3
0
 public void run() {
   int i = 0;
   try {
     Thread.sleep(2000);
     MuleClient client = new MuleClient();
     MuleMessage result = null;
     for (i = 0; i < numberOfRequests; i++) {
       try {
         result = client.request("CustomerResponses", getDelay());
       } catch (MuleException e) {
         exListener.exceptionThrown(e);
         break;
       }
       // System.out.println("Received: " + i);
       assertNotNull("Result is null", result);
       assertFalse("Result is null", result.getPayload() instanceof NullPayload);
       assertTrue(
           "Result should be LoanQuote but is " + result.getPayload().getClass().getName(),
           result.getPayload() instanceof LoanQuote);
       LoanQuote quote = (LoanQuote) result.getPayload();
       assertTrue(quote.getInterestRate() > 0);
     }
   } catch (Throwable e) {
     // e.printStackTrace();
     System.out.println(StringMessageUtils.getBoilerPlate("Processed Messages=" + i));
     if (e instanceof Error) {
       // throw (Error)e;
       exListener.exceptionThrown(new Exception(e));
     } else {
       exListener.exceptionThrown((Exception) e);
     }
   } finally {
     latch.countDown();
   }
 }
 /** Check whether device model is populated and offer to bootstrap system if not. */
 protected void verifyDeviceModel() {
   try {
     IDeviceModelInitializer init =
         (IDeviceModelInitializer)
             SERVER_SPRING_CONTEXT.getBean(SiteWhereServerBeans.BEAN_DEVICE_MODEL_INITIALIZER);
     ISearchResults<ISite> sites = getDeviceManagement().listSites(new SearchCriteria(1, 1));
     if (sites.getNumResults() == 0) {
       List<String> messages = new ArrayList<String>();
       messages.add(
           "There are currently no sites defined in the system. You have the option of loading "
               + "a default dataset for previewing system functionality. Would you like to load the default "
               + "dataset?");
       String message = StringMessageUtils.getBoilerPlate(messages, '*', 60);
       LOGGER.info("\n" + message + "\n");
       System.out.println("Load default dataset? Yes/No (Default is Yes)");
       String response = readLine();
       if ((response == null) && (init.isInitializeIfNoConsole())) {
         response = "Y";
       } else if ((response == null) && (!init.isInitializeIfNoConsole())) {
         response = "N";
       }
       if ((response.length() == 0) || (response.toLowerCase().startsWith("y"))) {
         init.initialize(getDeviceManagement());
       }
     }
   } catch (NoSuchBeanDefinitionException e) {
     LOGGER.info("No device model initializer found in Spring bean configuration. Skipping.");
     return;
   } catch (SiteWhereException e) {
     LOGGER.warn("Unable to read from device model.", e);
   }
 }
 /** Check whether user model is populated and offer to bootstrap system if not. */
 protected void verifyUserModel() {
   try {
     IUserModelInitializer init =
         (IUserModelInitializer)
             SERVER_SPRING_CONTEXT.getBean(SiteWhereServerBeans.BEAN_USER_MODEL_INITIALIZER);
     List<IUser> users = getUserManagement().listUsers(new UserSearchCriteria());
     if (users.size() == 0) {
       List<String> messages = new ArrayList<String>();
       messages.add(
           "User model is currently empty. A default user and permissions can be "
               + "created automatically so that the admin interface and web services can authenticate. "
               + "Create default user and permissions now?");
       String message = StringMessageUtils.getBoilerPlate(messages, '*', 60);
       LOGGER.info("\n" + message + "\n");
       System.out.println("Initialize user model? Yes/No (Default is Yes)");
       String response = readLine();
       if ((response == null) && (init.isInitializeIfNoConsole())) {
         response = "Y";
       } else if ((response == null) && (!init.isInitializeIfNoConsole())) {
         response = "N";
       }
       if ((response.length() == 0) || (response.toLowerCase().startsWith("y"))) {
         init.initialize(getUserManagement());
       }
     }
   } catch (NoSuchBeanDefinitionException e) {
     LOGGER.info("No user model initializer found in Spring bean configuration. Skipping.");
     return;
   } catch (SiteWhereException e) {
     LOGGER.warn("Error verifying user model.", e);
   }
 }
示例#6
0
  protected static String getInteractiveConfig() throws IOException {
    System.out.println(
        StringMessageUtils.getBoilerPlate("Welcome to the Mule Loan Broker example"));

    int response = 0;
    String provider = "axis";

    while (response != 'a' && /* response != 'g' && */ response != 'x') {
      // System.out.println("\nWhich SOAP stack would you like to use: [a]xis,
      // [g]lue or [x]fire?");
      System.out.println("\nWhich SOAP stack would you like to use: [a]xis or [x]fire?");
      response = readCharacter();
      switch (response) {
        case 'a':
          {
            provider = "axis";
            break;
          }

          // TODO re-enable glue when the locahost/IP issue is fixed
          // case 'g':
          // {
          // provider = "glue";
          // break;
          // }

        case 'x':
          {
            provider = "xfire";
            break;
          }
      }
    }

    response = 0;
    while (response != 'a' && response != 's') {
      System.out.println("\nWould you like to run the [s]ynchronous or [a]synchronous version?");
      response = readCharacter();
      switch (response) {
        case 'a':
          {
            System.out.println("Loading Asynchronous Loan Broker");
            synchronous = false;
            break;
          }

        case 's':
          {
            System.out.println("Loading Synchronous Loan Broker");
            synchronous = true;
            break;
          }
      }
    }

    String config =
        "loan-broker-" + provider + "-" + (synchronous ? "sync" : "async") + "-config.xml";
    return config;
  }
示例#7
0
 /**
  * Converts the message implementation into a String representation
  *
  * @param encoding The encoding to use when transforming the message (if necessary). The parameter
  *     is used when converting from a byte array
  * @return String representation of the message payload
  * @throws Exception Implementation may throw an endpoint specific exception
  */
 public String getPayloadAsString(String encoding) throws Exception {
   if (out instanceof ByteArrayOutputStream) {
     return StringMessageUtils.getString(((ByteArrayOutputStream) out).toByteArray(), encoding);
   } else {
     logger.warn("Attempting to get the String contents of a non-ByteArray output stream");
     return out.toString();
   }
 }
示例#8
0
 /**
  * Converts the message implementation into a String representation
  *
  * @return String representation of the message
  * @throws Exception Implemetation may throw an endpoint specific exception
  */
 public byte[] getPayloadAsBytes() throws Exception {
   if (out instanceof ByteArrayOutputStream) {
     return ((ByteArrayOutputStream) out).toByteArray();
   } else {
     logger.warn("Attempting to get the bytes of a non-ByteArray output stream");
     return StringMessageUtils.getBytes(out.toString());
   }
 }
  /**
   * Create the server.
   *
   * @throws SiteWhereException
   */
  public void create() throws SiteWhereException {
    LOGGER.info("Initializing SiteWhere server components.");
    File sitewhereConf = getSiteWhereConfigFolder();

    // Load server configuration.
    LOGGER.info("Loading Spring configuration ...");
    File serverConfigFile = new File(sitewhereConf, SERVER_CONFIG_FILE_NAME);
    if (!serverConfigFile.exists()) {
      throw new SiteWhereException(
          "SiteWhere server configuration not found: " + serverConfigFile.getAbsolutePath());
    }
    SERVER_SPRING_CONTEXT = loadServerApplicationContext(serverConfigFile);

    // Load device management and wrap it for metrics.
    IDeviceManagement deviceManagementImpl =
        (IDeviceManagement)
            SERVER_SPRING_CONTEXT.getBean(SiteWhereServerBeans.BEAN_DEVICE_MANAGEMENT);
    if (deviceManagementImpl == null) {
      throw new SiteWhereException("No device management implementation configured.");
    }
    DeviceManagementMetricsFacade facade = new DeviceManagementMetricsFacade();
    facade.setDelegate(deviceManagementImpl);
    deviceManagement = facade;
    deviceManagement.start();

    // Load user management.
    userManagement =
        (IUserManagement) SERVER_SPRING_CONTEXT.getBean(SiteWhereServerBeans.BEAN_USER_MANAGEMENT);
    if (userManagement == null) {
      throw new SiteWhereException("No user management implementation configured.");
    }
    userManagement.start();

    // Load the asset module manager.
    assetModuleManager =
        (IAssetModuleManager)
            SERVER_SPRING_CONTEXT.getBean(SiteWhereServerBeans.BEAN_ASSET_MODULE_MANAGER);
    if (assetModuleManager == null) {
      throw new SiteWhereException("No asset module manager implementation configured.");
    }

    // Print version information.
    IVersion version = VersionHelper.getVersion();
    List<String> messages = new ArrayList<String>();
    messages.add("SiteWhere Server");
    messages.add("");
    messages.add("Version: " + version.getVersionIdentifier() + "." + version.getBuildTimestamp());
    messages.add("");
    messages.add("Copyright (c) 2013 Reveal Technologies, LLC");
    String message = StringMessageUtils.getBoilerPlate(messages, '*', 60);
    LOGGER.info("\n" + message + "\n");

    verifyUserModel();
    verifyDeviceModel();
  }
  public HzTransaction(MuleContext muleContext) {
    super(muleContext);
    try {
      this.hazelcastInstance = muleContext.getRegistry().lookupObject(HazelcastInstance.class);

    } catch (RegistrationException e) {

      logger.error(StringMessageUtils.getBoilerPlate("Hazel Cast Instance Not found " + e));
      throw new RuntimeException(e);
    }
  }
示例#11
0
  public Object onCall(UMOEventContext context) throws Exception {
    String contents = context.getTransformedMessageAsString();
    String msg =
        StringMessageUtils.getBoilerPlate(
            "Message Received in component: "
                + context.getComponentDescriptor().getName()
                + ". Content is: "
                + StringMessageUtils.truncate(contents, 100, true),
            '*',
            80);

    logger.info(msg);

    if (eventCallback != null) {
      eventCallback.eventReceived(context, this);
    }

    Object replyMessage;
    if (returnMessage != null) {
      replyMessage = returnMessage;
    } else {
      replyMessage =
          contents
              + " Received"
              + (appendComponentName ? " " + context.getComponentDescriptor().getName() : "");
    }

    MuleManager.getInstance()
        .fireNotification(
            new FunctionalTestNotification(
                context, replyMessage, FunctionalTestNotification.EVENT_RECEIVED));

    if (throwException) {
      throw new MuleException(Message.createStaticMessage("Functional Test Component Exception"));
    }

    return replyMessage;
  }
示例#12
0
  public static void main(String[] args) {
    LoanConsumer loanConsumer = null;
    try {
      String config = SystemUtils.getCommandLineOption("-config", args);
      if (StringUtils.isNotBlank(config)) {
        loanConsumer = new LoanConsumer(config);

        int i = 100;
        String requests = SystemUtils.getCommandLineOption("-req", args);
        if (requests != null) {
          i = Integer.parseInt(requests);
        }

        String sync = SystemUtils.getCommandLineOption("-sync", args);
        if (sync != null) {
          synchronous = Boolean.valueOf(sync).booleanValue();
        }

        if (synchronous) {
          long start = System.currentTimeMillis();
          List results = loanConsumer.requestSend(i, "vm://LoanBrokerRequests");
          System.out.println("Number or quotes received: " + results.size());
          List output = new ArrayList(results.size());
          int x = 1;
          for (Iterator iterator = results.iterator(); iterator.hasNext(); x++) {
            LoanQuote quote = (LoanQuote) iterator.next();
            output.add(x + ". " + quote.toString());
          }
          System.out.println(StringMessageUtils.getBoilerPlate(output, '*', 80));
          long cur = System.currentTimeMillis();
          System.out.println(DateUtils.getFormattedDuration(cur - start));
          System.out.println("Avg request: " + ((cur - start) / x));
        } else {
          loanConsumer.requestDispatch(i, "vm://LoanBrokerRequests");
        }
      } else {
        loanConsumer = new LoanConsumer(getInteractiveConfig());
        loanConsumer.run(synchronous);
      }

    } catch (Exception e) {
      System.err.println(e.getMessage());
      e.printStackTrace(System.err);
      System.exit(1);
    }
  }
示例#13
0
  public OutStreamMessageAdapter(Object message) throws MessageTypeNotSupportedException {
    try {
      if (message instanceof OutputStream) {
        out = (OutputStream) message;
      } else if (message instanceof String) {
        out = new ByteArrayOutputStream(message.toString().length());
        out.write(StringMessageUtils.getBytes(message.toString()));
      } else if (message instanceof byte[]) {
        out = new ByteArrayOutputStream(((byte[]) message).length);
        out.write((byte[]) message);

      } else {
        throw new MessageTypeNotSupportedException(message, getClass());
      }
    } catch (IOException e) {
      throw new MessageTypeNotSupportedException(message, getClass(), e);
    }
  }
示例#14
0
 public void write(String string, int offset, int len) throws IOException {
   out.write(StringMessageUtils.getBytes(string), offset, len);
 }
示例#15
0
 public void write(String string) throws IOException {
   out.write(StringMessageUtils.getBytes(string));
 }
示例#16
0
  private boolean accept(Object obj) {
    if (obj == null) {
      logger.warn("Applying JXPathFilter to null object.");
      return false;
    }
    if (pattern == null) {
      logger.warn("Expression for JXPathFilter is not set.");
      return false;
    }
    if (expectedValue == null) {
      // Handle the special case where the expected value really is null.
      if (pattern.endsWith("= null") || pattern.endsWith("=null")) {
        expectedValue = "null";
        pattern = pattern.substring(0, pattern.lastIndexOf("="));
      } else {
        if (logger.isInfoEnabled()) {
          logger.info("Expected value for JXPathFilter is not set, using 'true' by default");
        }
        expectedValue = Boolean.TRUE.toString();
      }
    }

    Object xpathResult = null;
    boolean accept = false;

    // Payload is a DOM Document
    if (obj instanceof Document) {
      if (namespaces == null) {
        // no namespace defined, let's perform a direct evaluation
        xpathResult = ((Document) obj).valueOf(pattern);
      } else {
        // create an xpath expression with namespaces and evaluate it
        XPath xpath = DocumentHelper.createXPath(pattern);
        xpath.setNamespaceURIs(namespaces);
        xpathResult = xpath.valueOf(obj);
      }

    }
    // Payload is a String of XML
    else if (obj instanceof String) {
      try {
        return accept(DocumentHelper.parseText((String) obj));
      } catch (DocumentException e) {
        logger.warn("JXPathFilter unable to parse XML document: " + e.getMessage(), e);
        if (logger.isDebugEnabled())
          logger.debug("XML = " + StringMessageUtils.truncate((String) obj, 200, false));
        return false;
      }
    }
    // Payload is a Java object
    else {
      if (logger.isDebugEnabled()) {
        logger.debug("Passing object of type " + obj.getClass().getName() + " to JXPathContext");
      }
      JXPathContext context = JXPathContext.newContext(obj);
      initialise(context);
      xpathResult = context.getValue(pattern);
    }

    if (logger.isDebugEnabled()) {
      logger.debug(
          "JXPathFilter Expression result = '"
              + xpathResult
              + "' -  Expected value = '"
              + expectedValue
              + "'");
    }
    // Compare the XPath result with the expected result.
    if (xpathResult != null) {
      accept = xpathResult.toString().equals(expectedValue);
    } else {
      // A null result was actually expected.
      if (expectedValue.equals("null")) {
        accept = true;
      }
      // A null result was not expected, something probably went wrong.
      else {
        logger.warn("JXPathFilter expression evaluates to null: " + pattern);
      }
    }

    if (logger.isDebugEnabled()) {
      logger.debug("JXPathFilter accept object  : " + accept);
    }

    return accept;
  }
示例#17
0
 public void processException(ErrorMessage message, Throwable t) throws HandlerException {
   String msg = LocaleMessage.defaultHandlerMessage();
   System.out.println(StringMessageUtils.getBoilerPlate(msg));
 }
示例#18
0
  public Object transform(UMOMessage message, String outputEncoding) throws TransformerException {
    Object src = message.getPayload();

    String data = src.toString();
    if (src instanceof InputStream) {
      InputStream is = (InputStream) src;
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      try {
        try {
          IOUtils.copy(is, bos);
        } finally {
          is.close();
        }
      } catch (IOException e) {
        throw new TransformerException(this, e);
      }

      src = bos.toByteArray();
    }

    if (src instanceof byte[]) {
      try {
        data = new String((byte[]) src, outputEncoding);
      } catch (UnsupportedEncodingException e) {
        throw new TransformerException(this, e);
      }
      // Data is already Xml
      if (data.startsWith("<") || data.startsWith("&lt;")) {
        return data;
      }
    }

    String httpMethod = message.getStringProperty("http.method", "GET");
    String request = message.getStringProperty("http.request", null);

    int i = request.indexOf('?');
    String query = request.substring(i + 1);
    Properties p = PropertiesUtils.getPropertiesFromQueryString(query);

    String method = (String) p.remove(MuleProperties.MULE_METHOD_PROPERTY);
    if (method == null) {
      throw new TransformerException(
          CoreMessages.propertiesNotSet(MuleProperties.MULE_METHOD_PROPERTY), this);
    }

    if (httpMethod.equals("POST")) {
      p.setProperty(method, data);
    }

    StringBuffer result = new StringBuffer(8192);
    String header =
        StringMessageUtils.getFormattedMessage(SOAP_HEADER, new Object[] {outputEncoding});

    result.append(header);
    result.append('<').append(method).append(" xmlns=\"");
    result.append(DEFAULT_NAMESPACE).append("\">");
    for (Iterator iterator = p.entrySet().iterator(); iterator.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iterator.next();
      result.append('<').append(entry.getKey()).append('>');
      result.append(entry.getValue());
      result.append("</").append(entry.getKey()).append('>');
    }
    result.append("</").append(method).append('>');
    result.append(SOAP_FOOTER);

    return result.toString();
  }
示例#19
0
  @Override
  public void processReplyTo(MuleEvent event, MuleMessage returnMessage, Object replyTo)
      throws MuleException {
    Destination replyToDestination = null;
    MessageProducer replyToProducer = null;
    Session session = null;
    try {
      // now we need to send the response
      if (replyTo instanceof Destination) {
        replyToDestination = (Destination) replyTo;
      }
      if (replyToDestination == null) {
        super.processReplyTo(event, returnMessage, replyTo);
        return;
      }

      // This is a work around for JmsTransformers where the current endpoint needs
      // to be set on the transformer so that a JMSMessage can be created correctly (the transformer
      // needs a Session)
      Class srcType = returnMessage.getPayload().getClass();
      for (Iterator iterator = getTransformers().iterator(); iterator.hasNext(); ) {
        Transformer t = (Transformer) iterator.next();
        if (t.isSourceDataTypeSupported(DataTypeFactory.create(srcType))) {
          if (t.getEndpoint() == null) {
            t.setEndpoint(getEndpoint(event, "jms://temporary"));
            break;
          }
        }
      }
      returnMessage.applyTransformers(getTransformers());
      Object payload = returnMessage.getPayload();

      if (replyToDestination instanceof Topic
          && replyToDestination instanceof Queue
          && connector.getJmsSupport() instanceof Jms102bSupport) {
        logger.error(
            StringMessageUtils.getBoilerPlate(
                "ReplyTo destination implements both Queue and Topic "
                    + "while complying with JMS 1.0.2b specification. "
                    + "Please report your application server or JMS vendor name and version "
                    + "to dev<_at_>mule.codehaus.org or http://mule.mulesource.org/jira"));
      }

      final boolean topic = connector.getTopicResolver().isTopic(replyToDestination);
      session = connector.getSession(false, topic);
      Message replyToMessage = JmsMessageUtils.toMessage(payload, session);

      processMessage(replyToMessage, event);
      if (logger.isDebugEnabled()) {
        logger.debug(
            "Sending jms reply to: "
                + replyToDestination
                + "("
                + replyToDestination.getClass().getName()
                + ")");
      }
      replyToProducer =
          connector.getJmsSupport().createProducer(session, replyToDestination, topic);

      // QoS support
      MuleMessage eventMsg = event.getMessage();
      String ttlString = (String) eventMsg.removeProperty(JmsConstants.TIME_TO_LIVE_PROPERTY);
      String priorityString = (String) eventMsg.removeProperty(JmsConstants.PRIORITY_PROPERTY);
      String persistentDeliveryString =
          (String) eventMsg.removeProperty(JmsConstants.PERSISTENT_DELIVERY_PROPERTY);

      String correlationIDString = replyToMessage.getJMSCorrelationID();
      if (StringUtils.isBlank(correlationIDString)) {
        correlationIDString = (String) eventMsg.getProperty(JmsConstants.JMS_MESSAGE_ID);
        replyToMessage.setJMSCorrelationID(correlationIDString);
      }

      event.getService().getStatistics().incSentReplyToEvent();

      final ImmutableEndpoint endpoint = event.getEndpoint();
      if (ttlString == null && priorityString == null && persistentDeliveryString == null) {
        connector.getJmsSupport().send(replyToProducer, replyToMessage, topic, endpoint);
      } else {
        long ttl = Message.DEFAULT_TIME_TO_LIVE;
        int priority = Message.DEFAULT_PRIORITY;

        if (ttlString != null) {
          ttl = Long.parseLong(ttlString);
        }
        if (priorityString != null) {
          priority = Integer.parseInt(priorityString);
        }
        boolean persistent =
            StringUtils.isNotBlank(persistentDeliveryString)
                ? Boolean.valueOf(persistentDeliveryString)
                : connector.isPersistentDelivery();

        connector
            .getJmsSupport()
            .send(replyToProducer, replyToMessage, persistent, priority, ttl, topic, endpoint);
      }

      logger.info(
          "Reply Message sent to: "
              + replyToDestination
              + " with correlationID:"
              + correlationIDString);
    } catch (Exception e) {
      throw new DispatchException(
          JmsMessages.failedToCreateAndDispatchResponse(replyToDestination),
          returnMessage,
          null,
          e);
    } finally {
      connector.closeQuietly(replyToProducer);

      final Transaction transaction = TransactionCoordination.getInstance().getTransaction();
      if (transaction == null) {
        if (logger.isDebugEnabled()) {
          logger.debug("Closing non-TX replyTo session: " + session);
        }
        connector.closeQuietly(session);
      } else if (logger.isDebugEnabled()) {
        logger.debug("Not closing TX replyTo session: " + session);
      }
    }
  }