Ejemplo n.º 1
0
  private static void readXml() throws JAXBException {
    JAXBContext jaxbContext = null;
    File file = null;
    Unmarshaller unmarshaller = null;

    jaxbContext = JAXBContext.newInstance(Characters.class);
    file = new File("Characters.xml");
    unmarshaller = jaxbContext.createUnmarshaller();
    characters = (Characters) unmarshaller.unmarshal(file);

    jaxbContext = JAXBContext.newInstance(Subject.class);
    file = new File("Subject.xml");
    unmarshaller = jaxbContext.createUnmarshaller();
    subject = (Subject) unmarshaller.unmarshal(file);

    jaxbContext = JAXBContext.newInstance(Theme.class);
    file = new File("Theme.xml");
    unmarshaller = jaxbContext.createUnmarshaller();
    theme = (Theme) unmarshaller.unmarshal(file);

    jaxbContext = JAXBContext.newInstance(Locale.class);
    file = new File("Locale.xml");
    unmarshaller = jaxbContext.createUnmarshaller();
    locale = (Locale) unmarshaller.unmarshal(file);

    jaxbContext = JAXBContext.newInstance(LearningAct.class);
    file = new File("LearningAct.xml");
    unmarshaller = jaxbContext.createUnmarshaller();
    learningAct = (LearningAct) unmarshaller.unmarshal(file);

    System.out.println();
  }
  @Before
  public void setUp() throws Exception {
    preferredValidatorFactory = Validation.buildDefaultValidatorFactory();

    JAXBContext ctx = JAXBContextFactory.createContext(EMPLOYEE, null);
    marshallerValidOn = (JAXBMarshaller) ctx.createMarshaller();
    marshallerValidOn.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshallerValidOff = (JAXBMarshaller) ctx.createMarshaller();
    /* tests setting the property through marshaller */
    marshallerValidOff.setProperty(
        MarshallerProperties.BEAN_VALIDATION_MODE, BeanValidationMode.NONE);
    marshallerValidOff.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    JAXBContext ctxValidationOff =
        JAXBContextFactory.createContext(
            EMPLOYEE,
            new HashMap<String, Object>() {
              {
                put(JAXBContextProperties.BEAN_VALIDATION_MODE, BeanValidationMode.NONE);
                put(JAXBContextProperties.BEAN_VALIDATION_FACTORY, preferredValidatorFactory);
              }
            });
    unmarshallerValidOn = (JAXBUnmarshaller) ctxValidationOff.createUnmarshaller();
    /* tests setting the property through unmarshaller */
    unmarshallerValidOn.setProperty(
        UnmarshallerProperties.BEAN_VALIDATION_MODE, BeanValidationMode.CALLBACK);
    unmarshallerValidOff = (JAXBUnmarshaller) ctxValidationOff.createUnmarshaller();
  }
 public ArrayList validateXML(String xmlMessage) {
   StringBuffer validationError = new StringBuffer("");
   String result = "Pass";
   ArrayList list = new ArrayList();
   SubmitManufacturerPartyData sb = null;
   InputStream inFile = null;
   try {
     inFile = new ByteArrayInputStream(xmlMessage.getBytes());
     SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
     Schema schema = schemaFactory.newSchema(new File("PartydataManufacturer.xsd"));
     JAXBContext ctx = JAXBContext.newInstance(new Class[] {SubmitManufacturerPartyData.class});
     Unmarshaller um = ctx.createUnmarshaller();
     um.setSchema(schema);
     sb = (SubmitManufacturerPartyData) um.unmarshal(inFile);
   } catch (SAXException e) {
     result = "Fail";
     e.printStackTrace();
   } catch (UnmarshalException umex) {
     result = "Fail";
     System.out.println("---------- XML Validation Error -------------- ");
     System.out.println("#######" + umex.getLinkedException().getMessage());
     umex.printStackTrace();
   } catch (Exception e) {
     result = "Fail";
     e.printStackTrace();
   }
   list.add(sb);
   list.add(result);
   return list;
 }
