Example usage for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT

List of usage examples for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT

Introduction

In this page you can find the example usage for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT.

Prototype

String JAXB_FORMATTED_OUTPUT

To view the source code for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT.

Click Source Link

Document

The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation.

Usage

From source file:dk.dbc.rawrepo.oai.ResumptionTokenTest.java

@Test
public void testXmlExpiration() throws Exception {
    ObjectNode jsonOriginal = (ObjectNode) new ObjectMapper().readTree("{\"foo\":\"bar\"}");

    long now = Instant.now().getEpochSecond();
    ResumptionTokenType token = ResumptionToken.toToken(jsonOriginal, 0);

    OAIPMH oaipmh = OBJECT_FACTORY.createOAIPMH();
    ListRecordsType getRecord = OBJECT_FACTORY.createListRecordsType();
    oaipmh.setListRecords(getRecord);/*from www  .  ja  v a2  s  .c om*/
    getRecord.setResumptionToken(token);
    JAXBContext context = JAXBContext.newInstance(OAIPMH.class);
    StringWriter writer = new StringWriter();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(oaipmh, writer);
    String xml = writer.getBuffer().toString();
    System.out.println("XML is:\n" + xml);
    int start = xml.indexOf("expirationDate=\"") + "expirationDate=\"".length();
    int end = xml.indexOf("\"", start);
    String timestamp = xml.substring(start, end);
    System.out.println("timestamp = " + timestamp);

    assertTrue("Timestamp should be in ISO_INSTANT ending with Z", timestamp.endsWith("Z"));
    TemporalAccessor parse = DateTimeFormatter.ISO_INSTANT.withZone(ZoneId.systemDefault()).parse(timestamp);
    long epochSecond = Instant.from(parse).getEpochSecond();
    long diff = Math.abs(now - epochSecond);
    System.out.println("diff = " + diff);
    assertTrue("Difference between expirationdate and now should be 10 sec or less", diff <= 10);
}

From source file:com.floreantpos.bo.actions.DataExportAction.java

@Override
public void actionPerformed(ActionEvent e) {
    Session session = null;/* www.  j  a v a 2s  .c o  m*/
    Transaction transaction = null;
    FileWriter fileWriter = null;
    GenericDAO dao = new GenericDAO();

    try {
        JFileChooser fileChooser = getFileChooser();
        int option = fileChooser.showSaveDialog(com.floreantpos.util.POSUtil.getBackOfficeWindow());
        if (option != JFileChooser.APPROVE_OPTION) {
            return;
        }

        File file = fileChooser.getSelectedFile();
        if (file.exists()) {
            option = JOptionPane.showConfirmDialog(com.floreantpos.util.POSUtil.getFocusedWindow(),
                    Messages.getString("DataExportAction.1") + file.getName() + "?", //$NON-NLS-1$//$NON-NLS-2$
                    Messages.getString("DataExportAction.3"), //$NON-NLS-1$
                    JOptionPane.YES_NO_OPTION);
            if (option != JOptionPane.YES_OPTION) {
                return;
            }
        }

        // fixMenuItemModifierGroups();

        JAXBContext jaxbContext = JAXBContext.newInstance(Elements.class);
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        StringWriter writer = new StringWriter();

        session = dao.createNewSession();
        transaction = session.beginTransaction();

        Elements elements = new Elements();

        //          * 2. USERS
        //          * 3. TAX
        //          * 4. MENU_CATEGORY
        //          * 5. MENU_GROUP
        //          * 6. MENU_MODIFIER
        //          * 7. MENU_MODIFIER_GROUP
        //          * 8. MENU_ITEM
        //          * 9. MENU_ITEM_SHIFT
        //          * 10. RESTAURANT
        //          * 11. USER_TYPE
        //          * 12. USER_PERMISSION
        //          * 13. SHIFT

        elements.setTaxes(TaxDAO.getInstance().findAll(session));
        elements.setMenuCategories(MenuCategoryDAO.getInstance().findAll(session));
        elements.setMenuGroups(MenuGroupDAO.getInstance().findAll(session));
        elements.setMenuModifiers(MenuModifierDAO.getInstance().findAll(session));
        elements.setMenuModifierGroups(MenuModifierGroupDAO.getInstance().findAll(session));
        elements.setMenuItems(MenuItemDAO.getInstance().findAll(session));
        elements.setMenuItemModifierGroups(MenuItemModifierGroupDAO.getInstance().findAll(session));

        //           elements.setUsers(UserDAO.getInstance().findAll(session));
        //           
        //           elements.setMenuItemShifts(MenuItemShiftDAO.getInstance().findAll(session));
        //           elements.setRestaurants(RestaurantDAO.getInstance().findAll(session));
        //           elements.setUserTypes(UserTypeDAO.getInstance().findAll(session));
        //           elements.setUserPermissions(UserPermissionDAO.getInstance().findAll(session));
        //           elements.setShifts(ShiftDAO.getInstance().findAll(session));

        m.marshal(elements, writer);

        transaction.commit();

        fileWriter = new FileWriter(file);
        fileWriter.write(writer.toString());
        fileWriter.close();

        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(),
                Messages.getString("DataExportAction.4")); //$NON-NLS-1$

    } catch (Exception e1) {
        transaction.rollback();
        PosLog.error(getClass(), e1);
        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(), e1.getMessage());
    } finally {
        IOUtils.closeQuietly(fileWriter);
        dao.closeSession(session);
    }
}

