Пример #1
0
  /** Use Staxon to convert JSON to an XML string */
  @Override
  protected Object doTransform(Object src, String enc) throws TransformerException {
    XMLInputFactory inputFactory = new JsonXMLInputFactory();
    inputFactory.setProperty(JsonXMLInputFactory.PROP_MULTIPLE_PI, false);
    TransformerInputs inputs = new TransformerInputs(this, src);
    Source source;
    try {
      if (inputs.getInputStream() != null) {
        source =
            new StAXSource(
                inputFactory.createXMLStreamReader(
                    inputs.getInputStream(), enc == null ? "UTF-8" : enc));
      } else {
        source = new StAXSource(inputFactory.createXMLStreamReader(inputs.getReader()));
      }

      XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
      return convert(source, outputFactory);
    } catch (Exception ex) {
      throw new TransformerException(this, ex);
    } finally {
      IOUtils.closeQuietly(inputs.getInputStream());
      IOUtils.closeQuietly(inputs.getReader());
    }
  }
Пример #2
0
  public boolean compareResults(Object expected, Object result) {
    if (expected == null && result == null) {
      return true;
    }

    if (expected == null || result == null) {
      return false;
    }

    if (expected instanceof Object[] && result instanceof Object[]) {
      return Arrays.equals((Object[]) expected, (Object[]) result);
    } else if (expected instanceof byte[] && result instanceof byte[]) {
      return Arrays.equals((byte[]) expected, (byte[]) result);
    }

    if (expected instanceof InputStream && result instanceof InputStream) {
      return IOUtils.toString((InputStream) expected)
          .equals(IOUtils.toString((InputStream) result));
    } else if (expected instanceof InputStream) {
      expected = IOUtils.toString((InputStream) expected);
    }

    // Special case for Strings: normalize comparison arguments
    if (expected instanceof String && result instanceof String) {
      expected = this.normalizeString((String) expected);
      result = this.normalizeString((String) result);
    }

    return expected.equals(result);
  }
Пример #3
0
 public Object doTransform(Object src, String encoding) throws TransformerException {
   byte[] buf;
   if (src instanceof String) {
     buf = src.toString().getBytes();
   } else if (src instanceof InputStream) {
     InputStream input = (InputStream) src;
     try {
       buf = IOUtils.toByteArray(input);
     } finally {
       IOUtils.closeQuietly(input);
     }
   } else {
     buf = (byte[]) src;
   }
   try {
     byte[] result = getTransformedBytes(buf);
     if (getReturnClass().equals(String.class)) {
       if (encoding != null) {
         try {
           return new String(result, encoding);
         } catch (UnsupportedEncodingException ex) {
           return new String(result);
         }
       } else {
         return new String(result);
       }
     } else {
       return result;
     }
   } catch (CryptoFailureException e) {
     throw new TransformerException(this, e);
   }
 }
  @Override
  protected void doSetUp() throws Exception {
    InputStream resourceStream = IOUtils.getResourceAsStream("cdcatalog-utf-8.xml", getClass());
    srcData = IOUtils.toString(resourceStream, "UTF-8").getBytes("UTF-8");

    resourceStream = IOUtils.getResourceAsStream("cdcatalog-us-ascii.xml", getClass());
    resultData = IOUtils.toString(resourceStream, "US-ASCII");
  }
Пример #5
0
 // @Override
 protected void doSetUp() throws Exception {
   org.dom4j.Document dom4jDoc =
       DocumentHelper.parseText(
           IOUtils.toString(
               IOUtils.getResourceAsStream("cdcatalog-utf-8.xml", getClass()), "UTF-8"));
   srcData = new DOMWriter().write(dom4jDoc);
   resultData =
       IOUtils.toString(
           IOUtils.getResourceAsStream("cdcatalog-us-ascii.xml", getClass()), "US-ASCII");
 }