Ejemplo n.º 4
0
  private Suggestions transformJsonResponse(final InputStream is, final Path transformation)
      throws IOException, TransformationException {
    try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
      jsonTransformer.transform(is, transformation, os);

      try (final InputStream resultIs = new ByteArrayInputStream(os.toByteArray())) {
        final JAXBContext context =
            org.eclipse.persistence.jaxb.JAXBContextFactory.createContext(
                new Class[] {Suggestions.class}, null);

        final Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setProperty(
            UnmarshallerProperties.MEDIA_TYPE,
            org.eclipse.persistence.oxm.MediaType.APPLICATION_JSON);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_ATTRIBUTE_PREFIX, null);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, false);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
        unmarshaller.setProperty(
            UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, namespacePrefixMapper);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_SEPARATOR, ':');

        final JAXBElement<Suggestions> jaxbElement =
            unmarshaller.unmarshal(new StreamSource(resultIs), Suggestions.class);
        return jaxbElement.getValue();
      } catch (final JAXBException e) {
        throw new TransformationException(e);
      }
    }
  }
Ejemplo n.º 5
0
  @Test
  public void testModelValidate() throws Exception {

    JAXBContext ctx = JAXBContext.newInstance("jsr352.batch.jsl");

    Unmarshaller u = ctx.createUnmarshaller();
    u.setSchema(ValidatorHelper.getXJCLSchema());
    XJCLValidationEventHandler handler = new XJCLValidationEventHandler();
    u.setEventHandler(handler);
    URL url = this.getClass().getResource("/job1.xml");

    // Use this for anonymous type
    // Job job = (Job)u.unmarshal(url.openStream());

    // Use this for named complex type
    Object elem = u.unmarshal(url.openStream());
    assertFalse("XSD invalid, see sysout", handler.eventOccurred());

    JSLJob job = (JSLJob) ((JAXBElement) elem).getValue();

    assertEquals("job1", job.getId());
    assertEquals(1, job.getExecutionElements().size());
    Step step = (Step) job.getExecutionElements().get(0);
    assertEquals("step1", step.getId());
    Batchlet b = step.getBatchlet();
    assertEquals("step1Ref", b.getRef());
  }
Ejemplo n.º 6
0
 protected Object parseUri(String uri) throws JAXBException {
   Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
   URL resource = getClass().getResource(uri);
   assertNotNull("Cannot find resource on the classpath: " + uri, resource);
   Object value = unmarshaller.unmarshal(resource);
   return value;
 }
 public static xmltoOntology loadXsdOntologyMappings(String mappingFileDirectory)
     throws JAXBException {
   JAXBContext jaxbContext = JAXBContext.newInstance(xmltoOntology.class);
   Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
   mappings = (xmltoOntology) unmarshaller.unmarshal(new File(mappingFileDirectory));
   return mappings;
 }
 public static NeuralNetwork unmarsall(InputStream in) throws Exception {
   // TODO refactoring
   JAXBContext context = JAXBContext.newInstance(NeuralNetwork.class);
   Unmarshaller unmarshaller = context.createUnmarshaller();
   NeuralNetwork unmarshalledNn = (NeuralNetwork) unmarshaller.unmarshal(in);
   return unmarshalledNn;
 }
Ejemplo n.º 9
0
  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Libri.class);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    File xml = new File("./file/libri2.xml");

    // XML to Java Classes
    Libri libri = (Libri) unmarshaller.unmarshal(xml);

    for (Libro item : libri.getLibro()) {
      System.out.println(item.getTitolo());
      System.out.println(item.getAutore());
      System.out.println("-----------------");
    }

    // Java Classes to XML
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    marshaller.marshal(libri, System.out);

    System.out.println("");

    StringWriter sw = new StringWriter();
    marshaller.marshal(libri, sw);
    System.out.println(sw);
  }
