private Exchange io(Exchange exchange) {
   StringWriter writer = new StringWriter();
   JAXB.marshal(exchange, writer);
   writer.flush();
   String xml = writer.toString();
   StringReader reader = new StringReader(xml);
   return JAXB.unmarshal(reader, Exchange.class);
 }
Пример #2
0
  private <T extends Event> T convertConfig(Event theInitialConfig, Class<T> theDesiredClass) {
    if (theInitialConfig.getClass().equals(theDesiredClass)) {
      return (T) theInitialConfig;
    }

    StringWriter stringWriter = new StringWriter();
    JAXB.marshal(theInitialConfig, stringWriter);

    return JAXB.unmarshal(new StringReader(stringWriter.toString()), theDesiredClass);
  }
Пример #3
0
  @Test
  public void setReplicationConfig() throws Exception {

    ReplicationConfiguration r = new ReplicationConfiguration();
    Operator op = new Operator();
    op.setOperatorNodeID("test_node");
    op.setSoapReplicationURL("http://localhost");
    op.setOperatorStatus(OperatorStatusType.NORMAL);

    r.getOperator().add(op);
    r.setCommunicationGraph(new CommunicationGraph());
    r.setRegistryContact(new ReplicationConfiguration.RegistryContact());
    r.getRegistryContact().setContact(new Contact());
    r.getRegistryContact().getContact().getPersonName().add(new PersonName("test", null));
    //  r.getCommunicationGraph().getEdge().add(new CommunicationGraph.Edge());
    r.getCommunicationGraph().getNode().add("test_node");

    JAXB.marshal(r, System.out);
    DispositionReport setReplicationNodes = juddi.setReplicationNodes(authInfoRoot, r);

    ReplicationConfiguration replicationNodes = juddi.getReplicationNodes(authInfoRoot);
    Assert.assertNotNull(replicationNodes.getCommunicationGraph());
    Assert.assertNotNull(replicationNodes.getCommunicationGraph().getNode());
    Assert.assertEquals("test_node", replicationNodes.getCommunicationGraph().getNode().get(0));
    Assert.assertNotNull(replicationNodes.getMaximumTimeToGetChanges());
    Assert.assertNotNull(replicationNodes.getMaximumTimeToSyncRegistry());
    Assert.assertNotNull(replicationNodes.getTimeOfConfigurationUpdate());
    Assert.assertNotNull(replicationNodes.getSerialNumber());
    long firstcommit = replicationNodes.getSerialNumber();

    r = new ReplicationConfiguration();
    r.getOperator().add(op);
    r.setCommunicationGraph(new CommunicationGraph());
    r.setRegistryContact(new ReplicationConfiguration.RegistryContact());
    r.getRegistryContact().setContact(new Contact());
    r.getRegistryContact().getContact().getPersonName().add(new PersonName("test", null));
    //  r.getCommunicationGraph().getEdge().add(new CommunicationGraph.Edge());
    r.getCommunicationGraph().getNode().add("test_node");

    JAXB.marshal(r, System.out);
    setReplicationNodes = juddi.setReplicationNodes(authInfoRoot, r);

    replicationNodes = juddi.getReplicationNodes(authInfoRoot);
    Assert.assertNotNull(replicationNodes.getCommunicationGraph());
    Assert.assertNotNull(replicationNodes.getCommunicationGraph().getNode());
    Assert.assertEquals("test_node", replicationNodes.getCommunicationGraph().getNode().get(0));
    Assert.assertNotNull(replicationNodes.getMaximumTimeToGetChanges());
    Assert.assertNotNull(replicationNodes.getMaximumTimeToSyncRegistry());
    Assert.assertNotNull(replicationNodes.getTimeOfConfigurationUpdate());
    Assert.assertNotNull(replicationNodes.getSerialNumber());
    Assert.assertTrue(firstcommit < replicationNodes.getSerialNumber());
  }
