Java 类javax.xml.bind.JAXB 实例源码

项目:LivroJavaComoProgramar10Edicao    文件:EquationGeneratorXMLResource.java   
@GET
@Path("{operation}/{level}")
@Produces("application/xml")
public String getXml(@PathParam("operation") String operation,
   @PathParam("level") int level)
{
   // compute minimum and maximum values for the numbers
   int minimum = (int) Math.pow(10, level - 1);
   int maximum = (int) Math.pow(10, level);

   // create the numbers on the left-hand side of the equation
   int first = randomObject.nextInt(maximum - minimum) + minimum;
   int second = randomObject.nextInt(maximum - minimum) + minimum;

   // create Equation object and marshal it into XML
   Equation equation = new Equation(first, second, operation);
   StringWriter writer = new StringWriter(); // XML output here
   JAXB.marshal(equation, writer); // write Equation to StringWriter
   return writer.toString(); // return XML string
}
项目:LivroJavaComoProgramar10Edicao    文件:WelcomeRESTXMLClientJFrame.java   
private void submitJButtonActionPerformed(//GEN-FIRST:event_submitJButtonActionPerformed
   java.awt.event.ActionEvent evt)
{//GEN-HEADEREND:event_submitJButtonActionPerformed
   String name = nameJTextField.getText(); // get name from JTextField

   // the URL for the REST service
   String url = "http://localhost:8080/WelcomeRESTXML/" +
      "webresources/welcome/" + name;

   // read from URL and convert from XML to Java String
   String message = JAXB.unmarshal(url, String.class);

   // display the message to the user
   JOptionPane.showMessageDialog(this, message,
         "Welcome", JOptionPane.INFORMATION_MESSAGE);
}
项目:LivroJavaComoProgramar10Edicao    文件:EquationGeneratorXMLClientJFrame.java   
private void generateJButtonActionPerformed(//GEN-FIRST:event_generateJButtonActionPerformed
   java.awt.event.ActionEvent evt)
{//GEN-HEADEREND:event_generateJButtonActionPerformed
   try
   {
      String url = String.format("http://localhost:8080/" +
         "EquationGeneratorXML/webresources/equation/%s/%d",
         operation, difficulty);

      // convert XML back to an Equation object
      Equation equation = JAXB.unmarshal(url, Equation.class);

      answer = equation.getResult();
      equationJLabel.setText(equation.getLeftHandSide() + " =");
      checkAnswerJButton.setEnabled(true);
   } 
   catch (Exception exception)
   {
      exception.printStackTrace();
   } 
}
项目:personium-core    文件:ServiceSchmaTest.java   
/**
 * スキーマのスキーマ情報を取得するテスト$metadata_$metadata.
 */
@Test
public final void スキーマのスキーマ情報を取得するテスト$metadata_$metadata() {

    TResponse res = Http.request("box/$metadata-$metadata-get.txt")
            .with("path", "\\$metadata/\\$metadata")
            .with("col", "setodata")
            .with("accept", "application/xml")
            .with("token", PersoniumUnitConfig.getMasterToken())
            .returns()
            .statusCode(HttpStatus.SC_OK)
            .debug();

    // レスポンスボディーのチェック
    String str = res.getBody();

    Edmx edmx = JAXB.unmarshal(new StringReader(str), Edmx.class);
    Edmx checkBody = getRightEdmx();
    assertTrue(checkBody.equals(edmx));
}
项目:TLS-Attacker    文件:ActionTestUtils.java   
/**
 * Verify that unmarshal(marshal(TlsAction)) for empty action equals
 * original action.
 * <p>
 * "Empty" action refers to a TlsAction instance initialized with empty
 * constructor and without any additional values set.
 * <p>
 * Calling this method is expensive. <b>Should be invoked by tests in
 * 
 * @Category(SlowTests.class) only</b>
 *                            <p>
 * 
 * @param actionClass
 *            the Class to test
 * @param logger
 *            to which messages are written to
 * @see this.marshalingEmptyActionYieldsMinimalOutput(Class<T>)
 */
public static <T extends TlsAction> void marshalingAndUnmarshalingEmptyObjectYieldsEqualObject(
        Class<T> actionClass, Logger logger) {
    try {
        T action = actionClass.newInstance();
        StringWriter writer = new StringWriter();

        action.filter();
        JAXB.marshal(action, writer);
        TlsAction actual = JAXB.unmarshal(new StringReader(writer.getBuffer().toString()), actionClass);
        action.normalize();
        actual.normalize();

        assertEquals(action, actual);
    } catch (InstantiationException | IllegalAccessException ex) {
        logger.error(ex.getLocalizedMessage(), ex);
        fail();
    }
}
项目:TEI-Completer    文件:JerseyClientTest.java   
/**
 * Same as {@link MockServer#getLemmaSelection_Xml(String)} except the
 * output is forcefully encoded as GZIP
 */