Ejemplo n.º 10
0
  public void createPeriodActions() {
    try {
      JAXBContext jaxbContext = JAXBContext.newInstance(PeriodList.class);
      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
      StringReader stream =
          new StringReader(
              UIActivator.getDefault()
                  .getPreferenceStore()
                  .getString(UIActivator.PREFS_CHART_PERIODS));

      PeriodList list = (PeriodList) unmarshaller.unmarshal(stream);
      Collections.sort(
          list,
          new Comparator<Period>() {

            @Override
            public int compare(Period o1, Period o2) {
              if (o1.getPeriod().higherThan(o2.getPeriod())) {
                return -1;
              }
              if (o2.getPeriod().higherThan(o1.getPeriod())) {
                return 1;
              }
              return 0;
            }
          });

      periodActions = new ContributionItem[list.size()];
      for (int i = 0; i < periodActions.length; i++) {
        periodActions[i] = new ContributionItem(list.get(i));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  protected Credentials getCredentials(Representation entity, String entityText)
      throws IOException, JAXBException {

    Credentials creds = null;
    getLiberecoResourceLogger().debug("Entity text: " + entityText);

    if (entity.isCompatible(RestletConstants.APPLICATION_XML_VARIANT)) {
      JAXBContext jc = JAXBContext.newInstance(Request.class);
      Unmarshaller um = jc.createUnmarshaller();
      StringReader sr = new StringReader(entityText);

      Request req = (Request) um.unmarshal(sr);
      creds = req.getCredentials();
    } else if (entity.isCompatible(RestletConstants.APPLICATION_JSON_VARIANT)) {

      Gson gson = new GsonFactory().createGson();
      RequestJson reqJson = gson.fromJson(entityText, RequestJson.class);

      if (reqJson != null) {
        Request req = reqJson.getRequest();
        if (req != null) {
          creds = req.getCredentials();
        }
      }
    }

    getLiberecoResourceLogger().debug("Credentials = " + creds);

    return creds;
  }
Ejemplo n.º 12
0
  public DesignServiceManager() throws JAXBException, IOException {

    this.serviceDefinitions = new HashMap<Project, Map<String, Service>>();

    Unmarshaller unmarshaller = definitionsContext.createUnmarshaller();
    ClassPathResource primitiveServiceFile =
        new ClassPathResource("com/wavemaker/tools/service/primitive_types.xml");
    InputStream inputStream = primitiveServiceFile.getInputStream();
    try {
      Service primitiveService = (Service) unmarshaller.unmarshal(inputStream);
      this.primitiveTypes =
          Collections.unmodifiableList(primitiveService.getDataobjects().getDataobject());

      Map<String, String> m = new TreeMap<String, String>();

      for (DataObject o : this.primitiveTypes) {
        if (!o.isInternal()) {
          m.put(o.getName(), o.getJavaType());
        }
      }

      this.primitivesMap = Collections.unmodifiableMap(m);
    } finally {
      inputStream.close();
    }
  }
Ejemplo n.º 13
0
  public String updateTemplate(HttpHeaders hh, String payload) throws HelperException {
    logger.debug("StartOf updateTemplate payload:" + payload);
    try {
      JAXBContext context = JAXBContext.newInstance(Template.class);
      Unmarshaller unMarshaller = context.createUnmarshaller();

      eu.atos.sla.parser.data.wsag.Template templateXML =
          (eu.atos.sla.parser.data.wsag.Template) unMarshaller.unmarshal(new StringReader(payload));

      Template template = getTemplateForDB(templateXML, payload);

      boolean templateStored = this.templateDAO.update(template.getUuid(), template);
      ITemplate templateFromDatabase = new Template();

      String str = null;
      if (templateStored) {

        templateFromDatabase = this.templateDAO.getByUuid(template.getUuid());
        str = printTemplateToXML(templateFromDatabase);
      }
      logger.debug("EndOf updateTemplate");
      return str;

    } catch (JAXBException e) {
      logger.error("Error in updateTemplate ", e);
      throw new HelperException(
          Code.PARSER, "Error when updating template parsing file:" + e.getMessage());
    } catch (Throwable e) {
      logger.error("Error in updateTemplate ", e);
      throw new HelperException(Code.INTERNAL, "Error when updating template:" + e.getMessage());
    }
  }
Ejemplo n.º 14
0
  public static void main(String[] args) throws JAXBException {

    JAXBContext jc = JAXBContext.newInstance(MobilePhone.class);
    Unmarshaller u = jc.createUnmarshaller();
    MobilePhone mobilePhone = (MobilePhone) u.unmarshal(new File(Path.PHONE));
    System.out.println(mobilePhone);
  }
  /**
   * Parses the given set of input stream representing XML constraint mappings.
   *
   * @param mappingStreams The streams to parse. Must support the mark/reset contract.
   */
  public final void parse(Set<InputStream> mappingStreams) {

    try {
      JAXBContext jc = JAXBContext.newInstance(ConstraintMappingsType.class);

      for (InputStream in : mappingStreams) {

        String schemaVersion = xmlParserHelper.getSchemaVersion("constraint mapping file", in);
        String schemaResourceName = getSchemaResourceName(schemaVersion);
        Schema schema = xmlParserHelper.getSchema(schemaResourceName);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        unmarshaller.setSchema(schema);

        ConstraintMappingsType mapping = getValidationConfig(in, unmarshaller);
        String defaultPackage = mapping.getDefaultPackage();

        parseConstraintDefinitions(mapping.getConstraintDefinition(), defaultPackage);

        for (BeanType bean : mapping.getBean()) {
          Class<?> beanClass = getClass(bean.getClazz(), defaultPackage);
          checkClassHasNotBeenProcessed(processedClasses, beanClass);
          annotationProcessingOptions.ignoreAnnotationConstraintForClass(
              beanClass, bean.getIgnoreAnnotations());
          parseClassLevelOverrides(bean.getClassType(), beanClass, defaultPackage);
          parseFieldLevelOverrides(bean.getField(), beanClass, defaultPackage);
          parsePropertyLevelOverrides(bean.getGetter(), beanClass, defaultPackage);
          processedClasses.add(beanClass);
        }
      }
    } catch (JAXBException e) {
      throw log.getErrorParsingMappingFileException(e);
    }
  }
Ejemplo n.º 16
0
 public UnmarshalGetRequestParamsResponse unmarshalGetRequestParams(
     UnmarshalGetRequestParamsRequest inputPart) {
   UnmarshalGetRequestParamsResponse r = new UnmarshalGetRequestParamsResponse();
   try {
     JAXBContext jc;
     StringReader stringReader = new StringReader(inputPart.getXmlString());
     jc = JAXBContext.newInstance(GetRequestParams.class);
     Unmarshaller u = jc.createUnmarshaller();
     GetRequestParams params = new GetRequestParams();
     JAXBElement<GetRequestParams> root =
         u.unmarshal(new StreamSource(stringReader), GetRequestParams.class);
     params = root.getValue();
     r.setRawEthernet(params.isRawEthernet());
     r.setLRWidth(params.getLRWidth());
     r.setRLWidth(params.getRLWidth());
     r.setUuid(params.getUuid());
     for (FPGA f : params.getFPGA()) {
       FPGA fpga = new FPGA();
       fpga.setName(f.getName());
       for (String s : f.getLink()) {
         fpga.getLink().add(s);
       }
       r.getFPGA().add(fpga);
     }
     return r;
   } catch (Exception ex) {
     return null;
   }
 }
Ejemplo n.º 17
0
 public static OrcidMessage getProtectedOrcidMessage() throws JAXBException {
   JAXBContext context = JAXBContext.newInstance(PACKAGE);
   Unmarshaller unmarshaller = context.createUnmarshaller();
   return (OrcidMessage)
       unmarshaller.unmarshal(
           JaxbOrcidMessageUtil.class.getResourceAsStream(ORCID_PROTECTED_FULL_XML));
 }
Ejemplo n.º 18
0
  /**
   * Load anual hours xml file from disk and parse
   *
   * @return AnualHours java bean
   * @throws CRUDException
   */
  public static AnualHours loadAnualHoursFromXML() throws CRUDException {
    StringBuffer strBuffer = new StringBuffer();
    FileReader fr = null;
    try {
      // Read from file
      File archivo = ConfigurationUtils.getInputHoursFile();
      fr = new FileReader(archivo);
      BufferedReader br = new BufferedReader(fr);
      String str;
      while ((str = br.readLine()) != null) strBuffer.append(str);

      // Parse the XML
      final JAXBContext jaxbContext = JAXBContext.newInstance(AnualHours.class);
      final AnualHours aHours =
          (AnualHours)
              jaxbContext.createUnmarshaller().unmarshal(new StringReader(strBuffer.toString()));
      return aHours;
    } catch (Exception e) {
      throw new CRUDException(e);
    } finally {
      if (fr != null)
        try {
          fr.close();
        } catch (IOException e) {
          throw new CRUDException(e);
        }
    }
  }
 public static OAuthApp getOAuthApplicationData(String appName)
     throws DynamicClientRegistrationException {
   Resource resource;
   String resourcePath =
       DynamicClientRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH + "/" + appName;
   try {
     resource = DynamicClientWebAppRegistrationUtil.getRegistryResource(resourcePath);
     if (resource != null) {
       JAXBContext context = JAXBContext.newInstance(OAuthApp.class);
       Unmarshaller unmarshaller = context.createUnmarshaller();
       return (OAuthApp)
           unmarshaller.unmarshal(
               new StringReader(
                   new String(
                       (byte[]) resource.getContent(),
                       Charset.forName(
                           DynamicClientRegistrationConstants.CharSets.CHARSET_UTF8))));
     }
     return new OAuthApp();
   } catch (JAXBException e) {
     throw new DynamicClientRegistrationException(
         "Error occurred while parsing the OAuth application data : " + appName, e);
   } catch (RegistryException e) {
     throw new DynamicClientRegistrationException(
         "Error occurred while retrieving the Registry resource of OAuth application : " + appName,
         e);
   }
 }
 public static PackageDefinition readFromFile(URL resource) throws JAXBException, IOException {
   JAXBContext jc = JAXBContext.newInstance(PackageDefinition.class);
   Unmarshaller unmarshaller = jc.createUnmarshaller();
   Object unmarshal = unmarshaller.unmarshal(resource.openStream());
   PackageDefinition settings = (PackageDefinition) unmarshal;
   return settings;
 }
Ejemplo n.º 21
0
  // TODO - change the return type and the factory parameter to be Definitions and ObjectFactory,
  // and move to bpmn-schema
  public BpmnDefinitions correctFlowNodeRefs(
      final BpmnDefinitions definitions, final BpmnObjectFactory factory)
      throws JAXBException, TransformerException {

    JAXBContext context =
        JAXBContext.newInstance(
            factory.getClass(),
            com.processconfiguration.ObjectFactory.class,
            org.omg.spec.bpmn._20100524.di.ObjectFactory.class,
            org.omg.spec.bpmn._20100524.model.ObjectFactory.class,
            org.omg.spec.dd._20100524.dc.ObjectFactory.class,
            org.omg.spec.dd._20100524.di.ObjectFactory.class,
            com.signavio.ObjectFactory.class);

    // Marshal the BPMN into a DOM tree
    DOMResult intermediateResult = new DOMResult();
    Marshaller marshaller = context.createMarshaller();
    marshaller.marshal(factory.createDefinitions(definitions), intermediateResult);

    // Apply the XSLT transformation, generating a new DOM tree
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer =
        transformerFactory.newTransformer(
            new StreamSource(
                getClass().getClassLoader().getResourceAsStream("xsd/fix-flowNodeRef.xsl")));
    DOMSource finalSource = new DOMSource(intermediateResult.getNode());
    DOMResult finalResult = new DOMResult();
    transformer.transform(finalSource, finalResult);

    // Unmarshal back to JAXB
    Object def2 = context.createUnmarshaller().unmarshal(finalResult.getNode());
    return ((JAXBElement<BpmnDefinitions>) def2).getValue();
  }
Ejemplo n.º 22
0
 protected FigureType unmarshall(InputStream is) throws JAXBException, SAXException {
   Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
   Schema schema = getFigureSchema();
   unmarshaller.setSchema(schema);
   Object result = unmarshaller.unmarshal(is);
   return (FigureType) JAXBElement.class.cast(result).getValue();
 }
  /**
   * @param data xml stream
   * @param classe 类
   * @return jaxb生成xml的java 类对象
   */
  public static Object unmarshal(File file, Class<?> classe) throws JAXBException {

    JAXBContext context = JAXBCache.instance().getJAXBContext(classe);
    Unmarshaller unmarshaller = context.createUnmarshaller();

    return unmarshaller.unmarshal(file);
  }
Ejemplo n.º 24
0
  @Test
  public void testJaxb() throws JAXBException {
    Person pb = new Person();
    pb.setGivenName("Anton");
    pb.setFamilyName("Johansson");
    pb.setInstitution("TFE");
    List<String> emails = new ArrayList<String>();
    emails.add("*****@*****.**");
    emails.add("*****@*****.**");
    pb.setEmails(emails);

    JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);

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

    StringWriter writer = new StringWriter();

    m.marshal(pb, writer);
    System.out.println("======= Marshalling =============");
    System.out.println(writer);

    System.out.println("======= Unmarshalling =============");
    Unmarshaller um = jaxbContext.createUnmarshaller();
    Reader reader = new StringReader(writer.toString());
    Person umPb = (Person) um.unmarshal(reader);
    assertEquals(pb.getEmails().get(0), umPb.getEmails().get(0));
    assertEquals(pb.getEmails().get(1), umPb.getEmails().get(1));
    assertEquals(pb, umPb);
  }
Ejemplo n.º 25
0
  public static void main(String[] args) {
    List<Speaker> speakerList = new ArrayList<Speaker>();
    JAXBContext jaxbContext;
    OnlineJsonWriter jsonWriter = new OnlineJsonWriter();
    File outputFile = new File("speakerData.json");

    try {
      jaxbContext = JAXBContext.newInstance(Speakers.class);
      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
      File file = new File("SPEAKERS.xml");
      if (file.exists()) {
        System.out.println("File exists ...." + file.getName());
      }
      Speakers speakers = (Speakers) jaxbUnmarshaller.unmarshal(new FileInputStream(file));

      jsonWriter.writeSpeakerObjectToJason(speakers, outputFile);
      System.out.println("Speakers: " + speakers.getSpeakers());

      for (Speaker speaker : speakers.getSpeakers()) {
        speakerList.add(speaker);
      }
    } catch (JAXBException e) {
      System.err.println("Error: " + e);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 26
0
  /**
   * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], MultivaluedMap,
   *     InputStream)
   */
  @Override
  public Object readFrom(
      Class<Object> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, String> httpHeaders,
      InputStream entityStream)
      throws IOException {
    try {
      SAXParserFactory spf = SAXParserFactory.newInstance();
      spf.setXIncludeAware(isXIncludeAware());
      spf.setNamespaceAware(true);
      spf.setValidating(isValidatingDtd());
      spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isSecureProcessing());
      spf.setFeature(
          "http://xml.org/sax/features/external-general-entities", isExpandingEntityRefs());
      spf.setFeature(
          "http://xml.org/sax/features/external-parameter-entities", isExpandingEntityRefs());

      XMLReader reader = spf.newSAXParser().getXMLReader();
      JAXBContext jaxbContext = getJaxbContext(type);
      Unmarshaller um = jaxbContext.createUnmarshaller();
      return um.unmarshal(new SAXSource(reader, new InputSource(entityStream)));
    } catch (Exception e) {
      throw new IOException("Could not unmarshal to " + type.getName());
    }
  }
 protected Object wbxmlStream2Object(InputStream in, boolean event) throws Exception {
   XMLStreamReader xmlStreamReader = null;
   XMLEventReader xmlEventReader = null;
   try {
     if (event) {
       xmlEventReader = inFact.createXMLEventReader(in);
     } else {
       xmlStreamReader = inFact.createXMLStreamReader(in);
     }
     if (jc == null) {
       jc = JAXBContext.newInstance(Class.forName(this.def.getClazz()));
     }
     Unmarshaller unmarshaller = jc.createUnmarshaller();
     if (event) {
       return unmarshaller.unmarshal(xmlEventReader);
     } else {
       return unmarshaller.unmarshal(xmlStreamReader);
     }
   } finally {
     if (xmlStreamReader != null) {
       try {
         xmlStreamReader.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventReader != null) {
       try {
         xmlEventReader.close();
       } catch (Exception e) {
       }
     }
   }
 }
  @Override
  public WSNDeviceApp create(
      TestbedRuntime testbedRuntime, String applicationName, Object xmlConfig) {

    try {

      JAXBContext context = JAXBContext.newInstance(WsnDevice.class.getPackage().getName());
      Unmarshaller unmarshaller = context.createUnmarshaller();

      WsnDevice wsnDevice =
          (WsnDevice) ((JAXBElement) unmarshaller.unmarshal((Node) xmlConfig)).getValue();

      try {

        WSNDeviceAppConfiguration wsnDeviceAppConfiguration =
            createWsnDeviceAppConfiguration(wsnDevice);
        return new WSNDeviceAppImpl(testbedRuntime, wsnDeviceAppConfiguration);

      } catch (Exception e) {
        throw propagate(e);
      }

    } catch (JAXBException e) {
      throw propagate(e);
    }
  }
  @Test
  public void marshalling() throws Exception {
    MyInteger value = new MyInteger(1);

    // MyInteger cannot be marshalled because it
    // lacks @XmlRootElement.

    JAXBContext context = JAXBContext.newInstance(MyInteger.class);
    StringWriter writer = new StringWriter();
    try {
      context.createMarshaller().marshal(value, writer);
      fail();
    } catch (MarshalException ex) {
      // Expected.
    }

    // When MyInteger is wrapped by RootElementWrapper,
    // marshalling becomes possible.

    RootElementWrapper<MyInteger> w = new RootElementWrapper<MyInteger>(value);

    context = JAXBContext.newInstance(RootElementWrapper.class, MyInteger.class);
    writer = new StringWriter();
    context.createMarshaller().marshal(w, writer);
    assertEquals(w, (context.createUnmarshaller().unmarshal(new StringReader(writer.toString()))));
  }
Ejemplo n.º 30
0
  @Test
  public void testSuspendUntil() throws Exception {
    JAXBContext c = JAXBContext.newInstance("org.apache.hise.lang.xsd.htdt");
    Unmarshaller m = c.createUnmarshaller();
    m.setSchema(
        SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema")
            .newSchema(getClass().getResource("/ws-humantask-api-wsdl.xsd")));
    SuspendUntil e =
        (SuspendUntil) m.unmarshal(getClass().getResourceAsStream("/suspendUntil.xml"));
    XQueryEvaluator ev = new XQueryEvaluator();
    Date d =
        (Date)
            ev.evaluateExpression(
                    "declare namespace xsd='http://www.w3.org/2001/XMLSchema'; xsd:dateTime('2009-01-01T12:59:34')",
                    null)
                .get(0);
    System.out.println(d);
    e.getTime().getTimePeriod().addTo(d);

    Date d2 =
        (Date)
            ev.evaluateExpression(
                    "declare namespace xsd='http://www.w3.org/2001/XMLSchema'; xsd:dateTime('2009-01-04T12:59:34')",
                    null)
                .get(0);
    System.out.println(d2);
    Assert.assertEquals(d2, d);
    System.out.println(d);
  }