コード例 #1
1
    /**
     * Called for an incoming message.
     *
     * @param inMessage
     */
    public void onMessage(Message inMessage) {
      // disposable exchange, swapped with real Exchange on correlation
      inMessage.setExchange(new ExchangeImpl());
      inMessage.getExchange().put(Bus.class, bus);
      inMessage.put(Message.DECOUPLED_CHANNEL_MESSAGE, Boolean.TRUE);
      inMessage.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_OK);

      // remove server-specific properties
      // inMessage.remove(AbstractHTTPDestination.HTTP_REQUEST);
      // inMessage.remove(AbstractHTTPDestination.HTTP_RESPONSE);
      inMessage.remove(Message.ASYNC_POST_RESPONSE_DISPATCH);
      updateResponseCode(inMessage);

      // cache this inputstream since it's defer to use in case of async
      try {
        InputStream in = inMessage.getContent(InputStream.class);
        if (in != null) {
          CachedOutputStream cos = new CachedOutputStream();
          IOUtils.copy(in, cos);
          inMessage.setContent(InputStream.class, cos.getInputStream());
        }
        observer.onMessage(inMessage);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
コード例 #2
1
  /* (non-Javadoc)
   * @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
   */
  @Override
  public Event mapRow(ResultSet rs, int rowNum) throws SQLException {
    Event event = new Event();
    event.setPersistedId(rs.getLong("ID"));
    event.setTimestamp(rs.getTimestamp("EI_TIMESTAMP"));
    event.setEventType(EventTypeEnum.valueOf(rs.getString("EI_EVENT_TYPE")));

    Originator originator = new Originator();
    originator.setProcessId(rs.getString("ORIG_PROCESS_ID"));
    originator.setIp(rs.getString("ORIG_IP"));
    originator.setHostname(rs.getString("ORIG_HOSTNAME"));
    originator.setCustomId(rs.getString("ORIG_CUSTOM_ID"));
    originator.setPrincipal(rs.getString("ORIG_PRINCIPAL"));
    event.setOriginator(originator);

    MessageInfo messageInfo = new MessageInfo();
    messageInfo.setMessageId(rs.getString("MI_MESSAGE_ID"));
    messageInfo.setFlowId(rs.getString("MI_FLOW_ID"));
    messageInfo.setPortType(rs.getString("MI_PORT_TYPE"));
    messageInfo.setOperationName(rs.getString("MI_OPERATION_NAME"));
    messageInfo.setTransportType(rs.getString("MI_TRANSPORT_TYPE"));
    event.setMessageInfo(messageInfo);
    event.setContentCut(rs.getBoolean("CONTENT_CUT"));
    try {
      event.setContent(IOUtils.toString(rs.getClob("MESSAGE_CONTENT").getAsciiStream()));
    } catch (IOException e) {
      throw new RuntimeException("Error reading content", e);
    }
    return event;
  }
コード例 #3
0
  /**
   * Tests that, when 'mark-generated' option is set, @Generated annotations are inserted in all
   * generated java classes.
   */
  @Test
  public void testMarkGeneratedOption() throws Exception {
    env.put(ToolConstants.CFG_WSDLURL, getLocation("/wsdl2java_wsdl/hello_world.wsdl"));
    env.put(ToolConstants.CFG_MARK_GENERATED, "true");
    env.put(ToolConstants.CFG_COMPILE, null);
    env.put(ToolConstants.CFG_CLASSDIR, null);
    processor.setContext(env);
    processor.execute();

    File dir = new File(output, "org");
    assertTrue("org directory is not found", dir.exists());
    dir = new File(dir, "apache");
    assertTrue("apache directory is not found", dir.exists());
    dir = new File(dir, "cxf");
    assertTrue("cxf directory is not found", dir.exists());
    dir = new File(dir, "w2j");
    assertTrue("w2j directory is not found", dir.exists());
    dir = new File(dir, "hello_world_soap_http");
    assertTrue("hello_world_soap_http directory is not found", dir.exists());
    File types = new File(dir, "types");
    assertTrue("types directory is not found", dir.exists());

    String str = IOUtils.readStringFromStream(new FileInputStream(new File(dir, "Greeter.java")));
    assertEquals(7, countGeneratedAnnotations(str));
    str = IOUtils.readStringFromStream(new FileInputStream(new File(types, "SayHi.java")));
    assertEquals(1, countGeneratedAnnotations(str));
    str = IOUtils.readStringFromStream(new FileInputStream(new File(types, "SayHiResponse.java")));
    assertEquals(4, countGeneratedAnnotations(str));
  }
コード例 #4
0
    @SuppressWarnings("unchecked")
    public void process(Exchange exchange) throws Exception {
      CxfPayload<SoapHeader> in = exchange.getIn().getBody(CxfPayload.class);

      // verify request
      assertEquals(1, in.getBody().size());

      Map<String, String> ns = new HashMap<String, String>();
      ns.put("ns", MtomTestHelper.SERVICE_TYPES_NS);
      ns.put("xop", MtomTestHelper.XOP_NS);

      XPathUtils xu = new XPathUtils(ns);
      Element body = new XmlConverter().toDOMElement(in.getBody().get(0));
      Element ele =
          (Element) xu.getValue("//ns:Detail/ns:photo/xop:Include", body, XPathConstants.NODE);
      String photoId = ele.getAttribute("href").substring(4); // skip "cid:"
      assertEquals(MtomTestHelper.REQ_PHOTO_CID, photoId);

      ele = (Element) xu.getValue("//ns:Detail/ns:image/xop:Include", body, XPathConstants.NODE);
      String imageId = ele.getAttribute("href").substring(4); // skip "cid:"
      assertEquals(MtomTestHelper.REQ_IMAGE_CID, imageId);

      DataHandler dr = exchange.getIn().getAttachment(photoId);
      assertEquals("application/octet-stream", dr.getContentType());
      MtomTestHelper.assertEquals(
          MtomTestHelper.REQ_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream()));

      dr = exchange.getIn().getAttachment(imageId);
      assertEquals("image/jpeg", dr.getContentType());
      MtomTestHelper.assertEquals(
          MtomTestHelper.requestJpeg, IOUtils.readBytesFromStream(dr.getInputStream()));

      // create response
      List<Source> elements = new ArrayList<Source>();
      elements.add(
          new DOMSource(
              DOMUtils.readXml(new StringReader(MtomTestHelper.RESP_MESSAGE))
                  .getDocumentElement()));
      CxfPayload<SoapHeader> sbody =
          new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(), elements, null);
      exchange.getOut().setBody(sbody);
      exchange
          .getOut()
          .addAttachment(
              MtomTestHelper.RESP_PHOTO_CID,
              new DataHandler(
                  new ByteArrayDataSource(
                      MtomTestHelper.RESP_PHOTO_DATA, "application/octet-stream")));

      exchange
          .getOut()
          .addAttachment(
              MtomTestHelper.RESP_IMAGE_CID,
              new DataHandler(new ByteArrayDataSource(MtomTestHelper.responseJpeg, "image/jpeg")));
    }
  public void handleMessage(Message message) throws Fault {
    // check the fault from the message
    Throwable ex = message.getContent(Throwable.class);
    if (ex != null) {
      if (ex instanceof Fault) {
        throw (Fault) ex;
      } else {
        throw new Fault(ex);
      }
    }

    List<?> params = message.getContent(List.class);
    if (null != params) {
      InputStream is = (InputStream) params.get(0);
      OutputStream os = message.getContent(OutputStream.class);
      try {
        if (is instanceof StreamCache) {
          ((StreamCache) is).writeTo(os);
        } else {
          IOUtils.copy(is, os);
        }
      } catch (Exception e) {
        throw new Fault(e);
      } finally {
        IOHelper.close(is, "input stream", null);
        // Should not close the output stream as the interceptor chain will close it
      }
    }
  }