@GET
@Path("getlemma/gzip/xml/{selection}")
public Response getLemmaSelection_Gzip_Xml(@PathParam("selection") final String selection) throws IOException {
    try(final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        try(final GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
            JAXB.marshal(getTestSuggestions(selection, null), gzos);
        }

        return Response.status(Response.Status.OK)
                .entity(baos.toByteArray())
                .encoding("gzip")
                .build();
    }
}
项目:TEI-Completer    文件:JerseyClientTest.java   
/**
 * Same as {@link MockServer#getLemmaSelectionWithDependent_Xml(String, String)} except the
 * output is forcefully encoded as GZIP
 */
@GET
@Path("getlemma/gzip/xml/{selection}/{dependent}")
@Produces({MediaType.APPLICATION_XML})
public Response getLemmaSelectionWithDependent_Gzip_Xml(@PathParam("selection") final String selection, @PathParam("dependent") final String dependent) throws IOException {
    try(final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        try(final GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
            JAXB.marshal( getTestSuggestions(selection, dependent), gzos);
        }

        return Response.status(Response.Status.OK)
                .entity(baos.toByteArray())
                .encoding("gzip")
                .build();
    }
}
项目:EGKfeuer    文件:CardReaderServiceTest.java   
@Test
public void unmarschallTest()
{
    UCPersoenlicheVersichertendatenXML pd = JAXB
            .unmarshal(
                    new StringReader(
                            "<?xml version=\"1.0\" encoding=\"ISO-8859-15\" standalone=\"yes\"?><UC_PersoenlicheVersichertendatenXML CDM_VERSION=\"5.1.0\" xmlns=\"http://ws.gematik.de/fa/vsds/UC_PersoenlicheVersichertendatenXML/v5.1\"><Versicherter><Versicherten_ID>H719994900</Versicherten_ID><Person><Geburtsdatum>19901124</Geburtsdatum><Vorname>Niklas</Vorname><Nachname>Bunge</Nachname><Geschlecht>M</Geschlecht><StrassenAdresse><Postleitzahl>74072</Postleitzahl><Ort>Heilbronn</Ort><Land><Wohnsitzlaendercode>D</Wohnsitzlaendercode></Land><Strasse>Oststr.</Strasse><Hausnummer>100</Hausnummer></StrassenAdresse></Person></Versicherter></UC_PersoenlicheVersichertendatenXML>"),
                    UCPersoenlicheVersichertendatenXML.class);

    UCPersoenlicheVersichertendatenXML pd2 = JAXB
            .unmarshal(
                    new StringReader(
                            "<?xml version=\"1.0\" encoding=\"ISO-8859-15\" standalone=\"yes\"?><UC_PersoenlicheVersichertendatenXML CDM_VERSION=\"5.1.0\" xmlns=\"http://ws.gematik.de/fa/vsds/UC_PersoenlicheVersichertendatenXML/v5.1\"><Versicherter><Versicherten_ID>D110104619</Versicherten_ID><Person><Geburtsdatum>19800112</Geburtsdatum><Vorname>Ltu</Vorname><Nachname>Musterkarte-0461</Nachname><Geschlecht>M</Geschlecht><StrassenAdresse><Postleitzahl>24937</Postleitzahl><Ort>Flensburg</Ort><Land><Wohnsitzlaendercode>D</Wohnsitzlaendercode></Land><Strasse>M�hlenstr.</Strasse><Hausnummer>46</Hausnummer></StrassenAdresse></Person></Versicherter></UC_PersoenlicheVersichertendatenXML>"),
                    UCPersoenlicheVersichertendatenXML.class);

    UCPersoenlicheVersichertendatenXML pd3 = JAXB
            .unmarshal(
                    new StringReader(
                            "<?xml version=\"1.0\" encoding=\"ISO-8859-15\" standalone=\"yes\"?><UC_PersoenlicheVersichertendatenXML CDM_VERSION=\"5.1.0\" xmlns=\"http://ws.gematik.de/fa/vsds/UC_PersoenlicheVersichertendatenXML/v5.1\"><Versicherter><Versicherten_ID>D110104619</Versicherten_ID><Person><Geburtsdatum>19800112</Geburtsdatum><Vorname>Ltu</Vorname><Nachname>Musterkarte-0461</Nachname><Geschlecht>M</Geschlecht><StrassenAdresse><Postleitzahl>24937</Postleitzahl><Ort>Flensburg</Ort><Land><Wohnsitzlaendercode>D</Wohnsitzlaendercode></Land><Strasse>Mühlenstr.</Strasse><Hausnummer>46</Hausnummer></StrassenAdresse></Person></Versicherter></UC_PersoenlicheVersichertendatenXML>"),
                    UCPersoenlicheVersichertendatenXML.class);

    assertNotNull(pd.getVersicherter());
    assertNotNull(pd2.getVersicherter());
    assertNotNull(pd3.getVersicherter());
    assertNotNull(pd.getVersicherter().getPerson());
}
项目:scelight    文件:InstanceMonitor.java   
/**
 * Creates a new {@link InstanceMonitor}.
 */
