Example usage for javax.xml.bind Marshaller marshal

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

Introduction

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

Prototype

public void marshal(Object jaxbElement, javax.xml.stream.XMLEventWriter writer) throws JAXBException;

Source Link

Document

Marshal the content tree rooted at jaxbElement into a javax.xml.stream.XMLEventWriter .

Usage

From source file:org.remus.marketplace.servlets.SearchListing.java

@Override
public void handleRequest(HttpServletRequest arg0, HttpServletResponse arg1)
        throws ServletException, IOException {
    String query = arg0.getParameter("query");
    String parameter = arg0.getParameter("filters");
    arg1.setContentType("text/xml");
    int category = 0;
    String marketId = null;//w  ww. j av a 2s  .  co  m
    if (parameter != null) {
        String[] split = parameter.split("\\s");
        for (String string : split) {
            String replace = string.replace("tid:", "");
            if (replace != null && replace.trim().length() > 0) {
                try {
                    category = Integer.parseInt(replace);

                } catch (NumberFormatException e1) {
                    marketId = replace;
                }
            }
        }
    }

    try {
        category = Integer.parseInt(arg0.getParameter("categoryId"));
    } catch (NumberFormatException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        JAXBContext newInstance = JAXBContext.newInstance(Marketplace.class,
                org.remus.marketplace.xml.Market.class);

        Marketplace marketplace = new Marketplace();

        List<Integer> searchNodes = indexService.searchNodes(query, category, marketId);
        Search search = new Search();
        search.setTerm(query);
        search.setCount(searchNodes.size());
        search.setUrl(serverPrefix + "search/apachesolr/" + URLEncoder.encode(query, "UTF-8")
                + (category != 0 && marketId != null ? "?filters=" : "")
                + (category != 0 ? "tid:" + category : "") + (marketId != null ? " tid:" + marketId : ""));

        for (int i = 0, n = Math.min(searchNodes.size(), 10); i < n; i++) {
            Node findById = nodeDao.findById(searchNodes.get(i));
            org.remus.marketplace.xml.Node node = XMLBuilder.buildNode(serverPrefix, findById);
            search.getNode().add(node);
        }
        marketplace.setSearch(search);
        Marshaller createMarshaller = newInstance.createMarshaller();
        XMLSerializer xmlSerializer = XMLBuilder.getXMLSerializer(arg1.getOutputStream());
        createMarshaller.marshal(marketplace, xmlSerializer.asContentHandler());
    } catch (JAXBException e) {
        throw new ServletException(e);
    }

}

From source file:com.cloud.baremetal.networkservice.SecurityGroupHttpClient.java

