Exemplo n.º 1
0
  /** tests the behavior of XML id/idref. */
  public void testXMLIDIDREF() throws Exception {
    Person person = new Person();
    person.id = "me";
    person.name = "me";
    person.father = new Person();
    person.father.id = "father";
    person.father.name = "father";
    person.mother = new Person();
    person.mother.id = "mother";
    person.mother.name = "mother";

    NonRefPerson nonRefperson = new NonRefPerson();
    nonRefperson.id = "me";
    nonRefperson.name = "me";
    nonRefperson.father = "father";
    nonRefperson.mother = "mother";

    Marshaller marshaller = JAXBContext.newInstance(NonRefPerson.class).createMarshaller();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    marshaller.marshal(nonRefperson, out);
    Unmarshaller unmarshaller = JAXBContext.newInstance(Person.class).createUnmarshaller();
    byte[] bytes = out.toByteArray();
    //    System.out.println(new String(bytes, "utf-8"));
    Person deserializedPerson = (Person) unmarshaller.unmarshal(new ByteArrayInputStream(bytes));
    assertEquals("me", deserializedPerson.id);
    assertEquals("me", deserializedPerson.name);
    assertNull(
        "The XMLID/IDREF tests have failed, meaning JAXB's doing some inference, and you may need add back the ID/IDREF warnings.",
        deserializedPerson.father);
    assertNull(
        "The XMLID/IDREF tests have failed, meaning JAXB's doing some inference, and you may need add back the ID/IDREF warnings.",
        deserializedPerson.mother);
  }
  @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()))));
  }
Exemplo n.º 3
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();
  }
Exemplo n.º 4
0
  /**
   * Loans (and legacy insurance) disbursement data submit routine<br>
   * Disburses one account at a time to a specific folder
   *
   * @return returns the loans xml as a string
   */
  public BaseServiceResponse disburse(LoansXML request, BaseServiceResponse response)
      throws ServiceException {
    // use this to get a handle on the IFS share stored inside the connection element
    initialize(BayServConstants.rpgService, response);
    // initialise the XML context
    try {
      if (disbursementCtx == null) disbursementCtx = JAXBContext.newInstance(LoansXML.class);
      if (errorCtx == null) errorCtx = JAXBContext.newInstance(ERRORSXML.class);
    } catch (JAXBException e) {
      throw new ServiceException(ErrorCodes.RPG006, e);
    }

    // put the result into exactus filesystem via AS400
    String loanReference = saveDisbursementFile(request, PATH_LOAN);

    // sleep
    DateUtils.sleep(1);

    // call the RPG to read the result and throw an error if there is one
    try {
      disburseRPG.execute(EProductType.LOAN, loanReference);
    } catch (ServiceException e) {
      // see if there's an error file
      response.setError(true);
      response.getErrors().addAll(findErrorXML(request, PATH_LOAN));
    }

    response.setXmlData(new XMLData());
    response.getXmlData().setXml(renderDisbursementXML(request));

    return response;
  }