public InstanceMonitor() {
    super( "Instance monitor" );

    ServerSocket serverSocket = null;
    try {
        // Pass 0 as port so the system will choose a free / available port for us.
        serverSocket = new ServerSocket( 0, 0, InetAddress.getByName( "localhost" ) );

        Env.LOGGER.trace( "Instance monitor listening on local port: " + serverSocket.getLocalPort() );

        // Save instance monitor info bean
        final InstMonInfBean imi = new InstMonInfBean();
        imi.setComProtVer( COM_PROT_VER );
        imi.setPort( serverSocket.getLocalPort() );
        JAXB.marshal( imi, Env.PATH_INSTANCE_MONITOR_INFO.toFile() );

    } catch ( final Exception e ) {
        Env.LOGGER.error( "Failed to setup instance monitor!", e );
    }
    this.serverSocket = serverSocket;
}
项目:scelight    文件:RepFiltersEditorDialog.java   
@Override
public void actionPerformed( final ActionEvent event ) {
 final XFileChooser fc = new XFileChooser( SAVE_FOLDER );
 fc.setDialogTitle( "Choose a file to load Replay Filters from" );
 fc.setFileFilter( new FileNameExtensionFilter( "Replay Filter files (*."
         + REP_FILTERS_FILE_EXT + ")", REP_FILTERS_FILE_EXT ) );

 if ( XFileChooser.APPROVE_OPTION != fc.showOpenDialog( RepFiltersEditorDialog.this ) )
  return;

 try {
  repFiltersBean = JAXB
          .unmarshal( fc.getSelectedPath().toFile(), RepFiltersBean.class );
  if ( rfBean != null )
   rfBean.setRepFiltersBean( (RepFiltersBean) repFiltersBean );
 } catch ( final Exception e ) {
  Env.LOGGER.error(
          "Failed to load Replay filters from file: " + fc.getSelectedPath(), e );
  GuiUtils.showErrorMsg( "Failed to load Replay filters from file file:",
          fc.getSelectedPath() );
  return;
 }
 rebuildTable();
}
项目:gradle-fury    文件:Test_Issue144.java   
@Test
public void testExclusions() throws Exception{
    for (int i=0; i < Main.allPoms.length; i++) {
        if (Main.allPoms[i].contains("hello-world-apk")) {
            Model project = JAXB.unmarshal(new File(Main.allPoms[i]), Model.class);
            Assert.assertNotNull(project);
            for (int k=0; k < project.getDependencies().getDependency().size(); k++){
                Dependency dependency = project.getDependencies().getDependency().get(k);
                if (dependency.getGroupId().equals("ch.acra") &&
                        dependency.getArtifactId().equals("acra")){
                    Assert.assertNotNull("no exclusions were present", dependency.getExclusions());
                    Assert.assertEquals("no exclusions were present", 1,dependency.getExclusions().getExclusion().size());
                }

            }
        }
    }
}
项目:lucene4ir    文件:FieldedRetrievalApp.java   
/**
 * Reads the additional parameters required for fielded retrieval.
 * Fields and boosts are read here.
 * @param paramFile
 */
public void readFieldedParamsFromFile(String paramFile){

    try {
        fl = JAXB.unmarshal(new File(paramFile), Fields.class);
    } catch (Exception e){
        System.out.println(" caught a " + e.getClass() +
                "\n with message: " + e.getMessage());
        System.exit(1);
    }

    for (Field field : fl.fields){
        if(field.fieldName.equals(null))
            field.fieldName=Lucene4IRConstants.FIELD_ALL;
        else if(field.fieldBoost <= 0.0f)
            field.fieldBoost=0.0f;
        System.out.println("Field " +field.fieldName + " Boost: " + field.fieldBoost);
    }

    System.out.println("Fielded Results File: " + p.resultFile);
}
项目:lucene4ir    文件:QERetrievalApp.java   
/**
 * Reads the additional parameters required for expansion.
 * noDocs, noTerms and additional alphas.
 * @param paramFile
 */