Пример #6
0
  /**
   * This is something of a hack. Velocity loads files relative to the property
   * VelocityEngine.FILE_RESOURCE_LOADER_PATH. So if we can find the template ourselves then we can
   * infer what the property value should be so that velocity works ok.
   */
  private void inferVelocityLoaderPath(VelocityEngine ve) throws IOException {
    String defaultPath = (String) ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH);
    if (null == defaultPath || StringUtils.isEmpty(defaultPath)) {
      URL url = IOUtils.getResourceAsUrl(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass());
      if (FILE.equals(url.getProtocol())) {
        String path =
            FileUtils.getResourcePath(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE, getClass());
        if (!StringUtils.isEmpty(path)) {
          File fullPath = new File(path);
          File target = new File(MuleDocPostRenderer.DEFAULT_MULE_TEMPLATE);

          // drop trailing files until we are at the relative parent
          while (null != target && !StringUtils.isEmpty(target.getPath())) {
            env.log(fullPath.getPath() + " - " + target.getPath());
            target = target.getParentFile();
            fullPath = fullPath.getParentFile();
          }

          path = fullPath.getPath();
          if (path.endsWith("!")) {
            path = path + File.separator;
          }
          getEnv().log(VelocityEngine.FILE_RESOURCE_LOADER_PATH + " = " + path);
          ve.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, path);
        }
      } else if (JAR.equals(url.getProtocol())) {
        env.log(url.toString());
        ve.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
        ve.setProperty(MAGIC_VELOCITY_RESOURCE_LOADER, ClasspathResourceLoader.class.getName());
      }
    }
  }
Пример #7
0
  @Override
  public Object doTransform(Object src, String outputEncoding) throws TransformerException {
    try {
      if (src instanceof String) {
        return src.toString().getBytes(outputEncoding);
      } else if (src instanceof InputStream) {
        InputStream is = (InputStream) src;
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        try {
          IOUtils.copyLarge(is, byteOut);
        } finally {
          is.close();
        }
        return byteOut.toByteArray();
      } else if (src instanceof OutputHandler) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();

        try {
          ((OutputHandler) src).write(RequestContext.getEvent(), bytes);

          return bytes.toByteArray();
        } catch (IOException e) {
          throw new TransformerException(this, e);
        }
      }
    } catch (Exception e) {
      throw new TransformerException(this, e);
    }

    return super.doTransform(src, outputEncoding);
  }
Пример #8
0
  private void initTrustManagerFactory() throws InitialisationException {
    if (null != trustStoreName) {
      trustStorePassword = null == trustStorePassword ? "" : trustStorePassword;

      KeyStore trustStore;
      try {
        trustStore = KeyStore.getInstance(trustStoreType);
        InputStream is = IOUtils.getResourceAsStream(trustStoreName, getClass());
        if (null == is) {
          throw new FileNotFoundException(
              "Failed to load truststore from classpath or local file: " + trustStoreName);
        }
        trustStore.load(is, trustStorePassword.toCharArray());
      } catch (Exception e) {
        throw new InitialisationException(
            CoreMessages.failedToLoad("TrustStore: " + trustStoreName), e, this);
      }

      try {
        trustManagerFactory = TrustManagerFactory.getInstance(trustManagerAlgorithm);
        trustManagerFactory.init(trustStore);
      } catch (Exception e) {
        throw new InitialisationException(
            CoreMessages.failedToLoad("Trust Manager (" + trustManagerAlgorithm + ")"), e, this);
      }
    }
  }