コード例 #6
0
  public boolean removeUserCredentialsForPaaS(String userInstanceUriId, String paaSInstanceUriId)
      throws SOAException {
    String rsUri = getBASE_URI() + "removeUserCredentialsForPaaS";

    WebClient client = WebClient.create(rsUri);
    client.type("multipart/mixed").accept(MediaType.TEXT_PLAIN);

    registerJsonProvider();

    List<Attachment> atts = new LinkedList<Attachment>();

    atts.add(new Attachment("userInstanceUriId", MediaType.TEXT_PLAIN, userInstanceUriId));

    atts.add(new Attachment("paaSInstanceUriId", MediaType.TEXT_PLAIN, paaSInstanceUriId));

    Response response = client.post(new MultipartBody(atts));

    if (Response.Status.fromStatusCode(response.getStatus()) == Response.Status.ACCEPTED) {
      try {
        String responseString = IOUtils.readStringFromStream((InputStream) response.getEntity());
        logger.debug("Response Status ACCEPTED - " + responseString);
      } catch (IOException ex) {
        logger.error("Error reading the REST response: " + ex.getMessage());
      }
      return true;
    }
    return false;
  }
コード例 #7
0
  @Test
  public void testEncoding() throws Exception {
    try {
      CodeWriter.class.getDeclaredField("encoding");
    } catch (Throwable t) {
      // version of jaxb that doesn't support this.  We'll just not run the test.
      return;
    }
    env.put(ToolConstants.CFG_WSDLURL, getLocation("/wsdl2java_wsdl/hello_world_encoding.wsdl"));
    env.put(ToolConstants.CFG_WSDLLOCATION, "/wsdl2java_wsdl/hello_world_encoding.wsdl");
    env.put(ToolConstants.CFG_ENCODING, "Cp1251");
    processor.setContext(env);
    processor.execute();

    File dir = new File(output, "org");
    assertTrue("org directory is not found", dir.exists());
    dir = new File(dir, "apache");
    assertTrue("apache directory is not found", dir.exists());
    dir = new File(dir, "cxf");
    assertTrue("cxf directory is not found", dir.exists());
    dir = new File(dir, "w2j");
    assertTrue("w2j directory is not found", dir.exists());
    dir = new File(dir, "hello_world_soap_http");
    assertTrue("hello_world_soap_http directory is not found", dir.exists());

    String str =
        IOUtils.readStringFromStream(new FileInputStream(new File(dir, "SOAPService.java")));
    assertTrue(str, str.contains("getResource"));

    Class<?> clz = classLoader.loadClass("org.apache.cxf.w2j.hello_world_soap_http.Greeter");
    for (Method m : clz.getMethods()) {
      String s = m.getName();
      assertEquals(1039, s.charAt(2));
    }
  }