public void readQEParamsFromFile(String paramFile){
    try {
        qep = JAXB.unmarshal(new File(paramFile), QERetrievalParams.class);
    } catch (Exception e){
        System.out.println(" caught a " + e.getClass() +
                "\n with message: " + e.getMessage());
        System.exit(1);
    }

    if (qep.noDocs<1)
        qep.noDocs=10;
    if (qep.noTerms<1)
        qep.noTerms=10;
    qeBeta=qep.qeBeta;
    feedbackDocs = qep.noDocs;
    feedbackTerms = qep.noTerms;
}
项目:lucene4ir    文件:IndexerApp.java   
public void readIndexParamsFromFile(String indexParamFile){
    try {
        p = JAXB.unmarshal(new File(indexParamFile), IndexParams.class);
    } catch (Exception e){
        e.printStackTrace();
        System.exit(1);
    }

    if(p.recordPositions==null)
        p.recordPositions=false;

    System.out.println("Index type: " + p.indexType);
    System.out.println("Path to index: " + p.indexName);
    System.out.println("List of files to index: " + p.fileList);
    System.out.println("Record positions in index: " + p.recordPositions);

}
项目:jarm    文件:Launcher.java   
public static void launch(Reader hardwareDefinition, String addrinfocmd, int gdbPort, boolean gdbVerbose) throws IOException {
    BasicDebugger debugger = gdbPort == 0 ? new SimpleDebugger(addrinfocmd) : new GDBDebugger(gdbPort, gdbVerbose);

    HardwareDefinition hardware = JAXB.unmarshal(hardwareDefinition, HardwareDefinition.class);
    List<JComponent> components = hardware.prepareSimulation(debugger);

    JFrame frame = new JFrame("ocarmsim");
    frame.setMinimumSize(new Dimension(100, 30));
    frame.setLayout(new GridLayout(2, components.size() / 2));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    for (JComponent c : components) {
        frame.add(c);
    }

    if (debugger.getGUIComponent() != null) {
        frame.add(debugger.getGUIComponent());
    }
    frame.pack();
    frame.setVisible(true);

    debugger.reset();
    while (true) {
        debugger.run();
    }
}
项目:dss    文件:CustomProcessExecutorTest.java   
@Test
public void testCertChain() throws Exception {
    FileInputStream fis = new FileInputStream("src/test/resources/qualifNA.xml");
    DiagnosticData diagnosticData = getJAXBObjectFromString(fis, DiagnosticData.class, "/xsd/DiagnosticData.xsd");
    assertNotNull(diagnosticData);

    CustomProcessExecutor executor = new CustomProcessExecutor();
    executor.setDiagnosticData(diagnosticData);
    executor.setValidationPolicy(loadPolicy());
    executor.setCurrentTime(diagnosticData.getValidationDate());

    Reports reports = executor.execute();

    SimpleReport simpleReport = reports.getSimpleReport();
    assertEquals(1, simpleReport.getJaxbModel().getSignaturesCount());
    XmlSignature xmlSignature = simpleReport.getJaxbModel().getSignature().get(0);
    assertTrue(!xmlSignature.getCertificateChain().getCertificate().isEmpty());
    assertEquals(3, xmlSignature.getCertificateChain().getCertificate().size());
    ByteArrayOutputStream s = new ByteArrayOutputStream();
    JAXB.marshal(simpleReport.getJaxbModel(), s);
}
项目:proarc    文件:JacksonProviderTest.java   
@Test
    public void testDublinCoreRecord() throws Exception {
        ObjectMapper om = new JacksonProvider().getContext(DublinCoreRecord.class);
        om.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
        URL resource = JacksonProviderTest.class.getResource("dc_test.xml");
        assertNotNull(resource);
        OaiDcType dc = JAXB.unmarshal(resource, OaiDcType.class);
        DublinCoreRecord dr = new DublinCoreRecord(dc, System.currentTimeMillis(), "uuid:1");
        String toJson = om.writeValueAsString(dr);
//        System.out.println(toJson);

        DublinCoreRecord ndr = om.readValue(toJson, DublinCoreRecord.class);
        assertEquals(dr.getBatchId(), ndr.getBatchId());
        assertEquals(dr.getPid(), ndr.getPid());
        assertEquals(dr.getTimestamp(), ndr.getTimestamp());
        assertEquals(dr.getDc().getIdentifiers(), ndr.getDc().getIdentifiers());
        assertEquals(dr.getDc().getTitles(), ndr.getDc().getTitles());
        assertEquals(dr.getDc().getCreators(), ndr.getDc().getCreators());

        StringWriter toXml = new StringWriter();
        DcUtils.marshal(new StreamResult(toXml), ndr.getDc(), true);
        toXml.flush();
//        System.out.println("---");
//        System.out.println(toXml);
    }
项目:proarc    文件:ExportUtils.java   
/**
 * Writes an export result in XML.
 */