Пример #4
0
  @Test
  public void testGetFlightsXml()
      throws AirlineException, DatatypeConfigurationException, TransformerException {
    GetFlightsRequest request = JAXB.unmarshal(getStream("request1.xml"), GetFlightsRequest.class);

    GetFlightsResponse response = endpoint.getFlights(request);

    DOMResult domResponse = new DOMResult();
    JAXB.marshal(response, domResponse);

    XMLUnit.setIgnoreWhitespace(true);
    XMLAssert.assertXMLEqual(getDocument("response1.xml"), (Document) domResponse.getNode());
  }
 private static <T> T getParamXPath(
     final Class<T> pClass, final String pXpath, final CompactFragment pBody) throws XmlException {
   // TODO Avoid JAXB where possible, use XMLDeserializer instead
   final boolean string = CharSequence.class.isAssignableFrom(pClass);
   Node match;
   DocumentFragment fragment =
       DomUtil.childrenToDocumentFragment(XMLFragmentStreamReader.from(pBody));
   for (Node n = fragment.getFirstChild(); n != null; n = n.getNextSibling()) {
     match = xpathMatch(n, pXpath);
     if (match != null) {
       if (!string) {
         XmlDeserializer deserializer = pClass.getAnnotation(XmlDeserializer.class);
         if (deserializer != null) {
           try {
             XmlDeserializerFactory<?> factory = deserializer.value().newInstance();
             factory.deserialize(XmlStreaming.newReader(new DOMSource(n)));
           } catch (InstantiationException | IllegalAccessException e) {
             throw new RuntimeException(e);
           }
         } else {
           return JAXB.unmarshal(new DOMSource(match), pClass);
         }
       } else {
         return pClass.cast(nodeToString(match));
       }
     }
   }
   return null;
 }
  private String marshal(Object o) {

    StringWriter w = new StringWriter();
    JAXB.marshal(o, w);
    w.flush();
    return w.getBuffer().toString();
  }
 /**
  * @param pXml
  * @return -
  */
 public static List<Question> parseQuestions(final String pXml) {
   ArgUtil.checkNullOrEmpty(pXml, "pXml"); // $NON-NLS-1$
   final List<Question> ret =
       JAXB.unmarshal(new StringReader(pXml), Questions.class).getQuestions();
   checkQuestions(ret);
   return ret;
 }
Пример #8
0
  @Test
  public void testCategories() throws Exception {

    createGroup("testGroup");
    String xml = sendRequest(GET, "/groups/testGroup/categories", 200);
    assertNotNull(xml);
    OnmsCategoryCollection categories =
        JAXB.unmarshal(new StringReader(xml), OnmsCategoryCollection.class);
    assertNotNull(categories);
    assertTrue(categories.getCategories().isEmpty());

    // add category to group
    sendRequest(
        PUT,
        "/groups/testGroup/categories/testCategory",
        400); // fails, because Category is not there
    createCategory("testCategory"); // create category
    sendRequest(
        PUT,
        "/groups/testGroup/categories/testCategory",
        200); // should not fail, because Category is now there
    xml = sendRequest(GET, "/groups/testGroup/categories/testCategory", 200); // get data
    assertNotNull(xml);
    OnmsCategory category = JAXB.unmarshal(new StringReader(xml), OnmsCategory.class);
    assertNotNull(category);
    assertEquals("testCategory", category.getName());

    // add again (fails)
    sendRequest(
        PUT,
        "/groups/testGroup/categories/testCategory",
        400); // should fail, because Category is already there

    // remove category from group
    sendRequest(DELETE, "/groups/testGroup/categories/testCategory", 200); // should not fail
    sendRequest(
        DELETE,
        "/groups/testGroup/categories/testCategory",
        400); // should fail, because category is already removed

    // test that all categories for group "testGroup" have been removed
    xml = sendRequest(GET, "/groups/testGroup/categories", 200);
    assertNotNull(xml);
    categories = JaxbUtils.unmarshal(OnmsCategoryCollection.class, xml);
    assertNotNull(categories);
    assertTrue(categories.getCategories().isEmpty());
  }