Exemplo n.º 5
0
  @Override
  public void integrateXMLs(String xmlFileName) {
    // Will collect Bikelists from all XML files.
    List<Bikelist> listOfBikeList = new ArrayList<Bikelist>();

    try {
      // Folder where all the XML files are stored.
      File f = new File("data");
      // Searching every xml file in the data folder.
      for (final File fileEntry : f.listFiles()) {
        int i = fileEntry.getName().lastIndexOf(".");
        String extension = fileEntry.getName().substring(i + 1);

        if (fileEntry.isFile()
            && !fileEntry.getName().equalsIgnoreCase("IntegratedXMLFile.xml")
            && extension.equals("xml")) {
          JAXBContext context = JAXBContext.newInstance(JAXB_CONTEXT_PACKAGE);
          Bikelist b = (Bikelist) context.createUnmarshaller().unmarshal(fileEntry);

          listOfBikeList.add(b);
        }
      }

      // A final list of bikes gathered from different bikelists.
      Bikelist bikelistclass = new Bikelist();
      List<Bike> finalBikeList = bikelistclass.getBike();

      // Merging bikelists from all the XML files
      for (Bikelist bikelist : listOfBikeList) {
        for (Bike bike : bikelist.getBike()) {
          finalBikeList.add(bike);
        }
      }

      // have to merge this list with list from the Integrated XML file.

      JAXBContext context1 = JAXBContext.newInstance(JAXB_CONTEXT_PACKAGE);
      f = new File("xmlfiles" + File.separator + "IntegratedXML.xml");

      FileOutputStream fos = null;
      try {
        JAXBContext jaxbContext = JAXBContext.newInstance(JAXB_CONTEXT_PACKAGE);
        Marshaller marshaller = jaxbContext.createMarshaller();
        fos = new FileOutputStream(XML_FILES_FOLDER + File.separator + "integratedXMLFile.xml");

        marshaller.marshal(bikelistclass, fos);
      } catch (IOException | JAXBException e) {
        e.printStackTrace();
      } finally {
        try {
          fos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }

    } catch (JAXBException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 6
0
  private static void createXml(TestObjects testObjects) throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(Characters.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    File file = new File("Characters.xml");
    marshaller.marshal(testObjects.getCharacters(), file);

    file = new File("LearningObjectiveOut.xml");
    jaxbContext = JAXBContext.newInstance(LearningAct.class);
    marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(testObjects.getLearningAct(), file);

    file = new File("ThemeOut.xml");
    jaxbContext = JAXBContext.newInstance(Theme.class);
    marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(testObjects.getTheme(), file);

    file = new File("LocaleOut.xml");
    jaxbContext = JAXBContext.newInstance(Locale.class);
    marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(testObjects.getLocale(), file);
  }
Exemplo n.º 7
0
  public static void main(String[] args) {
    Edge p = Edge.of(12.3, 4.2, 4.1, 22.3);

    try {

      File file = new File("C:\\file.xml");
      JAXBContext jaxbContext = JAXBContext.newInstance(Edge.class);
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

      // output pretty printed
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

      jaxbMarshaller.marshal(p, file);
      jaxbMarshaller.marshal(p, System.out);

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

    try {

      File file = new File("C:\\file.xml");
      JAXBContext jaxbContext = JAXBContext.newInstance(Edge.class);

      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
      Edge unp = (Edge) jaxbUnmarshaller.unmarshal(file);
      System.out.println(unp);

    } catch (JAXBException e) {
      e.printStackTrace();
    }
  }
  protected void renderMergedOutputModel(
      Object xmlObject,
      HttpServletRequest request,
      HttpServletResponse response,
      String type,
      String contentXML) {
    PrintWriter writer = null;
    if (xmlObject == null) {
      log.error("xmlObject is Null");
      return;
    }
    try {
      response.setContentType(CONTENT_TYPE_XML);
      WrapperResponse resp = new WrapperResponse(response);
      writer = resp.getWriter();
      JAXBContext jaxbContext = null;

      // 文件保存路径:
      String savePath = COMMIT_XML_SAVE_PATH + type + ".xml";

      if (SALE.equals(type))
        jaxbContext =
            JAXBContext.newInstance(
                cn.hshb.web.partner.baidu.entity.newest.houseSecond.Urlset.class);
      else if ("saleDel".equals(type))
        jaxbContext =
            JAXBContext.newInstance(
                cn.hshb.web.partner.baidu.entity.newest.houseSecondDel.Urlset.class);
      else if (RENT.equals(type))
        jaxbContext =
            JAXBContext.newInstance(cn.hshb.web.partner.baidu.entity.newest.houseRent.Urlset.class);
      else if (COMMUNITY.equals(type))
        jaxbContext =
            JAXBContext.newInstance(cn.hshb.web.partner.baidu.entity.newest.community.Urlset.class);
      else if ("rentDel".equals(type))
        jaxbContext =
            JAXBContext.newInstance(
                cn.hshb.web.partner.baidu.entity.newest.houseRentDel.Urlset.class);

      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
      jaxbMarshaller.marshal(xmlObject, writer);
      writer.flush();

      String content = resp.getContent();
      // 对这数据进行保存,以便查看
      new DocumentXML(savePath, content);
      resp.superWrite(content);
      resp.superFlush();
    } catch (Exception ex) {
      log.error(
          "JAXB Exception while rendering XML response to client: " + request.getRemoteAddr(), ex);
    } finally {
      if (writer != null) {
        writer.flush();
        writer.close();
        writer = null;
      }
    }
  }
 /** Added the generated SOAP package to the JAXB context so Soap datatypes are available */
 @Override
 protected JAXBContext createContext() throws JAXBException {
   if (getContextPath() != null) {
     return JAXBContext.newInstance(adapter.getSoapPackageName() + ":" + getContextPath());
   } else {
     return JAXBContext.newInstance();
   }
 }
  static {
    try {
      MARSHALLER = JAXBContext.newInstance(HibernateDatabase.class);
      INDEX_MARSHALLER = JAXBContext.newInstance(HibernateIndexNames.class);

    } catch (JAXBException e) {
      throw Throwables.propagate(e);
    }
  }
Exemplo n.º 11
0
 public RoutingDAO() {
   try {
     unmarshaller = JAXBContext.newInstance(LineStringType.class).createUnmarshaller();
     context = JAXBContext.newInstance("org.jvnet.ogc.gml.v_3_1_1.jts");
     marshaller = context.createMarshaller();
   } catch (JAXBException e) {
     LOG.error(e, e);
   }
 }
  public DeliveryOrderManagerImpl(GenericDao<DeliveryOrder, String> genericDao)
      throws JAXBException {
    super(genericDao);
    JAXBContext jc = JAXBContext.newInstance("com.faurecia.model.delvry");
    marshaller = jc.createMarshaller();

    JAXBContext jc2 = JAXBContext.newInstance("com.faurecia.lisa.kmp58");
    unmarshaller = jc2.createUnmarshaller();
  }
 public AlfrescoArtifactExporter() {
   // Initialize writers for artifacts
   bpmnConverter = new BpmnXMLConverter();
   try {
     modelJaxbContext = JAXBContext.newInstance(M2Model.class);
     moduleJaxbContext = JAXBContext.newInstance(Module.class, AlfrescoConfiguration.class);
     beansJaxbContext = JAXBContext.newInstance(Beans.class);
   } catch (JAXBException jaxbe) {
     throw new AlfrescoSimpleWorkflowException(
         "Error while building JAXB-context for exporting content-model", jaxbe);
   }
 }
Exemplo n.º 14
0
  /** @return the {@link JAXBContext} */
  public synchronized JAXBContext getJAXBContext() {
    if (this._Context == null)
      try {
        this._Context =
            (getID().getObjectTypes() != null && getID().getObjectTypes().length > 0)
                ? (JAXBContext) JAXBContext.newInstance(getID().getObjectTypes())
                : (JAXBContext)
                    JAXBContext.newInstance(getID().getObjectFactoryType().getPackage().getName());
      } catch (final JAXBException e) {
        throw CoalaExceptionFactory.INCONSTRUCTIBLE.createRuntime(e, JAXBContext.class, null);
      }

    return this._Context;
  }
Exemplo n.º 15
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"));
    }
  }
Exemplo n.º 16
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());
  }