public static void writeExportResult(File targetFolder, ExportResultLog result) {
    if (result.getEnd() == null) {
        result.setEnd(new Date());
    }
    if (result.getExports().size() == 1) {
        result.setBegin(null);
        result.setEnd(null);
    }
    File resultFile = new File(targetFolder, PROARC_EXPORT_STATUSLOG);
    try {
        JAXB.marshal(result, resultFile);
    } catch (Exception e) {
        LOG.log(Level.SEVERE, targetFolder.toString(), e);
    }
}
项目:proarc    文件:RemoteStorageTest.java   
@Test
public void testXmlRead() throws Exception {
    String dsId = "testId";
    LocalObject local = new LocalStorage().create();
    local.setLabel(test.getMethodName());
    String format = "testns";
    XmlStreamEditor leditor = local.getEditor(FoxmlUtils.inlineProfile(dsId, format, "label"));
    EditorResult editorResult = leditor.createResult();
    TestXml content = new TestXml("test content");
    JAXB.marshal(content, editorResult);
    leditor.write(editorResult, 0, null);

    RemoteStorage fedora = new RemoteStorage(client);
    fedora.ingest(local, "junit");

    RemoteObject remote = fedora.find(local.getPid());
    RemoteXmlStreamEditor editor = new RemoteXmlStreamEditor(remote, dsId);
    Source src = editor.read();
    assertNotNull(src);
    TestXml resultContent = JAXB.unmarshal(src, TestXml.class);
    assertEquals(content, resultContent);
    long lastModified = editor.getLastModified();
    assertTrue(String.valueOf(lastModified), lastModified != 0 && lastModified < System.currentTimeMillis());
    assertEquals(format, editor.getProfile().getDsFormatURI());
}
项目:proarc    文件:RemoteStorageTest.java   
@Test
public void testGetStreamProfile() throws Exception {
    String dsId = "testId";
    LocalObject local = new LocalStorage().create();
    local.setLabel(test.getMethodName());
    String format = "testns";
    XmlStreamEditor leditor = local.getEditor(FoxmlUtils.inlineProfile(dsId, format, "label"));
    EditorResult editorResult = leditor.createResult();
    TestXml content = new TestXml("test content");
    JAXB.marshal(content, editorResult);
    leditor.write(editorResult, 0, null);

    RemoteStorage fedora = new RemoteStorage(client);
    fedora.ingest(local, support.getTestUser());

    RemoteObject remote = fedora.find(local.getPid());
    List<DatastreamProfile> resultProfiles = remote.getStreamProfile(null);
    assertNotNull(resultProfiles);
    assertEquals(2, resultProfiles.size()); // + DC
    assertEquals(dsId, resultProfiles.get(0).getDsID());
}
项目:proarc    文件:TaskParameterTest.java   
@Test
    public void testTaskParameterJsonXml() throws Exception {
        String expectedTimestamp = "2017-01-05T14:51:24.639Z";
        Calendar c = DatatypeConverter.parseDateTime(expectedTimestamp);
        ObjectMapper om = JsonUtils.createJaxbMapper();
        TaskParameterView tp = new TaskParameterView();
        tp.addParamRef("paramRef").addTaskId(BigDecimal.TEN)
//                .addValueString("aha")
//                .addValueNumber(BigDecimal.ONE)
                .addValueDateTime(new Timestamp(c.getTimeInMillis()))
                ;
        tp.setJobId(BigDecimal.ZERO);
        String json = om.writeValueAsString(tp);
        assertTrue(json, json.contains("\"value\":\"" + expectedTimestamp));

        StringWriter stringWriter = new StringWriter();
        JAXB.marshal(tp, stringWriter);
        String xml = stringWriter.toString();
        assertTrue(xml, xml.contains(expectedTimestamp));
    }
项目:java-ui-factory    文件:JListFactory.java   
/**
 * 
 * @since 1.0
 * @param context
 * @param component
 * @param annotate
 */
@UiAnnotationHandler(UiResource.class)
void handleUiResource(final ComponentContext context,
        final JList component, final UiResource annotate) {

    final InputStream in = this.getClass().getClassLoader()
            .getResourceAsStream(annotate.value());

    if (in == null) {
        LOGGER.error("{}|resource {} not found", context.getId(),
                annotate.value());
        return;
    }

    final ListInfo info = JAXB.unmarshal(in, ListInfo.class);

    component.setListData(info.getItems().toArray());
    LOGGER.debug("{}|JList.setListData(count={})", context.getId(), info
            .getItems().size());
}
项目:java-ui-factory    文件:JComboBoxFactory.java   
@UiAnnotationHandler(UiResource.class)
protected void handleUiResource(final ComponentContext context,
        final JComboBox component, final UiResource annotate) {
    final InputStream in = getClass().getClassLoader().getResourceAsStream(
            annotate.value());
    if (in == null) {
        LOGGER.error("UiResource {} not found", annotate.value());
        return;
    }

    final ComboBoxInfo info = JAXB.unmarshal(in, ComboBoxInfo.class);
    if (info == null) {
        LOGGER.error("UiResource {} is invalid", annotate.value());
        return;
    }

    for (final ComboBoxItemInfo itemInfo : info.getItem()) {
        component.addItem(itemInfo.getText());
    }
}
项目:Hotel-Reservation-Tool    文件:AsynchronousGuestEventDispatcher.java   
public void sendGuestEvent(Guest guest) {
    if (null == jmsContext || null == guestEventQueue) {
        LOGGER.log(WARNING, () -> "Sending messages is deactivated!");
        return;
    }

    LOGGER.info(() -> format("Sending info about %s to %s", guest, guestEventQueue));
    try {
        StringWriter w = new StringWriter();
        JAXB.marshal(guest, w);
        TextMessage textMessage = this.jmsContext.createTextMessage(w.toString());
        this.jmsContext.createProducer().send(this.guestEventQueue, textMessage);
    } catch (JMSRuntimeException e) {
        LOGGER.log(SEVERE, e, () -> "Cannot send message due to technical reasons!");
    }
}
项目:AIGS    文件:User.java   
/**
 * Saves the static user list to the file conf/usersXml.xml
 * @since v1.1
 */