Пример #9
0
 public OfflineServerImpl() throws IOException, LoginException {
   InputStream is = new BufferedInputStream(new FileInputStream(getDataFile()));
   try {
     users = JAXB.unmarshal(is, Users.class);
     user = users.getUser().get(0);
     fixStartedPomodoros();
   } finally {
     is.close();
   }
 }
  public static InboundConnectionList fromXml(Controller theController, String theXml) {
    InboundConnectionList retVal =
        JAXB.unmarshal(new StringReader(theXml), InboundConnectionList.class);
    retVal.myController = theController;

    for (InboundConnection next : retVal.getConnections()) {
      next.setController(theController);
    }

    return retVal;
  }
Пример #11
0
  @Override
  public void execute() throws MojoExecutionException {
    try {
      Configuration configuration = new Configuration();
      configuration.setJdbc(jdbc);
      configuration.setGenerator(generator);

      StringWriter writer = new StringWriter();
      JAXB.marshal(configuration, writer);

      getLog().info("Using this configuration:\n" + writer.toString());
      GenerationTool.main(configuration);
    } catch (Exception ex) {
      throw new MojoExecutionException("Error running jOOQ code generation tool", ex);
    }
    project.addCompileSourceRoot(generator.getTarget().getDirectory());
  }
Пример #12
0
 private void flush(File file, Users users) {
   BufferedOutputStream bos = null;
   try {
     bos = new BufferedOutputStream(new FileOutputStream(file));
     JAXB.marshal(users, bos);
     lastFlushDate = new Date();
   } catch (FileNotFoundException ex) {
     Logger.getLogger(OfflineServerImpl.class.getName()).log(Level.SEVERE, null, ex);
   } finally {
     if (bos != null) {
       try {
         bos.close();
       } catch (IOException ex) {
         Logger.getLogger(OfflineServerImpl.class.getName()).log(Level.SEVERE, null, ex);
       }
     }
   }
 }
Пример #13
0
  public void parse(InputStream xml, ArrayList<Properties> sepaResults) {

    Document doc = JAXB.unmarshal(xml, Document.class);

    // Payment Information
    ArrayList<PaymentInstructionInformationSCT> pmtInfs =
        (ArrayList<PaymentInstructionInformationSCT>) doc.getCstmrCdtTrfInitn().getPmtInf();

    for (PaymentInstructionInformationSCT pmtInf : pmtInfs) {

      // Payment Information - Credit Transfer Transaction Information
      ArrayList<CreditTransferTransactionInformationSCT> cdtTrxTxInfs =
          (ArrayList<CreditTransferTransactionInformationSCT>) pmtInf.getCdtTrfTxInf();

      for (CreditTransferTransactionInformationSCT cdtTrxTxInf : cdtTrxTxInfs) {
        Properties sepaResult = new Properties();

        sepaResult.setProperty(
            "src.name", doc.getCstmrCdtTrfInitn().getGrpHdr().getInitgPty().getNm());

        sepaResult.setProperty("src.iban", pmtInf.getDbtrAcct().getId().getIBAN());
        sepaResult.setProperty("src.bic", pmtInf.getDbtrAgt().getFinInstnId().getBIC());

        sepaResult.setProperty("dst.name", cdtTrxTxInf.getCdtr().getNm());
        sepaResult.setProperty("dst.iban", cdtTrxTxInf.getCdtrAcct().getId().getIBAN());
        sepaResult.setProperty("dst.bic", cdtTrxTxInf.getCdtrAgt().getFinInstnId().getBIC());

        BigDecimal value = cdtTrxTxInf.getAmt().getInstdAmt().getValue();
        sepaResult.setProperty("value", value.toString());
        sepaResult.setProperty("curr", "EUR");

        if (cdtTrxTxInf.getRmtInf() != null) {
          sepaResult.setProperty("usage", cdtTrxTxInf.getRmtInf().getUstrd());
        }

        XMLGregorianCalendar date = pmtInf.getReqdExctnDt();
        if (date != null) {
          sepaResult.setProperty("date", date.toString());
        }

        sepaResults.add(sepaResult);
      }
    }
  }
  public static OORunResponse run(OORunRequest request) throws IOException, URISyntaxException {

    String urlString =
        StringUtils.slashify(request.getServer().getUrl())
            + REST_SERVICES_URL_PATH
            + RUN_OPERATION_URL_PATH
            + StringUtils.unslashifyPrefix(request.getFlow().getId());

    final URI uri = OOBuildStep.URI(urlString);
    final HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(new JaxbEntity(request));
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "text/xml");
    //        if (OOBuildStep.getEncodedCredentials()!=null) {
    //            httpPost.addHeader("Authorization", "Basic " + new
    // String(OOBuildStep.getEncodedCredentials()));
    //        }

    HttpResponse response;

    response = client.execute(httpPost);
    final int statusCode = response.getStatusLine().getStatusCode();
    final HttpEntity entity = response.getEntity();

    try {
      if (statusCode == HttpStatus.SC_OK) {

        return JAXB.unmarshal(entity.getContent(), OORunResponse.class);

      } else {

        throw new RuntimeException(
            "unable to get run result from "
                + uri
                + ", response code: "
                + statusCode
                + "("
                + HttpStatus.getStatusText(statusCode)
                + ")");
      }
    } finally {
      EntityUtils.consume(entity);
    }
  }
