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.º 2
0
  public void init(@Observes @Initialize String event) {
    // Chargement de la conf
    String userDir = System.getProperty("user.dir");
    File directory = new File(userDir);
    if (!directory.canRead() || !directory.canWrite())
      throw new BackException("Can't initialize application");
    configurationFile = new File(userDir + "/configuration.k");
    if (!configurationFile.exists()) {
      initConfigurationFile(configurationFile, userDir);
    }
    loadKConfiguration(configurationFile);

    // Chargement du fichier de sauvegarde
    String directionSaveFile = getDirectorySave();
    File tmpSaveFile = new File(directionSaveFile);
    if (!tmpSaveFile.exists()) throw new BackException("Can't initialize application");
    tmpSaveFile = new File(directionSaveFile + "/" + SAVE_FILENAME);
    if (!tmpSaveFile.exists()) {
      try {
        tmpSaveFile.createNewFile();
        JAXBContext jaxbContext = JAXBContext.newInstance(DtoPortfolio.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(new DtoPortfolio(), tmpSaveFile);
      } catch (IOException | JAXBException e) {
        throw new BackException("Can't initialize application");
      }
    }
    saveFile = tmpSaveFile;
    loadSaveFile();
    if (migration != null) migration.fire(this);
    if (initialisation != null) initialisation.fire("");
  }
 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
  /**
   * Statische Funktion die ein XML-Trefferdokument erzeugt
   *
   * @param feedDetails Vector der NewsItems-Objekte enthält
   * @param strWhichInputType Zeichenkette für den XML-Dateinamen
   * @throws JAXBException
   */
  public static void write_XML_File(Vector<NewsItems> feedDetails, String strWhichInputType)
      throws JAXBException {
    TrefferDokument trefferDokument = new TrefferDokument();

    for (int i = 0; i < feedDetails.size(); i++) {

      /*
       * Hier werden die Klassen benutzt, die mittels xjc erstellt
       * worden. gut nachzuvollziehen, wenn sich die assignment2.xsd
       * angeschaut wird.
       */
      TrefferType type = new TrefferType();
      ItemType item = new ItemType();

      item.setTitle(feedDetails.get(i).getTitle());
      item.setDescription(feedDetails.get(i).getDescription());

      type.getItem().add(item);
      trefferDokument.getTreffer().add(type);

      JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class);
      Marshaller m = jc.createMarshaller();
      /*
       * Output wird für eine gewohnte Lesbarkeit formatiert
       */
      m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

      m.marshal(trefferDokument, new File(strWhichInputType + ".xml"));
    }
  }
 /**
  * Cenverte o objeto informado para uma String que representa o XML do objeto.
  *
  * @param <T> Tipo generico que informa a classe
  * @param object O objeto a ser convertido. A classe deste objeto deve conter as anotações de
  *     JAXB.
  * @param schemaLocation {@link URL} do schema.
  * @return
  * @throws JAXBException
  */
 @SuppressWarnings("unchecked")
 public static <T> String marshal(T object, URL schemaLocation) throws JAXBException {
   Class<T> objClass = (Class<T>) object.getClass();
   JAXBContext context = JAXBContext.newInstance(objClass);
   Marshaller marshaller = context.createMarshaller();
   StringWriter sWriter = new StringWriter();
   XmlSchema xmlSchema = objClass.getPackage().getAnnotation(XmlSchema.class);
   if (xmlSchema != null && xmlSchema.namespace() != null) {
     XmlType xmlType = objClass.getAnnotation(XmlType.class);
     if (xmlType != null && xmlType.name() != null) {
       QName qName = new QName(xmlSchema.namespace(), xmlType.name());
       JAXBElement<T> elem = new JAXBElement<T>(qName, objClass, object);
       if (schemaLocation != null) {
         SchemaFactory schemaFactory =
             SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
         try {
           Schema schema = schemaFactory.newSchema(schemaLocation);
           marshaller.setSchema(schema);
         } catch (SAXException e) {
           e.printStackTrace();
         }
       }
       marshaller.marshal(elem, sWriter);
       return sWriter.toString();
     } else {
       throw new JAXBException("The xmlType could not be identified in class annotation");
     }
   } else {
     throw new JAXBException("The namespace could not be identified from package-info class");
   }
 }
Ejemplo n.º 6
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();
  }
  /**
   * 生成xml文件的二进制数据,"D:\\HelloWorld.xml"
   *
   * @param obj 对象
   */
  public static File marshal(Object obj, String filePath) throws JAXBException {
    if (StringUtil.isEmpty(filePath)) {
      return null;
    }

    File file = new File(filePath);

    if (file == null) {
      return null;
    }

    // 初始化JAXBContext.JAXBContext类提供的JAXB API的客户端的入口点。
    // 它提供一个抽象的用于管理XML / Java绑定的必要信息,以实现JAXB绑定框架行动:解组,编组和验证。
    JAXBContext context = JAXBCache.instance().getJAXBContext(obj.getClass());

    // 将Java对象Marshal成XML内容的Marshal的初始化设置.
    Marshaller jaxbMarshaller = context.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, UTF8);
    jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, false); // 是否包含头信息
    jaxbMarshaller.marshal(obj, file); // 输出到文件
    jaxbMarshaller.marshal(obj, System.out); // 控制台输出

    return file;
  }