public static void writeUsersToXml(){
    UserList tempList = new UserList();
    for(int i = 0; i < users.size(); i++)
    {
        if (users.get(i).isNonPersistentUser() == true)
        {
            continue; // Skip non-persistent users
        }
        tempList.add(users.get(i));
    }
    File userConfigFile = new File("conf/usersXml.xml");
    try
    {
        JAXB.marshal(tempList, userConfigFile);
        //LOG//Logger.getLogger(User.class.getName()).log(Level.INFO, "Write user configuration.");
        LogRouter.log(User.class.getName(), LoggingLevel.system, "Write user configuration.");
    }
    catch(Exception ex)
    {
        //LOG//Logger.getLogger(User.class.getName()).log(Level.INFO, "User configuration file could not be written.");
        LogRouter.log(User.class.getName(), LoggingLevel.system, "User configuration file could not be written.");
    }
}
项目:oai-harvest-manager    文件:XMLOverview.java   
/**
 * <br> Associate the cycle with an XML file <br><br>
 *
 * This constructor initialises the OverviewType object with data from the
 * file.
 *
 * @param overviewFile name of the file
 */
public XMLOverview(File overviewFile) {

    // create factory that creates objects of the generated classes
    factory = new ObjectFactory();

    // ask the factory for an object that can represent XML
    overviewType = factory.createOverviewType();

    // remember the XML file
    file = overviewFile;

    // get the XML from this file
    Object object = JAXB.unmarshal(file, OverviewType.class);

    /* Check if the object is in the OverviewType class. Note: if the
       unmarshalling method returns null, the object is not in the class,
       otherwise it is.
      */
    if (object == null) {
        throw new Exception();
    } else {
        overviewType = (OverviewType) object;
    }
}
项目:Openfire    文件:CrowdManager.java   
/**
 * Get the description of a group from crowd
 * @param groupName
 * @return a Group object
 * @throws RemoteException
 */
public Group getGroup(String groupName) throws RemoteException {
    if (LOG.isDebugEnabled()) LOG.debug("Get group:" + groupName + " from crowd");

    GetMethod get = createGetMethodXmlResponse(crowdServer.resolve("group?groupname=" + urlEncode(groupName)));
    Group group = null;

    try {
        int httpCode = client.executeMethod(get);
        if (httpCode != 200) {
            handleHTTPError(get);
        }

        group = JAXB.unmarshal(get.getResponseBodyAsStream(), Group.class);

    } catch (IOException ioe) {
        handleError(ioe);
    } finally {
        get.releaseConnection();
    }

    return group;
}
项目:wms-q-facade    文件:ConfigResource.java   
@GET
@Produces(MediaType.TEXT_HTML)
public Viewable getMappingsHtml(@Context ServletContext context) {
    Config config = null;
    try {
        // Load config.xml from WEB-INF
        config = JAXB.unmarshal(
                context.getResourceAsStream("/WEB-INF/config.xml"),
                Config.class);
    } catch (Exception e) {
        throw new WebApplicationException(Response.serverError()
                .entity("Error reading configuration file").build());
    }

    return new Viewable("/mappings", config);
}
项目:juddi    文件:UDDIRequestsAsXML.java   
public static String getSubscription(String method) {
    StringWriter sw = new StringWriter();
    if (method.equalsIgnoreCase("deleteSubscription")) {
        JAXB.marshal(new DeleteSubscription(), sw);
    }
    if (method.equalsIgnoreCase("getSubscriptionResults")) {
        JAXB.marshal(new GetSubscriptionResults(), sw);
    }
    if (method.equalsIgnoreCase("getSubscriptions")) {
        JAXB.marshal(new GetSubscriptions(), sw);
    }
    if (method.equalsIgnoreCase("saveSubscription")) {
        JAXB.marshal(new SaveSubscription(), sw);
    }
    return prettyPrintXML(sw.toString());
}
项目:juddi    文件:GetPublisherDetailTest.java   
@Test
public void marshallReplicationMessage() throws Exception{
        ReplicationConfiguration r = new ReplicationConfiguration();
        r.setCommunicationGraph(new CommunicationGraph());
                Operator op = new Operator();
                op.setOperatorNodeID("a node");
                op.setSoapReplicationURL("http://localhost/services/replication");

                op.getContact().add(new Contact());
                op.getContact().get(0).getPersonName().add(new PersonName("Unknown", null));
                op.setOperatorStatus(OperatorStatusType.NORMAL);

                r.getOperator().add(op);
                r.getCommunicationGraph().getNode().add("a node");
                r.getCommunicationGraph().getControlledMessage().add("*");
                r.setSerialNumber(0);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddkkmmZ");
                r.setTimeOfConfigurationUpdate(sdf.format(new Date()));
                r.setRegistryContact(new org.uddi.repl_v3.ReplicationConfiguration.RegistryContact());
                r.getRegistryContact().setContact(new Contact());
                r.getRegistryContact().getContact().getPersonName().add(new PersonName("Unknown", null));
                        JAXB.marshal(r, System.out);
}
项目:juddi    文件:SearchByQos.java   
public void doFindService(String token, Transport transport) throws Exception {

                // Now you create a reference to the UDDI API

                inquiry = transport.getUDDIInquiryService();

                // Making API call that retrieves the authentication token for the 'root' user.
                //String rootAuthToken = clerk.getAuthToken(clerk.getUDDINode().getSecurityUrl());
                String uddi = token;// security.getAuthToken(getAuthTokenRoot).getAuthInfo();

                ServiceList after = getServiceList(uddi);
                if (after.getServiceInfos()==null || after.getServiceInfos().getServiceInfo() == null) {
                        System.out.println("no services returned!");
                        return;
                }
                //PrintUDDI<ServiceList> p = new PrintUDDI<ServiceList>();
                System.out.println(after.getServiceInfos().getServiceInfo().size() + " services returned!");
                JAXB.marshal(after,System.out);


        }