Пример #15
0
 @Override
 public Object apply(Exception from) {
   Iterable<HttpResponseException> throwables =
       Iterables.filter(Throwables.getCausalChain(from), HttpResponseException.class);
   HttpResponseException exception = Iterables.getFirst(throwables, null);
   if (exception != null
       && exception.getResponse() != null
       && exception.getResponse().getStatusCode() >= 400
       && exception.getResponse().getStatusCode() < 500) {
     try {
       Error error =
           JAXB.unmarshal(InputSuppliers.of(exception.getContent()).getInput(), Error.class);
       throw new VCloudDirectorException(error);
     } catch (IOException e) {
       Throwables.propagate(e);
     }
   }
   throw Throwables.propagate(from);
 }
  public static OOListResponse listFlows(OOServer s, String... folders) throws IOException {

    String foldersPath = "";

    for (String folder : folders) {
      foldersPath += folder + "/";
    }

    String url =
        StringUtils.slashify(s.getUrl())
            + REST_SERVICES_URL_PATH
            + LIST_OPERATION_URL_PATH
            + foldersPath;

    final HttpResponse response =
        OOBuildStep.getHttpClient().execute(new HttpGet(OOBuildStep.URI(url)));

    final int statusCode = response.getStatusLine().getStatusCode();

    final HttpEntity entity = response.getEntity();

    try {

      if (statusCode == HttpStatus.SC_OK) {

        return JAXB.unmarshal(entity.getContent(), OOListResponse.class);
      } else {

        throw new RuntimeException(
            "unable to get list of flows from "
                + url
                + ", response code: "
                + statusCode
                + "("
                + HttpStatus.getStatusText(statusCode)
                + ")");
      }
    } finally {
      EntityUtils.consume(entity);
    }
  }
Пример #17
0
  public void build(File output, File template, DocumentModel model) throws IOException {
    File temporal;

    temporal = File.createTempFile(this.getClass().getName() + '.', ".xml");
    try {
      int result;

      JAXB.marshal(model, temporal);
      result =
          this.launch(
              "-build",
              template.getAbsolutePath(),
              output.getAbsolutePath(),
              temporal.getAbsolutePath());
      if (result != 0)
        throw new IOException(
            String.format("failed on build document" + " (process exit with %d)", result));
    } finally {
      temporal.delete();
    }
  }
  @Override
  public void save() {
    List<WrappedVertex> vertices = new ArrayList<WrappedVertex>();
    for (Vertex vertex : getVertices()) {
      if (vertex.isGroup()) {
        vertices.add(new WrappedGroup(vertex));
      } else {
        vertices.add(new WrappedLeafVertex(vertex));
      }
    }
    List<WrappedEdge> edges = new ArrayList<WrappedEdge>();
    for (Edge edge : getEdges()) {
      WrappedEdge newEdge =
          new WrappedEdge(
              edge,
              new WrappedLeafVertex(m_vertexProvider.getVertex(edge.getSource().getVertex())),
              new WrappedLeafVertex(m_vertexProvider.getVertex(edge.getTarget().getVertex())));
      edges.add(newEdge);
    }

    WrappedGraph graph = new WrappedGraph(getEdgeNamespace(), vertices, edges);

    JAXB.marshal(graph, new File(getConfigurationFile()));
  }