public SecurityGroupRuleAnswer call(String agentIp, SecurityGroupRulesCmd cmd) {
    PostMethod post = new PostMethod(String.format("http://%s:%s", agentIp, getPort()));
    try {//ww w .j a v  a 2  s . c om
        SecurityGroupVmRuleSet rset = new SecurityGroupVmRuleSet();
        rset.getEgressRules().addAll(generateRules(cmd.getEgressRuleSet()));
        rset.getIngressRules().addAll(generateRules(cmd.getIngressRuleSet()));
        rset.setVmName(cmd.getVmName());
        rset.setVmIp(cmd.getGuestIp());
        rset.setVmMac(cmd.getGuestMac());
        rset.setVmId(cmd.getVmId());
        rset.setSignature(cmd.getSignature());
        rset.setSequenceNumber(cmd.getSeqNum());
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(rset, writer);
        String xmlContents = writer.toString();
        logger.debug(xmlContents);

        post.addRequestHeader("command", "set_rules");
        StringRequestEntity entity = new StringRequestEntity(xmlContents);
        post.setRequestEntity(entity);
        if (httpClient.executeMethod(post) != 200) {
            return new SecurityGroupRuleAnswer(cmd, false, post.getResponseBodyAsString());
        } else {
            return new SecurityGroupRuleAnswer(cmd);
        }
    } catch (Exception e) {
        return new SecurityGroupRuleAnswer(cmd, false, e.getMessage());
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:gov.nih.nci.cabig.caaers.web.study.ExportStudyController.java

@Override
protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object o,
        BindException e) throws Exception {

    Integer studyID = Integer.valueOf(request.getParameter("id"));
    Study study = studyDao.getById(studyID);
    studyDao.initialize(study);//w w  w .  j  a  va  2  s .c  o  m

    // START study export pre-population
    study.setCoordinatingCenter(new CoordinatingCenter());
    study.getCoordinatingCenter().setStudyCoordinatingCenter(study.getStudyCoordinatingCenter());

    study.setFundingSponsor(new FundingSponsor());
    study.getFundingSponsor().setStudyFundingSponsor(study.getStudyFundingSponsors().get(0));

    for (OrganizationAssignedIdentifier id : study.getOrganizationAssignedIdentifiers()) {
        if (id.getOrganization().equals(study.getFundingSponsor().getStudyFundingSponsor().getOrganization())) {
            study.getFundingSponsor().setOrganizationAssignedIdentifier(id);
            study.getFundingSponsor().getOrganizationAssignedIdentifier().setPrimaryIndicator(true);
            break;
        }
    }
    for (OrganizationAssignedIdentifier id : study.getOrganizationAssignedIdentifiers()) {
        if (id.getOrganization()
                .equals(study.getCoordinatingCenter().getStudyCoordinatingCenter().getOrganization())) {
            study.getCoordinatingCenter().setOrganizationAssignedIdentifier(id);
            study.getCoordinatingCenter().getOrganizationAssignedIdentifier().setPrimaryIndicator(false);
            break;
        }
    }
    // END study export pre-population

    gov.nih.nci.cabig.caaers.integration.schema.study.Studies studies = converter
            .convertStudyDomainToStudyDto(study);

    //Marshall the Data Transfer Object according to Study.xsd schema,
    //and download it to the client machine.
    try {
        String tempDir = System.getProperty("java.io.tmpdir");
        String fileName = "ExportedStudy_" + study.getPrimaryIdentifierValue();
        fileName = RuleUtil.getStringWithoutSpaces(fileName);

        StringWriter sw = new StringWriter();
        JAXBContext jaxbContext = JAXBContext.newInstance("gov.nih.nci.cabig.caaers.integration.schema.study");

        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(studies, sw);
        BufferedWriter out = new BufferedWriter(new FileWriter(tempDir + fileName + ".xml"));
        out.write(sw.toString());
        out.flush();
        out.close();

        response.setContentType("application/xml");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xml");
        response.setHeader("Content-length", String.valueOf(sw.toString().length()));
        response.setHeader("Pragma", "private");
        response.setHeader("Cache-control", "private, must-revalidate");

        OutputStream outputStream = response.getOutputStream();
        File file = new File(tempDir + fileName + ".xml");
        FileInputStream fileIn = new FileInputStream(file);
        byte[] buffer = new byte[2048];
        int bytesRead = fileIn.read(buffer);
        while (bytesRead >= 0) {
            if (bytesRead > 0)
                outputStream.write(buffer, 0, bytesRead);
            bytesRead = fileIn.read(buffer);
        }
        outputStream.flush();
        outputStream.close();
        fileIn.close();

    } catch (Exception ex) {
        log.error(ex);
        ex.printStackTrace();
    }
    return null;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.SubjectRegistryWebServicePerformanceTest.java

private void executeBulkGradedQuerySubjectRegistryTest() throws SQLException, Exception {
    SubjectRegistry service = getService();

    // successful creation
    final QueryStudySubjectRegistryRequest request = new QueryStudySubjectRegistryRequest();
    DSETAdvanceSearchCriterionParameter dsetAdvanceSearchCriterionParameter = new DSETAdvanceSearchCriterionParameter();
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("=", "500"));
    request.setSearchParameter(dsetAdvanceSearchCriterionParameter);

    JAXBContext context = JAXBContext.newInstance("edu.duke.cabig.c3pr.webservice.subjectregistry");
    Marshaller marshaller = context.createMarshaller();
    marshaller.marshal(request, System.out);
    System.out.flush();/*from www  . j a  v  a 2s .co  m*/
    startProfiling();
    service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    startProfiling();
    DSETStudySubject studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(20, studySubjects.getItem().size());
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("like", "%-100"));
    startProfiling();
    studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(100, studySubjects.getItem().size());
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("like", "%-200"));
    startProfiling();
    studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(200, studySubjects.getItem().size());
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("like", "%-300"));
    startProfiling();
    studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(300, studySubjects.getItem().size());
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("like", "%-400"));
    startProfiling();
    studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(400, studySubjects.getItem().size());
}

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

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

    // and I thought it's illegal...
    m.marshal(new JAXBElement<String>(new QName("a", "a a"), String.class, "hello"), System.out);
}