Пример #9
0
  protected void parseChild(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    Element parent = (Element) element.getParentNode();
    String serviceName = parent.getAttribute(ATTRIBUTE_NAME);
    builder.addPropertyReference("service", serviceName);

    // Create a BeanDefinition for the nested object factory and set it a
    // property value for the component
    AbstractBeanDefinition objectFactoryBeanDefinition = new GenericBeanDefinition();
    objectFactoryBeanDefinition.setBeanClass(OBJECT_FACTORY_TYPE);
    objectFactoryBeanDefinition
        .getPropertyValues()
        .addPropertyValue(AbstractObjectFactory.ATTRIBUTE_OBJECT_CLASS, componentInstanceClass);
    objectFactoryBeanDefinition.setInitMethodName(Initialisable.PHASE_NAME);
    objectFactoryBeanDefinition.setDestroyMethodName(Disposable.PHASE_NAME);
    Map props = new HashMap();
    for (int i = 0; i < element.getAttributes().getLength(); i++) {
      Node n = element.getAttributes().item(i);
      props.put(n.getLocalName(), n.getNodeValue());
    }
    String returnData = null;

    NodeList list = element.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      if ("return-data".equals(list.item(i).getLocalName())) {
        Element rData = (Element) list.item(i);
        if (StringUtils.isNotEmpty(rData.getAttribute("file"))) {
          String file = rData.getAttribute("file");
          try {
            returnData = IOUtils.getResourceAsString(file, getClass());
          } catch (IOException e) {
            throw new BeanCreationException("Failed to load test-data resource: " + file, e);
          }
        } else {
          returnData = rData.getTextContent();
        }
      } else if ("callback".equals(list.item(i).getLocalName())) {
        Element ele = (Element) list.item(i);
        String c = ele.getAttribute("class");
        try {
          EventCallback cb = (EventCallback) ClassUtils.instanciateClass(c);
          props.put("eventCallback", cb);

        } catch (Exception e) {
          throw new BeanCreationException("Failed to load event-callback: " + c, e);
        }
      }
    }

    if (returnData != null) {
      props.put("returnData", returnData);
    }
    objectFactoryBeanDefinition.getPropertyValues().addPropertyValue("properties", props);

    builder.addPropertyValue("objectFactory", objectFactoryBeanDefinition);

    super.parseChild(element, parserContext, builder);
  }
Пример #10
0
  private void readPrivateKeyBundle() throws Exception {
    InputStream in = IOUtils.getResourceAsStream(secretKeyRingFileName, getClass());

    ExtendedKeyStore ring = (ExtendedKeyStore) ExtendedKeyStore.getInstance("OpenPGP/KeyRing");
    ring.load(in, null);

    in.close();

    secretKeyBundle = ring.getKeyBundle(secretAliasId);
  }
Пример #11
0
 public byte[] getPayloadForSerialization() throws Exception {
   if (message instanceof InputStream) {
     // message is an InputStream when the HTTP method was POST
     return IOUtils.toByteArray((InputStream) message);
   } else if (message instanceof Serializable) {
     // message is a String when the HTTP method was GET
     return SerializationUtils.serialize((Serializable) message);
   } else {
     throw new NotSerializableException(
         "Don't know how to serialize payload of type " + message.getClass().getName());
   }
 }
  /**
   * {@sample.xml ../../../doc/azure-blob-service-connector.xml.sample
   * azure-blog-service:downloadBlob}
   *
   * @param friend Name to be used to generate a greeting message.
   * @return A greeting message
   * @throws StorageException
   * @throws URISyntaxException
   */
  @Processor
  public void uploadBlob(String container, String fileName, InputStream fileStream)
      throws Exception {
    BlobContainerPermissions containerPermissions = new BlobContainerPermissions();
    containerPermissions.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);

    CloudBlobContainer blobContainer =
        this.config.getServiceClient().getContainerReference(container);
    blobContainer.createIfNotExists();
    blobContainer.uploadPermissions(containerPermissions);

    CloudBlockBlob blob = blobContainer.getBlockBlobReference(fileName);
    blob.uploadText(IOUtils.toString(fileStream, "UTF-8"));
  }
Пример #13
0
 public Object read(InputStream in) throws MuleException {
   if (inboundTransformer == null) {
     throw new IllegalArgumentException(
         CoreMessages.objectIsNull("inboundTransformer").getMessage());
   }
   if (inboundTransformer.isSourceTypeSupported(InputStream.class)) {
     return inboundTransformer.transform(in);
   } else {
     try {
       ByteArrayOutputStream baos = new ByteArrayOutputStream();
       IOUtils.copy(in, baos);
       return inboundTransformer.transform(baos.toByteArray());
     } catch (IOException e) {
       throw new DefaultMuleException(CoreMessages.failedToReadPayload(), e);
     }
   }
 }
Пример #14
0
  @Override
  protected void doInitialise() throws InitialisationException {
    logger.debug("Initialising transformer: " + this);
    try {
      // Only load the file once at initialize time
      if (xslFile != null) {
        this.xslt = IOUtils.getResourceAsString(xslFile, getClass());
      }

      if (uriResolver == null) {
        this.uriResolver = new LocalURIResolver(xslFile);
      }

      transformerPool.addObject();
    } catch (Throwable te) {
      throw new InitialisationException(te, this);
    }
  }