Пример #19
0
 /**
  * De-serializes the WiseML document and returns the object representation of the parsed document.
  *
  * @param serializedWiseML the serialized WiseML document
  * @return the object representation of the parsed document
  */
 @SuppressWarnings("unused")
 public static Wiseml deserialize(final String serializedWiseML) {
   return JAXB.unmarshal(new StringReader(serializedWiseML), Wiseml.class);
 }
Пример #20
0
 /** Gibt die Kontakte zurück welche im mitgelieferten XML File gespeichert wurden */
 public Contacts readContacts(File file) throws JAXBException {
   return JAXB.unmarshal(file, Contacts.class);
 }
Пример #21
0
 public static String marshal(Object anyObject) {
   StringWriter stringWriter = new StringWriter();
   JAXB.marshal(anyObject, stringWriter);
   return stringWriter.getBuffer().toString();
 }
Пример #22
0
  private Object getParam(
      final Class<?> pClass,
      final String pName,
      final ParamType pType,
      final String pXpath,
      final HttpMessage pMessage)
      throws XmlException {
    Object result = null;
    switch (pType) {
      case GET:
        result = getParamGet(pName, pMessage);
        break;
      case POST:
        result = getParamPost(pName, pMessage);
        break;
      case QUERY:
        result = getParamGet(pName, pMessage);
        if (result == null) {
          result = getParamPost(pName, pMessage);
        }
        break;
      case VAR:
        result = mPathParams.get(pName);
        break;
      case XPATH:
        result = getParamXPath(pClass, pXpath, pMessage.getBody());
        break;
      case BODY:
        result = getBody(pClass, pMessage);
        break;
      case ATTACHMENT:
        result = getAttachment(pClass, pName, pMessage);
        break;
      case PRINCIPAL:
        {
          final Principal principal = pMessage.getUserPrincipal();
          if (pClass.isAssignableFrom(String.class)) {
            result = principal.getName();
          } else {
            result = principal;
          }
          break;
        }
    }
    // XXX generizice this and share the same approach to unmarshalling in ALL code
    // TODO support collection/list parameters
    if ((result != null) && (!pClass.isInstance(result))) {
      if ((Types.isPrimitive(pClass) || (Types.isPrimitiveWrapper(pClass)))
          && (result instanceof String)) {
        try {
          result = Types.parsePrimitive(pClass, ((String) result));
        } catch (NumberFormatException e) {
          throw new HttpResponseException(
              HttpServletResponse.SC_BAD_REQUEST, "The argument given is invalid", e);
        }
      } else if (Enum.class.isAssignableFrom(pClass)) {
        @SuppressWarnings({"rawtypes"})
        final Class clazz = pClass;
        @SuppressWarnings("unchecked")
        final Enum<?> tmpResult = Enum.valueOf(clazz, result.toString());
        result = tmpResult;
      } else if (result instanceof Node) {
        XmlDeserializer factory = pClass.getAnnotation(XmlDeserializer.class);
        if (factory != null) {
          try {
            result =
                factory
                    .value()
                    .newInstance()
                    .deserialize(XmlStreaming.newReader(new DOMSource((Node) result)));
          } catch (IllegalAccessException | InstantiationException e) {
            throw new XmlException(e);
          }
        } else {
          result = JAXB.unmarshal(new DOMSource((Node) result), pClass);
        }
      } else {
        final String s = result.toString();
        // Only wrap when we don't start with <
        final char[] requestBody =
            (s.startsWith("<") ? s : "<wrapper>" + s + "</wrapper>").toCharArray();
        if (requestBody.length > 0) {
          result = JAXB.unmarshal(new CharArrayReader(requestBody), pClass);
        } else {
          result = null;
        }
      }
    }

    return result;
  }
 /**
  * XML形式のアンケート設定ファイルを読み込みます.
  *
  * @param pXmlLocation XMLファイルの位置.
  * @return 読み込み結果.
  */
 public static List<Question> loadQuestions(final URL pXmlLocation) {
   final List<Question> ret = JAXB.unmarshal(pXmlLocation, Questions.class).getQuestions();
   checkQuestions(ret);
   return ret;
 }
 @Override
 public String exportConfigToXml() {
   StringWriter writer = new StringWriter();
   JAXB.marshal(this, writer);
   return writer.toString();
 }