From source file:com.testdroid.api.APIEntity.java

@JsonIgnore
public String toXML() {
    try {/* ww  w.  j a  v a2 s . c o m*/
        JAXBContext context = getJAXBContext(this.getClass());
        Marshaller marshaller = context.createMarshaller();
        StringWriter writer = new StringWriter();
        marshaller.marshal(this, writer);
        return writer.toString();
    } catch (JAXBException ex) {
        Logger.getLogger(APIEntity.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}

From source file:org.bremersee.comparator.test.ComparatorItemTests.java

@Test
public void testXmlComparatorItem() throws Exception {

    System.out.println("Testing XML write-read operations ...");

    ComparatorItem item = new ComparatorItem("i0", true);
    item.next("i1", false).next("i2", true);

    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter sw = new StringWriter();

    marshaller.marshal(item, sw);

    String xmlStr = sw.toString();

    System.out.println(xmlStr);//  w w  w.  j  a  v a2 s.  c o m

    ComparatorItem readItem = (ComparatorItem) jaxbContext.createUnmarshaller()
            .unmarshal(new StringReader(xmlStr));

    System.out.println(item.toList(true));
    System.out.println(readItem.toList(true));

    TestCase.assertEquals(item.toList(true), readItem.toList(true));

    System.out.println("OK\n");
}

From source file:esg.node.components.registry.AzsWhitelistGleaner.java

public synchronized boolean saveAzsWhitelist(AzsWhitelist azss) {
    boolean success = false;
    if (azss == null) {
        log.error("azss (whitelist) is null ? [" + azss + "]");
        return success;
    }// w w  w  .j  a  va2 s .  c  o  m
    log.trace("Saving AZS Whitelist information to " + azsWhitelistPath + azsWhitelistFile);
    try {
        JAXBContext jc = JAXBContext.newInstance(AzsWhitelist.class);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(azss, new FileOutputStream(azsWhitelistPath + azsWhitelistFile));
        success = true;
    } catch (Exception e) {
        log.error(e);
    }

    return success;
}

From source file:esg.node.components.registry.IdpWhitelistGleaner.java

public synchronized boolean saveIdpWhitelist(IdpWhitelist idps) {
    boolean success = false;
    if (idps == null) {
        log.error("idps (whitelist) is null ? [" + idps + "]");
        return success;
    }//from   w w w . jav a  2 s .c o m
    log.trace("Saving IDP Whitelist information to " + idpWhitelistPath + idpWhitelistFile);
    try {
        JAXBContext jc = JAXBContext.newInstance(IdpWhitelist.class);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(idps, new FileOutputStream(idpWhitelistPath + idpWhitelistFile));
        success = true;
    } catch (Exception e) {
        log.error(e);
    }

    return success;
}

From source file:esg.node.components.registry.LasSistersGleaner.java

public synchronized boolean saveLasServers(LasServers servers) {
    boolean success = false;
    if (servers == null) {
        log.error("LasServers is [" + servers + "]");
        return success;
    }//from  w  w w .j av  a  2 s .co  m
    log.trace("Saving LAS LasServers information to " + sistersPath + sistersFile);
    try {
        JAXBContext jc = JAXBContext.newInstance(LasServers.class);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(servers, new FileOutputStream(sistersPath + sistersFile));
        success = true;
    } catch (Exception e) {
        log.error(e);
    }

    return success;
}