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; }
/** * @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; }
@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()); }
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); }
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(); } }
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); }
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; }
@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()); }
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); } } }
@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 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); } }
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); } }
/** * 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; }
/** 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); }
/** * 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); }
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; }
/** * 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); } }