Пример #15
0
  private void readPublicKeyRing() throws Exception {
    logger.debug(System.getProperties().get("user.dir"));
    InputStream in = IOUtils.getResourceAsStream(publicKeyRingFileName, getClass());

    ExtendedKeyStore ring = (ExtendedKeyStore) ExtendedKeyStore.getInstance("OpenPGP/KeyRing");
    ring.load(in, null);
    in.close();

    for (Enumeration e = ring.aliases(); e.hasMoreElements(); ) {
      String aliasId = (String) e.nextElement();

      KeyBundle bundle = ring.getKeyBundle(aliasId);

      if (bundle != null) {
        for (Iterator users = bundle.getPrincipals(); users.hasNext(); ) {
          Principal princ = (Principal) users.next();

          principalsKeyBundleMap.put(princ.getName(), bundle);
        }
      }
    }
  }
  protected <T> T deserializeJsonToEntity(
      final TypeReference<T> responseType, final MuleMessage response) throws MuleException {
    try {
      T entity;

      if (logger.isDebugEnabled()) {
        response.setPayload(IOUtils.toByteArray((InputStream) response.getPayload()));
        entity = OBJECT_MAPPER.<T>readValue((byte[]) response.getPayload(), responseType);
      } else {
        entity = OBJECT_MAPPER.<T>readValue((InputStream) response.getPayload(), responseType);
      }

      return entity;
    } catch (final IOException ioe) {
      throw new DefaultMuleException(
          "Failed to deserialize to: "
              + responseType.getType()
              + " from: "
              + renderMessageAsString(response),
          ioe);
    }
  }
Пример #17
0
 private void initKeyManagerFactory() throws InitialisationException {
   if (logger.isDebugEnabled()) {
     logger.debug("initialising key manager factory from keystore data");
   }
   KeyStore tempKeyStore;
   try {
     tempKeyStore = KeyStore.getInstance(keystoreType);
     InputStream is = IOUtils.getResourceAsStream(keyStoreName, getClass());
     if (null == is) {
       throw new FileNotFoundException(
           CoreMessages.cannotLoadFromClasspath("Keystore: " + keyStoreName).getMessage());
     }
     tempKeyStore.load(is, keyStorePassword.toCharArray());
   } catch (Exception e) {
     throw new InitialisationException(
         CoreMessages.failedToLoad("KeyStore: " + keyStoreName), e, this);
   }
   try {
     keyManagerFactory = KeyManagerFactory.getInstance(getKeyManagerAlgorithm());
     keyManagerFactory.init(tempKeyStore, keyPassword.toCharArray());
   } catch (Exception e) {
     throw new InitialisationException(CoreMessages.failedToLoad("Key Manager"), e, this);
   }
 }
Пример #18
0
    protected MessageAdapter buildStandardAdapter(final HttpRequest request, final Map headers)
        throws MuleException, TransformerException, IOException {
      final RequestLine requestLine = request.getRequestLine();

      sendExpect100(headers, requestLine);

      Object body = request.getBody();

      // If http method is GET we use the request uri as the payload.
      if (body == null) {
        body = requestLine.getUri();
      } else {
        // If we are running async we need to read stream into a byte[].
        // Passing along the InputStream doesn't work because the
        // HttpConnection gets closed and closes the InputStream, often
        // before it can be read.
        if (!endpoint.isSynchronous()) {
          logger.debug("Reading HTTP POST InputStream into byte[] for asynchronous messaging.");
          body = IOUtils.toByteArray((InputStream) body);
        }
      }

      return connector.getMessageAdapter(new Object[] {body, headers});
    }
Пример #19
0
 protected InputStream load(String name) throws IOException {
   InputStream stream = IOUtils.getResourceAsStream(name, getClass());
   assertNotNull("Cannot load " + name, stream);
   return stream;
 }
Пример #20
0
 public static InputStream toInputStream(String resource) throws IOException {
   return IOUtils.getResourceAsStream(resource, XMLTestUtils.class);
 }
Пример #21
0
 public static String toString(String resource) throws IOException {
   return IOUtils.getResourceAsString(resource, XMLTestUtils.class);
 }