Пример #25
0
 /**
  * Serializes the {@link Wiseml} instance.
  *
  * @param wiseML the {@link Wiseml} instance to serialize
  * @return the serialized WiseML document
  */
 @SuppressWarnings("unused")
 public static String serialize(final Wiseml wiseML) {
   StringWriter writer = new StringWriter();
   JAXB.marshal(wiseML, writer);
   return writer.toString();
 }
    private Message doProcess(Message theArg0) throws HL7Exception, ApplicationException {
      String encodedMessage = theArg0.encode();

      Terser terser = new Terser(theArg0);
      String msgType = terser.get("/MSH-9-1");
      String msgTrigger = terser.get("/MSH-9-2");
      MSH msh = (MSH) theArg0.get("MSH");

      ourLog.info("Message is of type " + msgType + "^" + msgTrigger);
      List<Failure> failures;

      try {
        String msgSourceOrg = terser.get("/MSH-3-1");
        String sourceOrg =
            myContributorConfig.getContributorConfig().getNameOfHspId9004(msgSourceOrg);
        ourLog.info("Sending organization from message is {} - {}", msgSourceOrg, sourceOrg);
      } catch (Exception e) {
        // ignore
      }

      Converter converter;
      try {
        converter = new Converter(true);
      } catch (JAXBException e2) {
        ourLog.error("Failed to convert message: Could not initialize converter", e2);
        throw new HL7Exception(e2);
      }

      String outcome = null;
      if ("ORU".equals(msgType) && "R01".equals(msgTrigger)) {
        final ORU_R01 oru = (ORU_R01) theArg0;
        final List<ClinicalDocumentGroup> documents = converter.convertClinicalDocument(oru);
        try {
          outcome =
              "ORU^R01 message evaluated (containing " + documents.size() + " documents/results)";
          //					outcome = Persister.persist(documents);
        } catch (final Exception e1) {
          throw new HL7Exception(e1);
        }
      } else if ("ADT".equals(msgType)) {
        ADT_A01 adt = new ADT_A01();
        adt.setParser(myParser);
        adt.parse(encodedMessage);
        PatientWithVisits pwv = converter.convertPatientWithVisits(adt);
        try {
          if (pwv != null) {
            outcome = "ADT^" + msgTrigger + " message evaluated";
            //						outcome = Persister.persist(pwv);
          } else {
            outcome = PROCESSING_FAILED_OUTCOME;
          }
        } catch (final Exception e1) {
          throw new HL7Exception(e1);
        }
      } else if ("RDE".equals(msgType) && "O11".equals(msgTrigger)) {
        RDE_O11 rde = new RDE_O11();
        rde.setParser(myParser);
        rde.parse(encodedMessage);
        List<MedicationOrder> medOrders = converter.convertMedicationOrder(rde);
        try {
          outcome =
              "RDE^O11 message evaluated (containing " + medOrders.size() + " medication orders)";
          //					outcome = Persister.persistMedicationOrders(medOrders);
        } catch (final Exception e1) {
          throw new HL7Exception(e1);
        }
      } else if ("RAS".equals(msgType) && "O17".equals(msgTrigger)) {
        RAS_O17 ras = new RAS_O17();
        ras.setParser(myParser);
        ras.parse(encodedMessage);
        List<MedicationOrderWithAdmins> medOrdersWithAdmins = converter.convertMedicationAdmin(ras);
        try {
          outcome =
              "RAS^O17 message evaluated (containing administration data for "
                  + medOrdersWithAdmins.size()
                  + " medication orders)";
          //					outcome = Persister.persistMedicationAdmins(medOrdersWithAdmins);
        } catch (final Exception e1) {
          throw new HL7Exception(e1);
        }
      } else {

        /*
         * Note: If adding processors for additional message types, make
         * sure to update the description for F098!!
         */

        converter.validateMsh(msh);
        converter.addFailure("/MSH-9", FailureCode.F098, msgType + "^" + msgTrigger);
        outcome = PROCESSING_FAILED_OUTCOME;
      }

      if (StringUtils.isBlank(outcome)) {
        outcome = PROCESSING_FAILED_OUTCOME;
      }

      // These are determined from the IDs in the message
      SendingSystem sendingSystem = converter.getSendingSystem();
      Contributor contributor = converter.getContributorConfig();

      //			if (contributor == null) {
      //				contributor = myContributor;
      //			} else if (contributor != myContributor) {
      //				converter.addFailure("MSH-3-1", FailureCode.F112,
      // msh.getMsh3_SendingApplication().getHd1_NamespaceID().getValue());
      //				contributor = myContributor;
      //			}

      if (sendingSystem == null) {
        throw new ApplicationException(
            "Failed to determine sender from message. Please check MSH-3 value");
      }

      //			if (sendingSystem == null ||
      // contributor.getSendingSystem9008WithOid(sendingSystem.getCode()) == null) {
      //				converter.addFailure("MSH-3-2", FailureCode.F113,
      // msh.getMsh3_SendingApplication().getHd2_UniversalID().getValue());
      //				sendingSystem = contributor.getSendingSystem().get(0);
      //				ourLog.info("Defaulting to first sending system {} because MSH-3-2 was {}",
      // sendingSystem.getDescription(),
      // msh.getMsh3_SendingApplication().getHd2_UniversalID().getValue());
      //			}

      ourLog.info(
          "Converted message from {} - {}", contributor.getName(), sendingSystem.getDescription());

      String orgId = sendingSystem.getManagementConsoleOrgId();
      if (StringUtils.isBlank(orgId)) {
        orgId = contributor.getManagementConsoleOrgId();
      }

      final CanonicalHl7V2Message canon =
          AbstractPojo.createNewCanonicalMessageHl7V2(
              encodedMessage,
              orgId,
              sendingSystem.getManagementConsoleSystemId(),
              Listener.INTERFACE_ID,
              MessagePhase.INCOMING,
              Listener.class,
              java.util.logging.Logger.getLogger(Listener.class.getName()));
      failures = converter.getFailures();
      if (failures.size() > 0) {

        String problemDescription = createHtmlProblemDescription(converter);

        if (problemDescription.length() > 0) {
          canon.setValidationOutcomeDescription(problemDescription);
        }

        ourLog.info("Message has {} failures", converter.getFailures().size());

      } else {

        ourLog.info("Message has no validation failures! Outstanding.");
        canon.setValidationOutcomeDescription("No issues");
      }

      if (outcome != null) {
        canon.setValidationOutcomeDescription(
            canon.getValidationOutcomeDescription() + "<br>Outcome: " + outcome);
      } else {
        canon.setValidationOutcomeDescription(canon.getValidationOutcomeDescription());
      }

      // Journal for the source
      ourLog.info("Journalling message");
      final JournalMessageRequest request = new JournalMessageRequest();
      request.setCanonicalHl7V2Message(canon);
      try {
        AbstractPojo.tryToJournalMessage(myJournalSvc, request);
      } catch (InvalidInputException e) {
        ourLog.error("Failed to send message to journal", e);
        throw new HL7Exception("Failed to process message");
      } catch (final sail.wsdl.infrastructure.journalling.UnexpectedErrorException e) {
        ourLog.error("Failed to send message to dead letter", e);
        throw new HL7Exception("Failed to process message");
      } catch (Exception e) {
        ourLog.error("Failed to journal message. Moving on", e);
        StringWriter w = new StringWriter();
        JAXB.marshal(request, w);
        ourLog.error("Request was: " + w.toString());
      }

      // // Journal again for the destination
      // canon.setDestination(new OutboundInterface());
      // canon.getDestination().setBoxId(canon.getSource().getBoxId());
      // canon.getDestination().setDomainId(canon.getSource().getDomainId());
      // canon.getDestination().setInterfaceDirection("O");
      // canon.getDestination().setOrgId("SIMS");
      // canon.getDestination().setSystemId("CGTA_Interim_CDR");
      // canon.getDestination().setInterfaceId("All");
      // canon.setCurrentMessagePhase(MessagePhase.OUTGOING);
      // try {
      // myJournalSvc.journalMessage(request);
      // } catch (final InvalidInputException e) {
      // ourLog.error("Failed to send message to journal", e);
      // } catch (final
      // sail.wsdl.infrastructure.journalling.UnexpectedErrorException e)
      // {
      // ourLog.error("Failed to send message to dead letter", e);
      // }

      try {
        ACK ack = (ACK) theArg0.generateACK();

        for (final Failure next : converter.getFailures()) {
          ERR err = ack.getERR(ack.getERRReps());
          err.getErr1_ErrorCodeAndLocation(0).getEld1_SegmentID().setValue(next.getTerserPath());
          err.getErr3_HL7ErrorCode().getCwe1_Identifier().setValue(next.getFailureCode().name());
          err.getErr6_ApplicationErrorParameter(0).setValue(next.getFieldVal());
          err.getErr7_DiagnosticInformation().setValue(next.getMessage());
        }

        return ack;
      } catch (final IOException e) {
        throw new HL7Exception(e);
      }
    }