From source file:it.tidalwave.northernwind.core.impl.io.ResourcePropertiesJaxbMarshallable.java

/*******************************************************************************************************************
 *
 * {@inheritDoc}//w  w  w.  j  a  va 2 s.c om
 *
 ******************************************************************************************************************/
@Override
public void marshal(final @Nonnull OutputStream os) throws IOException {
    try {
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // FIXME: set in Spring
        marshaller.marshal(objectFactory.createProperties(marshal(resourceProperties)), os);
    } catch (JAXBException e) {
        throw new IOException("", e);
    }
}

From source file:org.javelin.sws.ext.bind.jaxb.JaxbTest.java

@Test
public void unmarshalSameQNames() throws Exception {
    JAXBContext ctx = JAXBContext.newInstance(org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1.class,
            org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2.class);
    Marshaller m = ctx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    log.info("context1");
    org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1 mc1 = new org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1();
    mc1.setP(new MyProperty1());
    m.marshal(new JAXBElement<org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1>(new QName("a", "a"),
            org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1.class, mc1), System.out);
    log.info("context2");
    org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2 mc2 = new org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2();
    mc2.setP(new MyProperty2());
    m.marshal(new JAXBElement<org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2>(new QName("a", "a"),
            org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2.class, mc2), System.out);

    Object object = ctx.createUnmarshaller().unmarshal(
            new StreamSource(
                    new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n"
                            + "<ns2:a xmlns=\"urn:x\" xmlns:ns2=\"a\">\r\n" + "    <p/>\r\n" + "</ns2:a>")),
            org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2.class);
    log.info("Class: {}", ((JAXBElement<?>) object).getValue().getClass());
}

From source file:com.vangent.hieos.services.xds.bridge.utils.JUnitHelper.java

/**
 * Method description//  www .  j  a  v a  2  s.  c o  m
 *
 *
 *
 *
 * @param file
 * @param count
 * @param documentIds
 * @return
 *
 * @throws Exception
 */
public static OMElement createOMRequest(String file, int count, String[] documentIds) throws Exception {

    ObjectFactory factory = new ObjectFactory();
    SubmitDocumentRequest sdr = factory.createSubmitDocumentRequest();

    IdType pid = factory.createIdType();

    pid.setRoot("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478");
    sdr.setPatientId(pid);

    ClassLoader classLoader = JUnitHelper.class.getClassLoader();

    DocumentsType documents = factory.createDocumentsType();

    for (int i = 0; i < count; ++i) {

        DocumentType document = factory.createDocumentType();

        if ((documentIds != null) && (documentIds.length > i)) {
            document.setId(documentIds[i]);
        }

        CodeType type = factory.createCodeType();

        type.setCode("51855-5");
        type.setCodeSystem("2.16.840.1.113883.6.1");

        document.setType(type);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        InputStream is = classLoader.getResourceAsStream(file);

        assertNotNull(is);

        IOUtils.copy(is, bos);

        document.setContent(bos.toByteArray());

        documents.getDocument().add(document);
    }

    sdr.setDocuments(documents);

    QName qname = new QName(URIConstants.XDSBRIDGE_URI, "SubmitDocumentRequest");
    JAXBContext jc = JAXBContext.newInstance(SubmitDocumentRequest.class);
    Marshaller marshaller = jc.createMarshaller();

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    JAXBElement element = new JAXBElement(qname, sdr.getClass(), sdr);

    StringWriter sw = new StringWriter();

    marshaller.marshal(element, sw);

    String xml = sw.toString();

    logger.debug(xml);

    OMElement result = AXIOMUtil.stringToOM(OMAbstractFactory.getOMFactory(), xml);

    List<OMElement> list = XPathHelper.selectNodes(result, "./ns:Documents/ns:Document/ns:Content",
            URIConstants.XDSBRIDGE_URI);

    for (OMElement contentNode : list) {

        OMText binaryNode = (OMText) contentNode.getFirstOMChild();

        if (binaryNode != null) {
            binaryNode.setOptimize(true);
        }
    }

    return result;
}

