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:GetLeadChanges.java

public static void main(String[] args) {
    System.out.println("Executing Get Lead Changes");
    try {//from w  ww.j a v a2  s . co m
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsGetLeadChanges request = new ParamsGetLeadChanges();

        ObjectFactory objectFactory = new ObjectFactory();
        JAXBElement<Integer> batchSize = objectFactory.createParamsGetLeadActivityBatchSize(10);
        request.setBatchSize(batchSize);

        ArrayOfString activities = new ArrayOfString();
        activities.getStringItems().add("Visit Webpage");
        activities.getStringItems().add("Click Link");

        JAXBElement<ArrayOfString> activityFilter = objectFactory
                .createParamsGetLeadChangesActivityNameFilter(activities);
        request.setActivityNameFilter(activityFilter);

        // Create oldestCreateAt timestamp from 5 days ago
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(new Date().getTime());
        gc.add(GregorianCalendar.DAY_OF_YEAR, -5);

        DatatypeFactory factory = DatatypeFactory.newInstance();
        JAXBElement<XMLGregorianCalendar> oldestCreateAtValue = objectFactory
                .createStreamPositionOldestCreatedAt(factory.newXMLGregorianCalendar(gc));

        StreamPosition sp = new StreamPosition();
        sp.setOldestCreatedAt(oldestCreateAtValue);
        request.setStartPosition(sp);

        SuccessGetLeadChanges result = port.getLeadChanges(request, header);

        JAXBContext context = JAXBContext.newInstance(SuccessGetLeadChanges.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:SyncCustomObjects.java

public static void main(String[] args) {
    System.out.println("Executing Sync Custom Objects");
    try {//from   w  w  w . j  a  v  a  2  s  .  c  o  m
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsSyncCustomObjects request = new ParamsSyncCustomObjects();
        request.setObjTypeName("RoadShow");
        JAXBElement<SyncOperationEnum> operation = new ObjectFactory()
                .createParamsSyncCustomObjectsOperation(SyncOperationEnum.UPSERT);
        request.setOperation(operation);

        ArrayOfCustomObj customObjects = new ArrayOfCustomObj();

        CustomObj customObj = new CustomObj();

        ArrayOfAttribute arrayOfKeyAttributes = new ArrayOfAttribute();
        Attribute attr = new Attribute();
        attr.setAttrName("MKTOID");
        attr.setAttrValue("1090177");

        Attribute attr2 = new Attribute();
        attr2.setAttrName("rid");
        attr2.setAttrValue("rid1");

        arrayOfKeyAttributes.getAttributes().add(attr);
        arrayOfKeyAttributes.getAttributes().add(attr2);

        JAXBElement<ArrayOfAttribute> keyAttributes = new ObjectFactory()
                .createCustomObjCustomObjKeyList(arrayOfKeyAttributes);
        customObj.setCustomObjKeyList(keyAttributes);
        ArrayOfAttribute arrayOfValueAttributes = new ArrayOfAttribute();

        Attribute city = new Attribute();
        city.setAttrName("city");
        city.setAttrValue("SanMateo");

        Attribute zip = new Attribute();
        zip.setAttrName("zip");
        zip.setAttrValue("94404");

        Attribute state = new Attribute();
        state.setAttrName("state");
        state.setAttrValue("California");

        arrayOfValueAttributes.getAttributes().add(city);
        arrayOfValueAttributes.getAttributes().add(state);
        arrayOfValueAttributes.getAttributes().add(zip);

        JAXBElement<ArrayOfAttribute> valueAttributes = new ObjectFactory()
                .createCustomObjCustomObjAttributeList(arrayOfValueAttributes);
        customObj.setCustomObjAttributeList(valueAttributes);

        customObjects.getCustomObjs().add(customObj);

        SuccessSyncCustomObjects result = port.syncCustomObjects(request, header);

        JAXBContext context = JAXBContext.newInstance(SuccessSyncCustomObjects.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.l2jserver.model.template.NPCTemplateConverter.java

public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException {
    controllers.put("L2Teleporter", TeleporterController.class);
    controllers.put("L2CastleTeleporter", TeleporterController.class);
    controllers.put("L2Npc", BaseNPCController.class);
    controllers.put("L2Monster", MonsterController.class);
    controllers.put("L2FlyMonster", MonsterController.class);
    Class.forName("com.mysql.jdbc.Driver");

    final File target = new File("generated/template/npc");

    System.out.println("Scaning legacy HTML files...");
    htmlScannedFiles = FileUtils.listFiles(L2J_HTML_FOLDER, new String[] { "html", "htm" }, true);

    final JAXBContext c = JAXBContext.newInstance(NPCTemplate.class, Teleports.class);

    final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
    {//from   w w w .  j ava  2  s . c  o  m
        System.out.println("Converting teleport templates...");
        teleportation.teleport = CollectionFactory.newList();

        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        final PreparedStatement st = conn.prepareStatement("SELECT * FROM teleport");
        st.execute();
        final ResultSet rs = st.getResultSet();
        while (rs.next()) {
            final TeleportationTemplate template = new TeleportationTemplate();

            template.id = new TeleportationTemplateID(rs.getInt("id"), null);
            template.name = rs.getString("Description");
            TemplateCoordinate coord = new TemplateCoordinate();
            coord.x = rs.getInt("loc_x");
            coord.y = rs.getInt("loc_y");
            coord.z = rs.getInt("loc_z");
            template.point = coord;
            template.price = rs.getInt("price");
            template.item = rs.getInt("itemId");
            if (rs.getBoolean("fornoble")) {
                template.restrictions = new Restrictions();
                template.restrictions.restriction = Arrays.asList("NOBLE");
            }
            teleportation.teleport.add(template);
        }
        m.marshal(teleportation, getXMLSerializer(new FileOutputStream(new File(target, "../teleports.xml"))));
        // System.exit(0);
    }

    System.out.println("Generating template XML files...");
    // c.generateSchema(new SchemaOutputResolver() {
    // @Override
    // public Result createOutput(String namespaceUri,
    // String suggestedFileName) throws IOException {
    // // System.out.println(new File(target, suggestedFileName));
    // // return null;
    // return new StreamResult(new File(target, suggestedFileName));
    // }
    // });

    try {
        final Marshaller m = c.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        final PreparedStatement st = conn.prepareStatement(
                "SELECT npc.*, npcskills.level AS race " + "FROM npc " + "LEFT JOIN npcskills "
                        + "ON(npc.idTemplate = npcskills.npcid AND npcskills.skillid = ?)");
        st.setInt(1, 4416);
        st.execute();
        final ResultSet rs = st.getResultSet();
        while (rs.next()) {
            Object[] result = fillNPC(rs);
            NPCTemplate t = (NPCTemplate) result[0];
            String type = (String) result[1];

            String folder = createFolder(type);
            if (folder.isEmpty()) {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../npc.xsd");
            } else {
                m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "npc ../../npc.xsd");
            }

            final File file = new File(target, "npc/" + folder + "/" + t.getID().getID()
                    + (t.getInfo().getName() != null ? "-" + camelCase(t.getInfo().getName().getValue()) : "")
                    + ".xml");
            file.getParentFile().mkdirs();
            templates.add(t);

            try {
                m.marshal(t, getXMLSerializer(new FileOutputStream(file)));
            } catch (MarshalException e) {
                System.err.println("Could not generate XML template file for "
                        + t.getInfo().getName().getValue() + " - " + t.getID());
                file.delete();
            }
        }

        System.out.println("Generated " + templates.size() + " templates");

        System.gc();
        System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory()));
        System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory()));
        System.out.println("Used: " + FileUtils.byteCountToDisplaySize(
                Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
        System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory()));
    } finally {
        conn.close();
    }
}

From source file:SyncMultipleLeads.java

public static void main(String[] args) {
    System.out.println("Executing syncMultipleLeads");
    try {/*from   w  w  w.  j  ava  2s  . co  m*/
        URL marketoSoapEndPoint = new URL("https://100-AEK-913.mktoapi.com/soap/mktows/2_1" + "?WSDL");
        String marketoUserId = "demo17_1_809934544BFABAE58E5D27";
        String marketoSecretKey = "27272727aa";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsSyncMultipleLeads request = new ParamsSyncMultipleLeads();

        ObjectFactory objectFactory = new ObjectFactory();

        JAXBElement<Boolean> dedup = objectFactory.createParamsSyncMultipleLeadsDedupEnabled(true);
        request.setDedupEnabled(dedup);

        ArrayOfLeadRecord arrayOfLeadRecords = new ArrayOfLeadRecord();

        // Create First Lead Record
        LeadRecord rec1 = new LeadRecord();

        JAXBElement<String> email = objectFactory.createLeadRecordEmail("t@t.com");
        rec1.setEmail(email);

        Attribute attr1 = new Attribute();
        attr1.setAttrName("FirstName");
        attr1.setAttrValue("George");

        Attribute attr2 = new Attribute();
        attr2.setAttrName("LastName");
        attr2.setAttrValue("of the Jungle");

        ArrayOfAttribute aoa = new ArrayOfAttribute();
        aoa.getAttributes().add(attr1);
        aoa.getAttributes().add(attr2);

        QName qname = new QName("http://www.marketo.com/mktows/", "leadAttributeList");
        JAXBElement<ArrayOfAttribute> attrList = new JAXBElement(qname, ArrayOfAttribute.class, aoa);

        rec1.setLeadAttributeList(attrList);
        arrayOfLeadRecords.getLeadRecords().add(rec1);

        // Create Second Lead Record
        LeadRecord rec2 = new LeadRecord();

        JAXBElement<String> email2 = objectFactory.createLeadRecordEmail("myemail@test.com");
        rec2.setEmail(email2);

        Attribute attr11 = new Attribute();
        attr11.setAttrName("FirstName");
        attr11.setAttrValue("Nancy");

        Attribute attr21 = new Attribute();
        attr21.setAttrName("LastName");
        attr21.setAttrValue("Lady");

        ArrayOfAttribute aoa2 = new ArrayOfAttribute();
        aoa2.getAttributes().add(attr11);
        aoa2.getAttributes().add(attr21);

        qname = new QName("http://www.marketo.com/mktows/", "leadAttributeList");
        JAXBElement<ArrayOfAttribute> attrList2 = new JAXBElement(qname, ArrayOfAttribute.class, aoa2);

        rec2.setLeadAttributeList(attrList);
        arrayOfLeadRecords.getLeadRecords().add(rec2);

        request.setLeadRecordList(arrayOfLeadRecords);

        SuccessSyncMultipleLeads result = port.syncMultipleLeads(request, header);

        JAXBContext context = JAXBContext.newInstance(SuccessSyncMultipleLeads.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:GetMultipleLeads.java

public static void main(String[] args) {
    System.out.println("Executing GetMultipleLeads");
    try {/*from   w ww.j a v  a  2s.  c  om*/
        URL marketoSoapEndPoint = new URL("CHANGE ME" + "?WSDL");
        String marketoUserId = "CHANGE ME";
        String marketoSecretKey = "CHANGE ME";

        QName serviceName = new QName("http://www.marketo.com/mktows/", "MktMktowsApiService");
        MktMktowsApiService service = new MktMktowsApiService(marketoSoapEndPoint, serviceName);
        MktowsPort port = service.getMktowsApiSoapPort();

        // Create Signature
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        String text = df.format(new Date());
        String requestTimestamp = text.substring(0, 22) + ":" + text.substring(22);
        String encryptString = requestTimestamp + marketoUserId;

        SecretKeySpec secretKey = new SecretKeySpec(marketoSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(encryptString.getBytes());
        char[] hexChars = Hex.encodeHex(rawHmac);
        String signature = new String(hexChars);

        // Set Authentication Header
        AuthenticationHeader header = new AuthenticationHeader();
        header.setMktowsUserId(marketoUserId);
        header.setRequestTimestamp(requestTimestamp);
        header.setRequestSignature(signature);

        // Create Request
        ParamsGetMultipleLeads request = new ParamsGetMultipleLeads();

        // Request Using LeadKey Selector
        ////////////////////////////////////////////////////////
        LeadKeySelector keySelector = new LeadKeySelector();
        keySelector.setKeyType(LeadKeyRef.EMAIL);

        ArrayOfString aos = new ArrayOfString();
        aos.getStringItems().add("formtest1@marketo.com");
        aos.getStringItems().add("joe@marketo.com");
        keySelector.setKeyValues(aos);
        request.setLeadSelector(keySelector);

        /*
        // Request Using LastUpdateAtSelector
        ////////////////////////////////////////////////////////
        LastUpdateAtSelector leadSelector = new LastUpdateAtSelector();
                 
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTimeInMillis(new Date().getTime());
        gc.add( GregorianCalendar.DAY_OF_YEAR, -2);
                 
        DatatypeFactory factory = DatatypeFactory.newInstance();
                
        ObjectFactory objectFactory = new ObjectFactory();
        JAXBElement<XMLGregorianCalendar> until =objectFactory.createLastUpdateAtSelectorLatestUpdatedAt(factory.newXMLGregorianCalendar(gc));            
                 
        GregorianCalendar since = new GregorianCalendar();
        since.setTimeInMillis(new Date().getTime());
        since.add( GregorianCalendar.DAY_OF_YEAR, -5);
                 
        leadSelector.setOldestUpdatedAt(factory.newXMLGregorianCalendar(since));
        leadSelector.setLatestUpdatedAt(until);     
                 
        request.setLeadSelector(leadSelector);
        */

        /*
        // Request Using StaticList Selector
        ////////////////////////////////////////////////////////
        StaticListSelector staticListSelector = new StaticListSelector();
                
        //staticListSelector.setStaticListId(value)
        ObjectFactory objectFactory = new ObjectFactory();
        JAXBElement<String> listName = objectFactory.createStaticListSelectorStaticListName("SMSProgram.listForTesting");
        staticListSelector.setStaticListName(listName);
                 
        // JAXBElement<Integer> listId = objectFactory.createStaticListSelectorStaticListId(6926);
        // staticListSelector.setStaticListId(listId);
                 
        request.setLeadSelector(staticListSelector);
        */

        ArrayOfString attributes = new ArrayOfString();
        attributes.getStringItems().add("FirstName");
        attributes.getStringItems().add("AnonymousIP");
        attributes.getStringItems().add("Company");

        request.setIncludeAttributes(attributes);

        JAXBElement<Integer> batchSize = new ObjectFactory().createParamsGetMultipleLeadsBatchSize(10);
        request.setBatchSize(batchSize);

        SuccessGetMultipleLeads result = port.getMultipleLeads(request, header);

        JAXBContext context = JAXBContext.newInstance(SuccessGetLead.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(result, System.out);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static String saveObjectToXmlString(Object obj) throws JAXBException {
    final Marshaller m = JAXBContext.newInstance(obj.getClass()).createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    final StringWriter writer = new StringWriter();
    m.marshal(obj, writer);/* w ww . ja va2 s  .  com*/

    return writer.toString();
}

From source file:Main.java

public static String object2Xml(Object obj) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(obj.getClass());
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

    StringWriter writer = new StringWriter();
    marshaller.marshal(new JAXBElement(new QName("xml"), obj.getClass(), obj), writer);

    return writer.toString();
}

From source file:Main.java

public static <T> String toString(T xml) {
    JAXBContext jc;/*from  w  ww.  j a v a 2 s.co  m*/
    try {
        jc = JAXBContext.newInstance(xml.getClass());
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        StringWriter writer = new StringWriter();
        m.marshal(xml, writer);
        return writer.toString();
    } catch (JAXBException e) {
        return "";
    }
}

From source file:Main.java

public static void saveInstance(File outputFile, Object instance) throws JAXBException, IOException {
    Marshaller marshaller = JAXBContext.newInstance(instance.getClass()).createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(instance, outputFile);
}

From source file:Main.java

public static Marshaller getMarshaller(Class jaxbClass) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(jaxbClass);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
    return marshaller;
}