コード例 #8
0
  public String storeTurtleUserProfile(String userProfile, String username, String password) {
    String rsUri = getBASE_URI() + "createNewUserAccount";

    WebClient client = WebClient.create(rsUri);
    client.type("multipart/mixed").accept(MediaType.TEXT_PLAIN);

    registerJsonProvider();

    List<Attachment> atts = new LinkedList<Attachment>();

    atts.add(new Attachment("userProfile", MediaType.TEXT_PLAIN, userProfile));

    atts.add(new Attachment("username", MediaType.TEXT_PLAIN, username));

    atts.add(new Attachment("password", MediaType.TEXT_PLAIN, password));

    Response response = client.post(new MultipartBody(atts));
    String userInstanceUriId = null;
    if (Response.Status.fromStatusCode(response.getStatus()) == Response.Status.CREATED) {
      try {
        userInstanceUriId = IOUtils.readStringFromStream((InputStream) response.getEntity());
        logger.debug("Response Status CREATED - userInstanceUriId: " + userInstanceUriId);
      } catch (IOException ex) {
        logger.error("Error reading the REST response: " + ex.getMessage());
      }
    }
    return userInstanceUriId;
  }
コード例 #9
0
    private void doInvoke(String actualBookName, String actualHeaderName) throws Exception {
      Response response = client.post(actualBookName);

      assertEquals(actualHeaderName, response.getMetadata().getFirst("CustomHeader").toString());
      String responseValue = IOUtils.readStringFromStream((InputStream) response.getEntity());
      assertEquals(actualBookName, responseValue);
    }