Ejemplo n.º 8
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());
    }
  }
  @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);
    }
  }
 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.º 11
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.º 12
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);
        }
    }
  }
Ejemplo n.º 13
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.º 14
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();
    }
  }
  public static boolean putOAuthApplicationData(OAuthApp oAuthApp)
      throws DynamicClientRegistrationException {
    boolean status = false;
    try {
      if (log.isDebugEnabled()) {
        log.debug("Persisting OAuth application data in Registry");
      }
      StringWriter writer = new StringWriter();
      JAXBContext context = JAXBContext.newInstance(OAuthApp.class);
      Marshaller marshaller = context.createMarshaller();
      marshaller.marshal(oAuthApp, writer);

      Resource resource = DynamicClientWebAppRegistrationUtil.getGovernanceRegistry().newResource();
      resource.setContent(writer.toString());
      resource.setMediaType(DynamicClientRegistrationConstants.ContentTypes.MEDIA_TYPE_XML);
      String resourcePath =
          DynamicClientRegistrationConstants.OAUTH_APP_DATA_REGISTRY_PATH
              + "/"
              + oAuthApp.getWebAppName();
      status = DynamicClientWebAppRegistrationUtil.putRegistryResource(resourcePath, resource);
    } catch (RegistryException e) {
      throw new DynamicClientRegistrationException(
          "Error occurred while persisting OAuth application data : " + oAuthApp.getClientName(),
          e);
    } catch (JAXBException e) {
      e.printStackTrace();
    }
    return status;
  }
Ejemplo n.º 16
0
  @Ignore
  public void testGetMyTasks() throws Exception {

    TaskOperationsImpl ti = new MockTaskOperationsImpl();

    HISEEngineImpl he = new HISEEngineImpl();
    he.setHiseUserDetails(
        new HISEUserDetails() {
          public String getUserPassword(String user) {
            return null;
          }

          public Collection<String> getUserGroups(String user) {
            return Collections.singleton("group1");
          }
        });

    MockHiseDao dao = new MockHiseDao();
    he.setHiseDao(dao);
    ti.setHiseEngine(he);

    List<TTask> r = ti.getMyTasks("ALL", "ACTUALOWNER", "", Collections.EMPTY_LIST, "", "", 100);
    System.out.println(r.toString());

    JAXBContext c = JAXBContext.newInstance("org.apache.hise.lang.xsd.htda");

    Marshaller m = c.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.marshal(
        new JAXBElement(
            QName.valueOf("{http://www.example.org/WS-HT/api/xsd}taskAbstract"),
            TTask.class,
            r.get(0)),
        System.out);
  }
 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;
 }
Ejemplo n.º 18
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);
  }
  /**
   * @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.º 20
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.º 21
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.º 22
0
  private void write(String metadataFileName, EntityType entityType) {
    OutputStream output = null;

    try {
      JAXBContext context = JAXBContext.newInstance(ObjectFactory.class.getPackage().getName());
      Marshaller marshaller = context.createMarshaller();

      output = new FileOutputStream(metadataFileName);
      /*
       * Informa que o arquivo gerado deve conter um schemaLocation e ser formatado.
       * Fontes:
       * http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/1.5/tutorial/doc/JAXBWorks2.html
       */
      marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, PROPERTY_SCHEMA_LOCATION_VALUE);
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, PROPERTY_FORMATTED_VALUE);
      marshaller.marshal(entityType, output);

    } catch (Exception e) {
      IStatus status =
          new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error writing metadata file.", e);
      Activator.getDefault().getLog().log(status);

    } finally {
      try {
        output.close();

      } catch (IOException e) {
        IStatus status =
            new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error closing metadata file.", e);
        Activator.getDefault().getLog().log(status);
      }
    }
  }
Ejemplo n.º 23
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.º 24
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.º 25
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);
      }
    }
  }
 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;
 }
 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) {
       }
     }
   }
 }
 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);
   }
 }
Ejemplo n.º 29
0
  public String objectToXml(Object object) {
    String rtnStr = "";
    try {

      JAXBContext jaxbContext = cachedJaxb.get(pkgName);
      if (jaxbContext == null) {
        jaxbContext = JAXBContext.newInstance(pkgName);
        cachedJaxb.put(pkgName, jaxbContext);
      }

      Marshaller marshaller = jaxbContext.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_ENCODING, BcConstants.ENCODING);
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);

      Class docClazz = Class.forName(pkgName + ".Document");
      Class ofClazz = Class.forName(pkgName + ".ObjectFactory");
      Object factory = ofClazz.newInstance();
      Method method = ofClazz.getDeclaredMethod("createDocument", docClazz);
      JAXBElement jaxbElement = (JAXBElement) method.invoke(factory, docClazz.cast(object));

      StringWriter sw = new StringWriter();
      marshaller.marshal(jaxbElement, sw);
      rtnStr = sw.toString();

      // TODO remove the header in a better way: <?xml version="1.0" encoding="UTF-8"
      // standalone="yes"?>
      rtnStr = StringUtils.substringAfter(rtnStr, "?>").trim();
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e);
    }
    return rtnStr;
  }
Ejemplo n.º 30
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());
    }
  }