Example usage for javax.xml.bind JAXBContext newInstance

List of usage examples for javax.xml.bind JAXBContext newInstance

Introduction

In this page you can find the example usage for javax.xml.bind JAXBContext newInstance.

Prototype

public static JAXBContext newInstance(Class<?>... classesToBeBound) throws JAXBException 

Source Link

Document

Create a new instance of a JAXBContext class.

Usage

From source file:com.cws.esolutions.core.main.EmailUtility.java

public static final void main(final String[] args) {
    final String methodName = EmailUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//from   w w w .j  a va2s.  c o m
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", (Object) args);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(EmailUtility.CNAME, options, true);

        return;
    }

    try {
        CommandLineParser parser = new PosixParser();
        CommandLine commandLine = parser.parse(options, args);

        URL xmlURL = null;
        JAXBContext context = null;
        Unmarshaller marshaller = null;
        CoreConfigurationData configData = null;

        xmlURL = FileUtils.getFile(commandLine.getOptionValue("config")).toURI().toURL();
        context = JAXBContext.newInstance(CoreConfigurationData.class);
        marshaller = context.createUnmarshaller();
        configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL);

        EmailMessage message = new EmailMessage();
        message.setMessageTo(new ArrayList<String>(Arrays.asList(commandLine.getOptionValues("to"))));
        message.setMessageSubject(commandLine.getOptionValue("subject"));
        message.setMessageBody((String) commandLine.getArgList().get(0));
        message.setEmailAddr((StringUtils.isNotEmpty(commandLine.getOptionValue("from")))
                ? new ArrayList<String>(Arrays.asList(commandLine.getOptionValue("from")))
                : new ArrayList<String>(Arrays.asList(configData.getMailConfig().getMailFrom())));

        if (DEBUG) {
            DEBUGGER.debug("EmailMessage: {}", message);
        }

        try {
            EmailUtils.sendEmailMessage(configData.getMailConfig(), message, false);
        } catch (MessagingException mx) {
            System.err.println(
                    "An error occurred while sending the requested message. Exception: " + mx.getMessage());
        }
    } catch (ParseException px) {
        px.printStackTrace();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(EmailUtility.CNAME, options, true);
    } catch (MalformedURLException mx) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(EmailUtility.CNAME, options, true);
    } catch (JAXBException jx) {
        jx.printStackTrace();
        System.err.println("An error occurred while loading the provided configuration file. Cannot continue.");
    }
}

From source file:GetMultipleLeads.java

public static void main(String[] args) {
    System.out.println("Executing GetMultipleLeads");
    try {//w  ww .ja v a2  s .  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:eu.impact_project.iif.tw.cli.ToolWrapper.java

/**
 * Main method of the command line application
 *
 * @param args//from  w  w w. j a  v a2  s. c o  m
 *        Arguments of the command line application
 * @throws GeneratorException
 *         Exception if project generation fails
 */
public static void main(String[] args) throws GeneratorException {

    CommandLineParser cmdParser = new PosixParser();
    try {
        // Parse the command line arguments
        CommandLine cmd = cmdParser.parse(OPTIONS, args);
        // If no args or help selected
        if ((args.length == 0) || (cmd.hasOption(HELP_OPT))) {
            // OK help needed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true);

            if (args.length == 0)
                logger.info("Reading default configuration files from working " + "directory ...");
            else
                System.exit(0);
        }

        String toolspecPath = cmd.getOptionValue(TOOLSPEC_OPT, Constants.DEFAULT_TOOLSPEC);
        File toolspecFile = new File(toolspecPath);
        String propertiesPath = cmd.getOptionValue(PROPERTIES_OPT, Constants.DEFAULT_PROJECT_PROPERTIES);
        File propertiesFile = new File(propertiesPath);
        ioc.setXmlConf(toolspecFile);
        ioc.setProjConf(propertiesFile);

    } catch (ParseException excep) {
        // Problem parsing the command line args, just print the message and help
        logger.error("Problem parsing command line arguments.", excep);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Constants.PROJECT_NAME, OPTIONS, true);
        System.exit(1);
    }

    if (!ioc.hasConfig()) {
        throw new GeneratorException("No configuration available.");
    }
    JAXBContext context;
    try {
        context = JAXBContext.newInstance("eu.impact_project.iif.tw.toolspec");
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Toolspec toolspec = (Toolspec) unmarshaller.unmarshal(new File(ioc.getXmlConf()));
        // general tool specification properties
        logger.info("Toolspec model: " + toolspec.getModel());
        logger.info("Tool id: " + toolspec.getId());
        logger.info("Tool name: " + toolspec.getName());
        logger.info("Tool version: " + toolspec.getVersion());

        // List of services for the tool
        List<Service> services = toolspec.getServices().getService();
        // For each service a different maven project will be generated
        for (Service service : services) {
            createService(service, toolspec.getVersion());
        }
    } catch (IOException ex) {
        logger.error("An IOException occurred", ex);
    } catch (JAXBException ex) {
        logger.error("JAXBException", ex);
        throw new GeneratorException("Unable to create XML binding for toolspec");
    }
}

From source file:Main.java

private static JAXBContext createContext(Class<?> clazz) throws JAXBException {
    return JAXBContext.newInstance(clazz);
}

From source file:Main.java

public static JAXBContext createJaxbContext(Class<?> toBeBound) throws JAXBException {
    return JAXBContext.newInstance(toBeBound);
}

From source file:Main.java

public static <T> T xml2Object(String xml, Class<T> clazz) throws JAXBException {
    JAXBContext context = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    StringReader reader = new StringReader(xml);
    return (T) unmarshaller.unmarshal(reader);
}

From source file:Main.java

public static String bean2XML(Object obj) throws Exception {
    JAXBContext context = JAXBContext.newInstance(obj.getClass());
    Marshaller m = context.createMarshaller();
    StringWriter sw = new StringWriter();
    m.marshal(obj, sw);/*from  w w  w .  j a v  a2  s.  com*/
    return sw.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 Object xml2Bean(String xml, Object obj) throws Exception {
    JAXBContext context = JAXBContext.newInstance(obj.getClass());
    Unmarshaller um = context.createUnmarshaller();
    StringReader sr = new StringReader(xml);
    return um.unmarshal(sr);

}

From source file:Main.java

public static <T> String toXml(Class<T> z, Object o) {
    try {/*from  ww w .  ja va 2  s  .  c o  m*/
        JAXBContext jc = JAXBContext.newInstance(z);
        Marshaller ms = jc.createMarshaller();
        ms.marshal(o, System.out);
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return "";
}