コード例 #10
0
  protected void handle(Message message) throws SequenceFault, RMException {
    LOG.entering(getClass().getName(), "handleMessage");
    // This message capturing mechanism will need to be changed at some point.
    // Until then, we keep this interceptor here and utilize the robust
    // option to avoid the unnecessary message capturing/caching.
    if (!MessageUtils.isTrue(message.getContextualProperty(Message.ROBUST_ONEWAY))) {
      InputStream is = message.getContent(InputStream.class);
      if (is != null) {
        CachedOutputStream saved = new CachedOutputStream();
        try {
          IOUtils.copy(is, saved);

          saved.flush();
          is.close();
          saved.lockOutputStream();

          LOG.fine("Capturing the original RM message");
          RewindableInputStream ris = RewindableInputStream.makeRewindable(saved.getInputStream());
          message.setContent(InputStream.class, ris);
          message.put(RMMessageConstants.SAVED_CONTENT, ris);
        } catch (Exception e) {
          throw new Fault(e);
        }
      }
    }
  }
コード例 #11
0
ファイル: BookStoreSpring.java プロジェクト: Evolveum/cxf
 @POST
 @Path("/bookform")
 @Consumes("application/xml")
 @Produces("application/xml")
 public String echoBookFormXml(@Context HttpServletRequest req) throws IOException {
   InputStream is = req.getInputStream();
   return IOUtils.readStringFromStream(is);
 }
コード例 #12
0
 private InputStream copyIn(InputStream in) throws Exception {
   try (CachedOutputStream bos = new CachedOutputStream()) {
     IOUtils.copyAndCloseInput(in, bos);
     in = bos.getInputStream();
     bos.close();
     return in;
   }
 }
コード例 #13
0
ファイル: HelloWorldIT.java プロジェクト: saissaoui/server
 @Test
 public void testPing() throws Exception {
   WebClient client = WebClient.create(endpointUrl + "/hello/echo/SierraTangoNevada");
   Response r = client.accept("text/plain").get();
   assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
   String value = IOUtils.toString((InputStream) r.getEntity());
   assertEquals("SierraTangoNevada", value);
 }
コード例 #14
0
ファイル: OASISCatalogTest.java プロジェクト: CzarnyPeter/cxf
 private String readUrl(String address) {
   String content = null;
   try {
     URL url = new URL(address);
     assertNotNull(url.getContent());
     content = IOUtils.toString((InputStream) url.getContent());
   } catch (IOException e) {
     e.printStackTrace(System.err);
     Assert.fail("Couldn't read URL: " + e.getMessage());
   }
   return content;
 }
コード例 #15
0
  protected byte[] doMethodBytes(String urlStr, String message, String method, String ct)
      throws MalformedURLException, IOException, SAXException, ParserConfigurationException {

    InputStream is = invoke(urlStr, message, method, ct);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    IOUtils.copy(is, out);
    out.close();
    is.close();

    return out.toByteArray();
  }