Пример #22
0
  public void doInitialise() throws InitialisationException {
    if (getProvider() == null) {
      throw new NullPointerException("The security provider cannot be null");
    }
    if (getKeyStore() != null) {
      if (getKeyPassword() == null) {
        throw new NullPointerException("The Key password cannot be null");
      }
      if (getStorePassword() == null) {
        throw new NullPointerException("The KeyStore password cannot be null");
      }
      if (getKeyManagerAlgorithm() == null) {
        throw new NullPointerException("The Key Manager Algorithm cannot be null");
      }
      if (getKeyStoreType() == null) {
        throw new NullPointerException("The KeyStore type cannot be null");
      }
    }

    if (getKeyStore() != null) {
      KeyStore keystore;
      try {
        Security.addProvider(getProvider());
        // Create keyStore
        keystore = KeyStore.getInstance(keyStoreType);
        InputStream is = IOUtils.getResourceAsStream(getKeyStore(), getClass());
        if (is == null) {
          throw new FileNotFoundException(
              "Failed to load keystore from classpath or local file: " + getKeyStore());
        }
        keystore.load(is, getKeyPassword().toCharArray());
      } catch (Exception e) {
        throw new InitialisationException(
            new Message(Messages.FAILED_LOAD_X, "KeyStore: " + getKeyStore()), e, this);
      }
      try {
        // Get key manager
        keyManagerFactory = KeyManagerFactory.getInstance(getKeyManagerAlgorithm());
        // Initialize the KeyManagerFactory to work with our keyStore
        keyManagerFactory.init(keystore, getStorePassword().toCharArray());
      } catch (Exception e) {
        throw new InitialisationException(
            new Message(Messages.FAILED_LOAD_X, "Key Manager (" + getKeyManagerAlgorithm() + ")"),
            e,
            this);
      }
    }

    if (getTrustStore() != null) {
      KeyStore truststore;
      try {
        truststore = KeyStore.getInstance(trustStoreType);
        InputStream is = IOUtils.getResourceAsStream(getTrustStore(), getClass());
        if (is == null) {
          throw new FileNotFoundException(
              "Failed to load truststore from classpath or local file: " + getTrustStore());
        }
        truststore.load(is, getTrustStorePassword().toCharArray());
      } catch (Exception e) {
        throw new InitialisationException(
            new Message(Messages.FAILED_LOAD_X, "TrustStore: " + getTrustStore()), e, this);
      }

      try {
        trustManagerFactory = TrustManagerFactory.getInstance(getTrustManagerAlgorithm());
        trustManagerFactory.init(truststore);
      } catch (Exception e) {
        throw new InitialisationException(
            new Message(
                Messages.FAILED_LOAD_X, "Trust Manager (" + getTrustManagerAlgorithm() + ")"),
            e,
            this);
      }
    }

    super.doInitialise();

    if (protocolHandler != null) {
      System.setProperty("java.protocol.handler.pkgs", protocolHandler);
    }
    if (clientKeyStore != null) {
      try {
        String clientPath = FileUtils.getResourcePath(clientKeyStore, getClass());
        System.setProperty("javax.net.ssl.keyStore", clientPath);
        System.setProperty("javax.net.ssl.keyStorePassword", clientKeyStorePassword);

        logger.info("Set Client Key store: javax.net.ssl.keyStore=" + clientPath);
      } catch (IOException e) {
        throw new InitialisationException(
            new Message(Messages.FAILED_LOAD_X, "Client KeyStore: " + clientKeyStore), e, this);
      }
    }

    if (trustStore != null) {
      System.setProperty("javax.net.ssl.trustStore", getTrustStore());
      System.setProperty("javax.net.ssl.trustStorePassword", getTrustStorePassword());
      logger.debug("Set Trust store: javax.net.ssl.trustStore=" + getTrustStore());
    } else if (!isExplicitTrustStoreOnly()) {
      logger.info("Defaulting trust store to client Key Store");
      trustStore = getClientKeyStore();
      trustStorePassword = getClientKeyStorePassword();
      System.setProperty("javax.net.ssl.trustStore", getTrustStore());
      System.setProperty("javax.net.ssl.trustStorePassword", getTrustStorePassword());
      logger.debug("Set Trust store: javax.net.ssl.trustStore=" + getTrustStore());
    }
  }
Пример #23
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();
  }