Пример #27
0
 @Override
 void marshal(Object output, File outputFile) {
   javax.xml.bind.JAXB.marshal(castJaxbObject(output), outputFile);
 }
Пример #28
0
  /**
   * Cria a assinatura para o objeto informado no construtor.
   *
   * @return Assinatura gerada.
   * @throws SignatureException Caso ocorra algum erro ao gerar a assinatura.
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public SignatureType createSignature() throws SignatureException {
    try {
      final X509Certificate certificate = Configuration.getInstance().getCertificate();

      // Cria a assinatura com a API do Java.
      final XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM");

      final List<Transform> transformList = new ArrayList<Transform>();
      transformList.add(factory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
      transformList.add(
          factory.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null));

      final Reference reference =
          factory.newReference(
              this.referenceUri,
              factory.newDigestMethod(DigestMethod.SHA1, null),
              transformList,
              null,
              null);
      final SignedInfo signedInfo =
          factory.newSignedInfo(
              factory.newCanonicalizationMethod(
                  CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null),
              factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
              Collections.singletonList(reference));

      final KeyInfoFactory keyInfoFactory = factory.getKeyInfoFactory();

      final List x509Content = new ArrayList();
      x509Content.add(certificate.getSubjectX500Principal().getName());
      x509Content.add(certificate);

      final X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
      final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));

      final DOMSignContext domSignContext =
          new DOMSignContext(
              Configuration.getInstance().getPrivateKey(), this.document.getDocumentElement());

      final XMLSignature newXMLSignature = factory.newXMLSignature(signedInfo, keyInfo);
      newXMLSignature.sign(domSignContext);

      // Remove tags nao recomendadas.
      final String[] unnecessaryElements =
          new String[] {
            "X509SubjectName",
            "X509IssuerSerial",
            "X509IssuerName",
            "X509IssuerName",
            "X509SKI",
            "KeyValue",
            "RSAKeyValue",
            "Modulus",
            "Exponent"
          };
      final XPathFactory xpathFactory = XPathFactory.newInstance();

      for (final String elementName : unnecessaryElements) {
        final XPathExpression xpath =
            xpathFactory.newXPath().compile("//*[name()='" + elementName + "']");
        final Node node = (Node) xpath.evaluate(this.document, XPathConstants.NODE);

        if (null != node) {
          node.getParentNode().removeChild(node);
        }
      }

      final XPathExpression xpath = xpathFactory.newXPath().compile("//*[name()='Signature']");
      return JAXB.unmarshal(
          new DOMSource((Node) xpath.evaluate(this.document, XPathConstants.NODE)),
          SignatureType.class);

    } catch (Exception e) {
      throw new SignatureException("Um erro ocorreu ao criar a assinatura.", e);
    }
  }