コード例 #16
0
 @Override
 protected byte[] getBytes(Object object) {
   DataHandler handler = (DataHandler) object;
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   try {
     InputStream stream = handler.getInputStream();
     IOUtils.copy(stream, baos);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
   return baos.toByteArray();
 }
  @Test
  public void testPostRead() throws Exception {

    String dataConnectorReadUrl = environment.getProperty("ref_postgres_data_connector_read_url");
    String analyticReadDataRequestJSON =
        IOUtils.toString(
            getClass().getClassLoader().getResourceAsStream("analytic-read-data-request.json"));
    ResponseEntity<String> response =
        postRequestWithJsonPayload(dataConnectorReadUrl, analyticReadDataRequestJSON);

    assertEquals(HttpStatus.OK, response.getStatusCode());

    String expectedAnalyticReadDataResponseString =
        IOUtils.toString(
            getClass()
                .getClassLoader()
                .getResourceAsStream("expected-analytic-read-data-response.json"));
    String actualAnalyticReadDataResponseString = response.getBody();
    JSONAssert.assertEquals(
        expectedAnalyticReadDataResponseString,
        actualAnalyticReadDataResponseString,
        JSONCompareMode.LENIENT);
  }
コード例 #18
0
 @Test
 @Ignore
 public void testApiListingIsProperlyReturnedJSON() throws Exception {
   final WebClient client = createWebClient("/swagger.json");
   try {
     final Response r = client.get();
     assertEquals(Status.OK.getStatusCode(), r.getStatus());
     JSONAssert.assertEquals(
         getExpectedValue(getExpectedFileJson(), getPort()),
         IOUtils.readStringFromStream((InputStream) r.getEntity()),
         false);
   } finally {
     client.close();
   }
 }
コード例 #19
0
 @Override
 protected void doClose() {
   Reader transformedReader = null;
   try {
     transformedReader = XSLTUtils.transform(xsltTemplate, getReader());
     IOUtils.copyAndCloseInput(transformedReader, origWriter, IOUtils.DEFAULT_BUFFER_SIZE);
   } catch (IOException e) {
     throw new Fault("READER_COPY", LOG, e, e.getMessage());
   } finally {
     try {
       origWriter.close();
     } catch (IOException e) {
       LOG.warning("Cannot close stream after transformation: " + e.getMessage());
     }
   }
 }
コード例 #20
0
 @Override
 public void onClose(CachedOutputStream wrapper) {
   InputStream transformedStream = null;
   try {
     transformedStream = XSLTUtils.transform(xsltTemplate, wrapper.getInputStream());
     IOUtils.copyAndCloseInput(transformedStream, origStream);
   } catch (IOException e) {
     throw new Fault("STREAM_COPY", LOG, e, e.getMessage());
   } finally {
     try {
       origStream.close();
     } catch (IOException e) {
       LOG.warning("Cannot close stream after transformation: " + e.getMessage());
     }
   }
 }
コード例 #21
0
  @Test
  @Ignore
  public void testApiListingIsProperlyReturnedYAML() throws Exception {
    final WebClient client = createWebClient("/swagger.yaml");

    try {
      final Response r = client.get();
      assertEquals(Status.OK.getStatusCode(), r.getStatus());
      // REVISIT find a better way of reliably comparing two yaml instances.
      // I noticed that yaml.load instantiates a Map and
      // for an integer valued key, an Integer or a String is arbitrarily instantiated,
      // which leads to the assertion error. So, we serilialize the yamls and compare the
      // re-serialized texts.
      Yaml yaml = new Yaml();
      assertEquals(
          yaml.load(getExpectedValue(getExpectedFileYaml(), getPort())).toString(),
          yaml.load(IOUtils.readStringFromStream((InputStream) r.getEntity())).toString());

    } finally {
      client.close();
    }
  }
コード例 #22
0
  private InputStream invoke(String urlStr, String message, String method, String ct)
      throws MalformedURLException, IOException, ProtocolException {
    URL url = new URL(urlStr);
    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.setRequestMethod(method);

    if (ct != null) {
      c.setRequestProperty("Content-Type", ct);
    }

    if (message != null) {
      c.setDoOutput(true);
      OutputStream out = c.getOutputStream();
      InputStream msgIs = getResourceAsStream(message);
      assertNotNull(msgIs);

      IOUtils.copy(msgIs, out);
      out.close();
      msgIs.close();
    }

    return c.getInputStream();
  }
コード例 #23
0
  @Test
  public void testResourceURLForWsdlLocation() throws Exception {
    env.put(ToolConstants.CFG_WSDLURL, getLocation("/wsdl2java_wsdl/hello_world.wsdl"));
    env.put(ToolConstants.CFG_WSDLLOCATION, "/wsdl2java_wsdl/hello_world.wsdl");
    env.put(ToolConstants.CFG_COMPILE, null);
    env.put(ToolConstants.CFG_CLASSDIR, null);
    processor.setContext(env);
    processor.execute();

    File dir = new File(output, "org");
    assertTrue("org directory is not found", dir.exists());
    dir = new File(dir, "apache");
    assertTrue("apache directory is not found", dir.exists());
    dir = new File(dir, "cxf");
    assertTrue("cxf directory is not found", dir.exists());
    dir = new File(dir, "w2j");
    assertTrue("w2j directory is not found", dir.exists());
    dir = new File(dir, "hello_world_soap_http");
    assertTrue("hello_world_soap_http directory is not found", dir.exists());

    String str =
        IOUtils.readStringFromStream(new FileInputStream(new File(dir, "SOAPService.java")));
    assertTrue(str, str.contains("getResource"));
  }
コード例 #24
0
 private String getStringFromInputStream(InputStream in) throws Exception {
   return IOUtils.toString(in);
 }
コード例 #25
0
  @Test
  public void testUpdateResource() {

    final String KEY_STRING = "stringAtt";
    final String KEY_DATE = "dateAtt";

    final Date origDate = new Date();
    final String origString = "OrigStringValue";

    Long rid;

    createDefaultCategory();

    {
      RESTStoredData storedData = new RESTStoredData();
      storedData.setData("we wish you a merry xmas and a happy new year");

      List<ShortAttribute> attrList = new ArrayList<ShortAttribute>();
      attrList.add(new ShortAttribute("string1", "value1", DataType.STRING));
      attrList.add(new ShortAttribute("string2", "value2", DataType.STRING));
      attrList.add(new ShortAttribute("string3", "value3", DataType.STRING));

      String timeid = Long.toString(System.currentTimeMillis());

      RESTResource origResource = new RESTResource();
      origResource.setCategory(new RESTCategory(DEFAULTCATEGORYNAME));
      origResource.setName("rest_test_resource_" + timeid);
      origResource.setStore(storedData);
      origResource.setAttribute(attrList);

      rid = client.insert(origResource);
    }
    System.out.println("RESOURCE has ID " + rid);

    // test getResource
    String name1 = "rest_test_resource_" + Long.toString(System.currentTimeMillis());
    {
      RESTResource updResource = new RESTResource();
      updResource.setName(name1);

      List<ShortAttribute> attrList = new ArrayList<ShortAttribute>();
      attrList.add(new ShortAttribute("string1", "value1", DataType.STRING)); // same
      attrList.add(new ShortAttribute("string2", "value2.2", DataType.STRING)); // updated
      // attrList.add(new ShortAttribute("string3", "value3", DataType.STRING)); //removed
      attrList.add(new ShortAttribute("string4", "value4", DataType.STRING)); // added

      updResource.setAttribute(attrList);
      client.updateResource(rid, updResource);
    }

    {
      Resource loaded = client.getResource(rid);
      System.out.println("RESOURCE: " + loaded);

      // test reloaded attrs
      List<Attribute> loadedAttrs = loaded.getAttribute();
      assertEquals(3, loadedAttrs.size());

      Map<String, String> attMap = new HashMap<String, String>();
      for (Attribute attribute : loadedAttrs) {
        attMap.put(attribute.getName(), attribute.getTextValue());
      }

      assertEquals("value1", attMap.get("string1"));
      assertEquals("value2.2", attMap.get("string2"));
      assertEquals("value4", attMap.get("string4"));
    }

    // try bad update
    {
      RESTResource res = new RESTResource();
      res.setCategory(new RESTCategory("TestCategory2"));
      try {
        client.updateResource(rid, res);
        fail("Undetected error");
      } catch (UniformInterfaceException e) {
        String response = "COULD NOT READ RESPONSE";
        try {
          response = IOUtils.toString(e.getResponse().getEntityInputStream());
        } catch (Exception e2) {
          LOGGER.warn("Error reading response: " + e2.getMessage());
        }
        LOGGER.info("Error condition successfully detected: " + response);
      } catch (Exception e) {
        LOGGER.info("Error condition successfully detected:" + e.getMessage(), e);
      }
    }

    client.deleteResource(rid);
  }
コード例 #26
0
 private static String getExpectedValue(String name, Object... args) throws IOException {
   return String.format(
       IOUtils.readStringFromStream(
           AbstractSwagger2ServiceDescriptionTest.class.getResourceAsStream(name)),
       args);
 }