Exemplo n.º 17
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();
  }
Exemplo n.º 18
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();
    }
  }
 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;
 }
 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) {
       }
     }
   }
 }
 /**
  * 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");
   }
 }
Exemplo n.º 22
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));
 }
Exemplo n.º 23
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 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;
 }
Exemplo n.º 25
0
 static {
   try {
     dataContext = JAXBContext.newInstance(Data.class);
   } catch (JAXBException e) {
     LOGGER.error("Unable to create JAXB Context for Data Element. Error: {}", e.getMessage());
   }
 }
 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);
   }
 }
Exemplo n.º 27
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;
  }
  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;
  }
 private List<BroadcastMetadata> getBroadcastMetadata(
     List<String> fileObjectPids, InfrastructureContext context, TranscodeRequest request)
     throws ProcessorException {
   Map<String, BroadcastMetadata> pidMap = new HashMap<String, BroadcastMetadata>();
   CentralWebservice doms = CentralWebserviceFactory.getServiceInstance(context);
   List<BroadcastMetadata> broadcastMetadataList = new ArrayList<BroadcastMetadata>();
   for (String fileObjectPid : fileObjectPids) {
     BroadcastMetadata broadcastMetadata = null;
     try {
       String broadcastMetadataXml =
           doms.getDatastreamContents(fileObjectPid, "BROADCAST_METADATA");
       logger.debug("Found file metadata '" + fileObjectPid + "' :\n" + broadcastMetadataXml);
       broadcastMetadata =
           JAXBContext.newInstance(BroadcastMetadata.class)
               .createUnmarshaller()
               .unmarshal(
                   new StreamSource(new StringReader(broadcastMetadataXml)),
                   BroadcastMetadata.class)
               .getValue();
     } catch (Exception e) {
       throw new ProcessorException(
           "Failed to get Broadcast Metadata for " + request.getObjectPid(), e);
     }
     broadcastMetadataList.add(broadcastMetadata);
     pidMap.put(fileObjectPid, broadcastMetadata);
   }
   request.setPidMap(pidMap);
   return broadcastMetadataList;
 }
 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;
 }