From source file:com.zaubersoftware.gnip4j.http.JSONDeserializationTest.java

/** regression test for a NPE exception */
@Test/*  w ww  .j  a v  a  2s  .com*/
public void testNPE() throws Exception {
    final InputStream is = getClass().getClassLoader()
            .getResourceAsStream("com/zaubersoftware/gnip4j/payload/payload-twitter-entities.js");
    final InputStream expectedIs = getClass().getClassLoader()
            .getResourceAsStream("com/zaubersoftware/gnip4j/payload/payload-twitter-entities.xml");

    try {
        final String json = IOUtils.toString(is);
        final JsonParser parser = mapper.getJsonFactory().createJsonParser(json);
        final Activity activity = parser.readValueAs(Activity.class);
        final StringWriter w = new StringWriter();
        mapper.getJsonFactory().createJsonGenerator(w).writeObject(activity);

        final Marshaller o = ctx.createMarshaller();
        o.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        StringWriter ww = new StringWriter();
        o.marshal(activity, ww);
        assertEquals(IOUtils.toString(expectedIs), ww.toString());
    } finally {
        is.close();
    }
}

From source file:com.retroduction.carma.eventlisteners.ReportEventListener.java

public void destroy() {

    this.log.info("Finishing XML report");

    this.runProcessingEnd = System.currentTimeMillis();

    new StatisticalReportAnalyzer().enhanceReport(this.run);

    try {// w ww.  jav  a  2 s.  c  o m
        if (this.writeTimingInfo) {
            ProcessingInfo info = this.createTimingInformation(this.runProcessingStart, this.runProcessingEnd);
            this.run.setProcessingInfo(info);
        }
    } catch (DatatypeConfigurationException e) {
        e.printStackTrace();
    }

    try {
        JAXBContext context = JAXBContext.newInstance(MutationRun.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(this.run, new FileOutputStream(new File(this.outputFile)));
    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

From source file:de.xirp.profile.ProfileGenerator.java

/**
 * Generates a BOT file with the given path from the given 
 * {@link de.xirp.profile.Robot robot} bean.
 * /*  w  ww . java2 s  . c  om*/
 * @param robot
 *          The robot to generate the XML for. 
 * @param botFile
 *          The file to write the result to. Must be the full path.
 * 
 * @throws JAXBException if the given robot was null, or something 
 *                    went wrong generating the xml.
 * @throws FileNotFoundException if something went wrong generating the xml.
 */
public static void generateBOT(Robot robot, File botFile) throws FileNotFoundException, JAXBException {

    if (robot == null) {
        throw new JAXBException(I18n.getString("ProfileGenerator.exception.robotNull")); //$NON-NLS-1$
    }

    String fileName = FilenameUtils.getBaseName(botFile.getName());

    JAXBContext jc = JAXBContext.newInstance(Robot.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(robot, new FileOutputStream(
            Constants.CONF_ROBOTS_DIR + File.separator + fileName + Constants.ROBOT_POSTFIX));
}

From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.LicenseModuleRestWSTester.java

@SuppressWarnings("all")
private static void testGetUserLicenseQuery() throws Exception {
    GetUserQueryInputDTO input = new GetUserQueryInputDTO();
    input.setPresentationType("images");
    input.setAttributes(createUserObjAttributeDTO());

    JAXBContext context = JAXBContext.newInstance(GetUserQueryInputDTO.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(input, outputStream);//from www . j av  a2 s .c om

    // serialize to XML
    String inputXML = outputStream.toString();
    System.out.println(inputXML);
    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client
            .resource(UriBuilder.fromUri("http://localhost:8080/licensemodule/services/").build());

    // Call with XML
    String output = service.path("getUserLicenseQuery").type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML)
            .entity(inputXML).post(String.class);

    System.out.println("query:" + output);
}

From source file:eu.modaclouds.sla.service.rest.AbstractSLARest.java

protected String printError(int code, String text) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {//from w w w.j  ava2  s.c  o m
        ErrorResponse errorResponse = new ErrorResponse();

        errorResponse.setCode(code);
        errorResponse.setMessage(text);

        JAXBContext jaxbContext;
        jaxbContext = JAXBContext.newInstance(eu.atos.sla.parser.data.ErrorResponse.class);
        Marshaller marshaller = jaxbContext.createMarshaller();

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        marshaller.marshal(errorResponse, out);
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return out.toString();

}