项目:juddi    文件:JuddiAdminService.java   
void registerLocalNodeToRemoteNode(String authtoken, Node cfg, Node publishTo) throws Exception {

                Transport transport = clerkManager.getTransport(publishTo.getName());

                UDDISecurityPortType security2 = transport.getUDDISecurityService();
                System.out.print("username: ");
                String uname = System.console().readLine();
                char passwordArray[] = System.console().readPassword("password: ");
                GetAuthToken getAuthTokenRoot = new GetAuthToken();
                getAuthTokenRoot.setUserID(uname);
                getAuthTokenRoot.setCred(new String(passwordArray));
                authtoken = security2.getAuthToken(getAuthTokenRoot).getAuthInfo();
                System.out.println("Success!");

                JUDDIApiPortType juddiApiService = transport.getJUDDIApiService();
                SaveNode sn = new SaveNode();
                sn.setAuthInfo(authtoken);
                sn.getNode().add(cfg);
                NodeDetail saveNode = juddiApiService.saveNode(sn);
                JAXB.marshal(saveNode, System.out);
                System.out.println("Success.");

        }
项目:opennmszh    文件:LegacyLocalReportsDao.java   
/**
 * {@inheritDoc}
 */
@Override
public void loadConfiguration() throws Exception {
    InputStream stream = null;
    long lastModified;

    File file = null;
    try {
        file = m_configResource.getFile();
        Assert.notNull(file, "config file must be sot to a non-null value");
    } catch (IOException e) {
        logger.error("Resource '{}' does not seem to have an underlying File object.", m_configResource);
    }

    if (file != null) {
        lastModified = file.lastModified();
        stream = new FileInputStream(file);
    } else {
        lastModified = System.currentTimeMillis();
        stream = m_configResource.getInputStream();
    }
    setLegacyLocalReportsDefinition(JAXB.unmarshal(file, LegacyLocalReportsDefinition.class));
    Assert.notNull(m_legacyLocalReportsDefinition, "unmarshall config file returned a null value.");
    logger.debug("Unmarshalling config file '{}'", file.getAbsolutePath());
    logger.debug("Local report definitions assigned: '{}'", m_legacyLocalReportsDefinition.toString());
}
项目:juddi    文件:JuddiAdminService.java   
void dumpFailedReplicationRecords(String authtoken) throws Exception {
        GetFailedReplicationChangeRecordsMessageRequest req = new GetFailedReplicationChangeRecordsMessageRequest();
        req.setAuthInfo(authtoken);
        req.setMaxRecords(20);
        req.setOffset(0);
        GetFailedReplicationChangeRecordsMessageResponse failedReplicationChangeRecords = juddi.getFailedReplicationChangeRecords(req);
        while (failedReplicationChangeRecords != null
                && failedReplicationChangeRecords.getChangeRecords() != null
                && !failedReplicationChangeRecords.getChangeRecords().getChangeRecord().isEmpty()) {
                for (int i = 0; i < failedReplicationChangeRecords.getChangeRecords().getChangeRecord().size(); i++) {
                        JAXB.marshal(failedReplicationChangeRecords.getChangeRecords().getChangeRecord().get(i), System.out);
                }
                req.setOffset(req.getOffset() + failedReplicationChangeRecords.getChangeRecords().getChangeRecord().size());
                failedReplicationChangeRecords = juddi.getFailedReplicationChangeRecords(req);
        }
}
项目:juddi    文件:UddiReplication.java   
protected void getChangeRecords(Long record, String sourcenode) {
        try {
                HighWaterMarkVectorType highWaterMarkVectorType = new HighWaterMarkVectorType();

                highWaterMarkVectorType.getHighWaterMark().add(new ChangeRecordIDType(doPing(), record));
                GetChangeRecords req = new GetChangeRecords();
                req.setRequestingNode(sourcenode);
                req.setChangesAlreadySeen(highWaterMarkVectorType);
                req.setResponseLimitCount(BigInteger.valueOf(100));
                ChangeRecords res = uddiReplicationPort.getChangeRecords(req);
                List<ChangeRecord> changeRecords = res.getChangeRecord();
                System.out.println("Success...." + changeRecords.size() + " records returned");
                System.out.println("Node, USN, type");
                for (int i = 0; i < changeRecords.size(); i++) {
                        System.out.println(
                                changeRecords.get(i).getChangeID().getNodeID() + ", "
                                + changeRecords.get(i).getChangeID().getOriginatingUSN() + ": "
                                + getChangeType(changeRecords.get(i)));
                        JAXB.marshal(changeRecords.get(i), System.out);
                }
        } catch (Exception ex) {
                Logger.getLogger(UddiReplication.class.getName()).log(Level.SEVERE, null, ex);
        }
}
项目:juddi    文件:SimpleBrowse.java   
public void printServiceList(String authtoken, String searchString, boolean rawXml) throws Exception {

                int offset = 0;
                int maxrecords = 100;
                ServiceList findBusiness = getServiceList(authtoken, searchString, offset, maxrecords);
                while (findBusiness != null && findBusiness.getServiceInfos() != null
                        && !findBusiness.getServiceInfos().getServiceInfo().isEmpty()) {
                        if (rawXml) {
                                JAXB.marshal(findBusiness, System.out);
                        } else {
                                printServiceInfo(findBusiness.getServiceInfos());
                                //PrintBusinessDetails(findBusiness.getBusinessInfos(), authtoken);
                                //PrintServiceDetailsByBusiness(findBusiness.getBusinessInfos(), authtoken);
                        }
                        offset = offset + maxrecords;

                        findBusiness = getServiceList(authtoken, searchString, offset, maxrecords);
                }
        }
项目:juddi    文件:SimpleBrowse.java   
void printTModelList(String authtoken, String searchString, boolean rawXml) throws Exception {
        int offset = 0;
        int maxrecords = 100;
        TModelList findBusiness = getTmodelList(authtoken, searchString, offset, maxrecords);
        while (findBusiness != null && findBusiness.getTModelInfos() != null
                && !findBusiness.getTModelInfos().getTModelInfo().isEmpty()) {
                if (rawXml) {
                        JAXB.marshal(findBusiness, System.out);
                } else {
                        printTModelInfo(findBusiness.getTModelInfos());
                        //PrintBusinessDetails(findBusiness.getBusinessInfos(), authtoken);
                        //PrintServiceDetailsByBusiness(findBusiness.getBusinessInfos(), authtoken);
                }
                offset = offset + maxrecords;

                findBusiness = getTmodelList(authtoken, searchString, offset, maxrecords);
        }
}
项目:juddi    文件:UDDIPublicationImpl.java   
public static ChangeRecord getChangeRecord(BindingTemplate modelBindingTemplate, org.uddi.api_v3.BindingTemplate api, String node) throws DispositionReportFaultMessage {
        ChangeRecord cr = new ChangeRecord();
        cr.setEntityKey(modelBindingTemplate.getEntityKey());
        cr.setNodeID(node);

        cr.setRecordType(ChangeRecord.RecordType.ChangeRecordNewData);
        org.uddi.repl_v3.ChangeRecord crapi = new org.uddi.repl_v3.ChangeRecord();
        crapi.setChangeID(new ChangeRecordIDType(node, -1L));
        crapi.setChangeRecordNewData(new ChangeRecordNewData());
        crapi.getChangeRecordNewData().setBindingTemplate(api);
        crapi.getChangeRecordNewData().setOperationalInfo(new OperationalInfo());
        MappingModelToApi.mapOperationalInfo(modelBindingTemplate, crapi.getChangeRecordNewData().getOperationalInfo());
        StringWriter sw = new StringWriter();
        JAXB.marshal(crapi, sw);
        try {
                cr.setContents(sw.toString().getBytes("UTF8"));
        } catch (UnsupportedEncodingException ex) {
                logger.error(ex);
        }
        return cr;
}