javax.xml.bind.JAXB Java Examples

The following examples show how to use javax.xml.bind.JAXB. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RemoteStorageTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@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());
}
 
Example #2
Source File: Updater.java    From scelight with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the <code>SNAP</code> env var is present, and if so,
 * tries to load modules bean from one of the following locations:
 * <ol>
 * 	<li><code>./release/deployment-dev/modules.xml</code>
 * 	<li><code>usr/share/scelight/modules.xml</code>
 * </ol>
 */
private void checkLinuxSnap() {
	String snapRoot = System.getenv( "SNAP" );
	if ( snapRoot == null )
		return;
	
	File modulesFile = Paths.get( "./release/deployment-dev/modules.xml" ).toFile();
	if ( !modulesFile.exists() ) {
		modulesFile = Paths.get( snapRoot, "usr/share/scelight/modules.xml" ).toFile();
	}
	modules = JAXB.unmarshal( modulesFile, ModulesBean.class );
	modules.setOrigin( ModulesBeanOrigin.UPDATER_FAKE );
	launcher.setModules( modules );
	
	publishModCounts();
	
	throw new FinishException();
}
 
Example #3
Source File: JaxContextCentralizer.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public String toXml(Class<?> clazz, Object obj) throws GFDDPPException {
   StringWriter sw = new StringWriter();
   Marshaller marshaller = this.getMarshaller(clazz);

   try {
      marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);
      if (clazz.getAnnotation(XmlRootElement.class) != null) {
         marshaller.marshal(obj, (Writer)sw);
      } else {
         JAXB.marshal(obj, (Writer)sw);
      }
   } catch (JAXBException var7) {
      LOG.error("", var7);
      String message = this.processJAXBException(var7);
      throw new GFDDPPException(StatusCode.COMMON_ERROR_MARSHAL, new String[]{message, clazz.getName()});
   }

   return sw.toString();
}
 
Example #4
Source File: TaskParameterTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@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));
    }
 
Example #5
Source File: CreateAuthorXml.java    From scelight with Apache License 2.0 6 votes vote down vote up
/**
 * @param args used to take arguments from the running environment - not used here
 * @throws Exception if any error occurs
 */
public static void main( final String[] args ) throws Exception {
	final PersonBean author = new PersonBean();
	
	final PersonNameBean personName = new PersonNameBean();
	personName.setFirst( "AndrĂ¡s" );
	personName.setLast( "Belicza" );
	author.setPersonName( personName );
	
	final ContactBean contact = new ContactBean();
	contact.setEmail( "[email protected]" );
	contact.setLocation( "Budapest, Hungary" );
	author.setContact( contact );
	author.setDescription( "Author of BWHF, Sc2gears and Scelight" );
	
	JAXB.marshal( author, new File( LR.get( "bean/author.xml" ).toURI() ) );
}
 
Example #6
Source File: RepFiltersEditorDialog.java    From scelight with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #7
Source File: Test_Issue144.java    From gradle-fury with Apache License 2.0 6 votes vote down vote up
@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());
                }

            }
        }
    }
}
 
Example #8
Source File: RetrievabilityCalculator.java    From lucene4ir with Apache License 2.0 6 votes vote down vote up
private void readParamsFromFile() {
    System.out.println("Reading Param File");
    try {
        p = JAXB.unmarshal(new File(sourceParameterFile), RetrievabilityCalculatorParams.class );
        if (p.indexName.toString().isEmpty())
            displayMsg ("IndexName Parameter is Missing");
        System.out.println("Index: " + p.indexName);
        if (p.retFile.toString().isEmpty())
            displayMsg ("Query Output Path Parameter is Missing");
        if (p.resFile.toString().isEmpty())
            displayMsg ("Result File Parameter is Missing");
        if (p.queryFile.toString().isEmpty())
            displayMsg ("Query File Parameter is Missing");
        if (p.b < 1)
            p.b = 0;
        if (p.c < 1)
            p.c = 0;

    } catch (Exception e) {
        System.out.println(" caught a " + e.getClass() +
                "\n with message: " + e.getMessage());
        System.exit(1);
    }
}
 
Example #9
Source File: QERetrievalApp.java    From lucene4ir with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: PackageReader.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
private void readImpl(File metsFile) throws DigitalObjectException {
    this.metsFile = metsFile;
    this.metsUri = metsFile.toURI();
    this.mets = JAXB.unmarshal(metsFile, Mets.class);
    this.isParentObject = true;
    this.physicalPath.clear();
    pkgModelId = mets.getTYPE();
    if (pkgModelId == null) {
        throw new IllegalStateException("Unknown mets@TYPE:" + pkgModelId);
    }
    StructMapType otherMap = getStructMap(mets, PackageBuilder.STRUCTMAP_OTHERS_TYPE);
    processDevices(otherMap);

    StructMapType physicalMap = getStructMap(mets, PackageBuilder.STRUCTMAP_PHYSICAL_TYPE);
    DivType div = physicalMap.getDiv();
    processObject(1, div);
}
 
Example #11
Source File: ExportUtils.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #12
Source File: IndexerApp.java    From lucene4ir with Apache License 2.0 6 votes vote down vote up
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);

}
 
Example #13
Source File: CustomProcessExecutorTest.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Test
public void testCertChain() throws Exception {
	XmlDiagnosticData diagnosticData = DiagnosticDataFacade.newFacade().unmarshall(new File("src/test/resources/qualifNA.xml"));
	assertNotNull(diagnosticData);

	DefaultSignatureProcessExecutor executor = new DefaultSignatureProcessExecutor();
	executor.setDiagnosticData(diagnosticData);
	executor.setValidationPolicy(loadDefaultPolicy());
	executor.setCurrentTime(diagnosticData.getValidationDate());

	Reports reports = executor.execute();

	SimpleReport simpleReport = reports.getSimpleReport();
	assertEquals(1, simpleReport.getJaxbModel().getSignaturesCount());
	XmlCertificateChain certificateChain = simpleReport.getCertificateChain(simpleReport.getFirstSignatureId());
	assertNotNull(certificateChain);
	assertTrue(Utils.isCollectionNotEmpty(certificateChain.getCertificate()));
	assertEquals(3, certificateChain.getCertificate().size());
	ByteArrayOutputStream s = new ByteArrayOutputStream();
	JAXB.marshal(simpleReport.getJaxbModel(), s);

	validateBestSigningTimes(reports);
	checkReports(reports);
}
 
Example #14
Source File: JacksonProviderTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
 
Example #15
Source File: ResolverUtilsTest.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGetOriginator() {
    final String xml = "<mods xmlns='http://www.loc.gov/mods/v3'>"
            + "<name type='corporate'><namePart>Corporate</namePart></name>"
            + "<name type='personal' usage='primary'>"
                + "<namePart type='family'>PrimaryFamily</namePart>"
                + "<namePart type='given'>PrimaryGiven</namePart>"
                + "<namePart type='date'>Primary2002</namePart>"
                + "<namePart type='termsOfAddress'>PrimaryTermsOfAddress</namePart>"
            + "</name>"
            + "<name type='personal'>"
                + "<namePart>FullName</namePart>"
                + "<namePart type='given'>Given</namePart>"
                + "<namePart type='date'>2001</namePart>"
                + "<namePart type='termsOfAddress'>TermsOfAddress</namePart>"
                + "<namePart type='family'>Family</namePart>"
            + "</name>"
            + "<name type='personal'>"
                + "<namePart type='family'>Family2</namePart>"
                + "<namePart type='given'>Given2</namePart>"
                + "<namePart type='date'>2002</namePart>"
                + "<namePart type='termsOfAddress'>TermsOfAddress2</namePart>"
            + "</name>"
            + "</mods>";
    ModsDefinition mods = JAXB.unmarshal(new StringReader(xml), ModsDefinition.class);
    String originator = ResolverUtils.getOriginator("personal", false, mods);
    assertEquals("FullName, Family, Given; Family2, Given2", originator);

    originator = ResolverUtils.getOriginator("personal", true, mods);
    assertEquals("PrimaryFamily, PrimaryGiven", originator);

    originator = ResolverUtils.getOriginator("corporate", null, mods);
    assertEquals("Corporate", originator);
}
 
Example #16
Source File: FXManifest.java    From fxlauncher with Apache License 2.0 5 votes vote down vote up
static FXManifest load(URI uri) throws IOException {
	if (Objects.equals(uri.getScheme(), "file")) {
		return JAXB.unmarshal(new File(uri.getPath()), FXManifest.class);
	}
	URLConnection connection = uri.toURL().openConnection();
	if (uri.getUserInfo() != null) {
		byte[] payload = uri.getUserInfo().getBytes(StandardCharsets.UTF_8);
		String encoded = Base64.getEncoder().encodeToString(payload);
		connection.setRequestProperty("Authorization", String.format("Basic %s", encoded));
	}
	try (InputStream input = connection.getInputStream()) {
		return JAXB.unmarshal(input, FXManifest.class);
	}
}
 
Example #17
Source File: TokenAnalyzerMaker.java    From lucene4ir with Apache License 2.0 5 votes vote down vote up
public Analyzer createAnalyzer( String tokenFilterFile) {
    Analyzer analyzer = null;
    try {
        lucene4ir.utils.TokenFilters tokenFilters = JAXB.unmarshal(new File(tokenFilterFile), lucene4ir.utils.TokenFilters.class);
        CustomAnalyzer.Builder builder;
        if (tokenFilters.getResourceDir() != null) {
            builder = CustomAnalyzer.builder(Paths.get(tokenFilters.getResourceDir()));
        } else {
            builder = CustomAnalyzer.builder();
        }

        builder.withTokenizer(tokenFilters.getTokenizer());
        for (lucene4ir.utils.TokenFilter filter : tokenFilters.getTokenFilters()) {
            System.out.println("Token filter: " + filter.getName());
            List<lucene4ir.utils.Param> params = filter.getParams();
            if (params.size() > 0) {
                Map<String, String> paramMap = new HashMap<>();
                for (lucene4ir.utils.Param param : params) {
                    paramMap.put(param.getKey(), param.getValue());
                }
                builder.addTokenFilter(filter.getName(), paramMap);
            } else {
                builder.addTokenFilter(filter.getName());
            }
        }
        analyzer = builder.build();


    }
    catch (IOException ioe){
        System.out.println(" caught a " + ioe.getClass() +
                "\n with message: " + ioe.getMessage());
    }

    return analyzer;

}
 
Example #18
Source File: AlephXServer.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
private MetadataItem addBarcodeMetadata(MetadataItem item, int sysno) throws IOException, TransformerException {
    //add before ending tag of </mods>
    //identifier type="barcode">XXXX</identifier>
    String mods = item.getMods();
    int pos = mods.indexOf("\n</mods>");

    if (pos == -1) {
        LOG.log(Level.WARNING, "Barcode could not be added. Missing ending tag \"</mods>\"");
        return item;
    }

    ItemDataResponse details = null;

    try {
        details = JAXB.unmarshal(fetchItemData(sysno), ItemDataResponse.class);
    } catch (UnknownHostException ex) {
        LOG.log(Level.WARNING, "Unknown host: " + ex.getMessage());
    }

    if (details == null) {
        LOG.log(Level.WARNING, "Could not read item data response. Details null.");
        return item;
    }

    for (ItemDataResponse.Item idr : details.getItems()) {
        String barcode = idr.getBarcode();

        if (barcode == null || barcode.length() != 10 || !barcode.matches("[0-9]+")) {
            LOG.log(Level.WARNING, "Could not load barcode, invalid format: " + barcode);
            continue;
        }

        mods = mods.substring(0,pos) + "\n<identifier type=\"barcode\">" + barcode + "</identifier>" + mods.substring(pos);
    }

    return new MetadataItem(item.getId(), item.getRdczId(), mods, item.getPreview(), item.getTitle());
}
 
Example #19
Source File: JaxbCallbackTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void execute() {
    final String sample = "<someObject><someValue>Test Value</someValue></someObject>";

    final SomeObject result = JaxbCallback.execute(() -> JAXB.unmarshal(new StringReader(sample), SomeObject.class));

    assertThat(result.getSomeValue()).isEqualTo("Test Value");
}
 
Example #20
Source File: SoftwareListChdSet.java    From ia-rcade with Apache License 2.0 5 votes vote down vote up
/**
 * Get the best SoftwareListChdSet for the given Mame version.
 *
 * "Best" means equal or greatest inferior to given Mame version.
 */
public static SoftwareListChdSet findBest(MameVersion version) {

  MameVersion bestVersion;

  if (versions.contains(version)) {
    bestVersion = version;
  } else {
    bestVersion = versions.floor(version);
    IaRcade.warn("No archive.org softlist CHD set matches your Mame version");
    IaRcade.warn("Some files might not be available.");
  }

  // Unmarshal SoftwareListChdSet from XML data stored in classpath

  StringBuilder builder = new StringBuilder("softwarelist-chd-set/");
  builder.append(bestVersion);
  builder.append(".xml");

  InputStream stream = SoftwareListChdSet.class.getClassLoader()
      .getResourceAsStream(builder.toString());

  SoftwareListChdSet chdSet =
      JAXB.unmarshal(stream, SoftwareListChdSet.class);

  return chdSet;

}
 
Example #21
Source File: OutputDocids.java    From lucene4ir with Apache License 2.0 5 votes vote down vote up
public void readExampleStatsParamsFromFile(String indexParamFile) {
    try {
        OutputDocidsParams p = JAXB.unmarshal(new File(indexParamFile), OutputDocidsParams.class);
        indexName = p.indexName;
        outputFile = p.outputFile;
    } catch (Exception e) {
        System.out.println(" caught a " + e.getClass() +
                "\n with message: " + e.getMessage());
        System.exit(1);
    }
}
 
Example #22
Source File: PropertiesDescription.java    From biomedicus with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a description from a classpath resource.
 *
 * @param classpath the name of the classpath resource
 * @return initialized property groups from the XML file.
 */
public static PropertiesDescription loadFromFile(String classpath) {
  LOGGER.debug("Loading properties description from: {}", classpath);
  InputStream inputStream = Thread.currentThread().getContextClassLoader()
      .getResourceAsStream(classpath);
  return JAXB.unmarshal(inputStream, PropertiesDescription.class);
}
 
Example #23
Source File: AlephXServer.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
FindResponse createFindResponse(InputStream is) {
    try {
        return JAXB.unmarshal(is, AlephXServer.FindResponse.class);
    } finally {
        try {
            is.close();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
}
 
Example #24
Source File: Updater.java    From scelight with Apache License 2.0 5 votes vote down vote up
/**
 * Checks for Eclipse mode and if so, sets up the Launcher for Eclipse mode.
 * 
 * @throws FinishException if the updater should finish and return
 */
private void checkEclipseMode() {
	if ( !LEnv.ECLIPSE_MODE )
		return;
	
	LEnv.LOGGER.debug( "Eclipse mode: skipping update check." );
	
	modules = JAXB.unmarshal( Paths.get( "../release/deployment-dev/modules.xml" ).toFile(), ModulesBean.class );
	modules.setOrigin( ModulesBeanOrigin.ECLIPSE_MODULES_XML );
	launcher.setModules( modules );
	
	publishModCounts();
	
	throw new FinishException();
}
 
Example #25
Source File: Test_Issue144.java    From gradle-fury with Apache License 2.0 5 votes vote down vote up
@Test
public void validatePom() throws Exception {
    for (int i=0; i < Main.allPoms.length; i++) {
        Model project = JAXB.unmarshal(new File(Main.allPoms[i]), Model.class);
        Assert.assertNotNull(project);
    }
}
 
Example #26
Source File: ImportBatchManager.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets batch import folder status.
 * @param batch
 * @return status or {@code null} in case of empty file (backward compatibility)
 * @throws FileNotFoundException missing batch import folder
 */
public ImportFolderStatus getFolderStatus(Batch batch) throws FileNotFoundException {
    File importFolder = resolveBatchFile(batch.getFolder());
    ImportFileScanner.validateImportFolder(importFolder);
    File f = new File(importFolder, ImportFileScanner.IMPORT_STATE_FILENAME);
    ImportFolderStatus ifs = null;
    if (f.exists() && f.length() > 0) {
        ifs = JAXB.unmarshal(f, ImportFolderStatus.class);
    }
    return ifs;
}
 
Example #27
Source File: RepFiltersEditorDialog.java    From scelight with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed( final ActionEvent event ) {
 final XFileChooser fc = new XFileChooser( SAVE_FOLDER );
 fc.setDialogTitle( "Choose a file to save Replay Filters" );
 fc.setFileFilter( new FileNameExtensionFilter( "Replay Filter files (*."
         + REP_FILTERS_FILE_EXT + ')', REP_FILTERS_FILE_EXT ) );
 
 // Suggested file name
 fc.setSelectedFile( Utils.uniqueFile(
         SAVE_FOLDER.resolve( "replay-filters." + REP_FILTERS_FILE_EXT ) ).toFile() );
 
 if ( XFileChooser.APPROVE_OPTION != fc.showSaveDialog( RepFiltersEditorDialog.this ) )
  return;
 Path path = fc.getSelectedPath();
 // Ensure proper extension
 if ( !path.getFileName().toString().toLowerCase().endsWith( '.' + REP_FILTERS_FILE_EXT ) )
  path = path.resolveSibling( path.getFileName().toString() + '.'
          + REP_FILTERS_FILE_EXT );
 if ( Files.exists( path ) )
  if ( !GuiUtils.confirm( "The selected file already exists?", "Overwrite it?" ) )
   return;
 
 try {
  JAXB.marshal( repFiltersBean, path.toFile() );
 } catch ( final Exception e ) {
  Env.LOGGER.error( "Failed to write to file: " + path, e );
  GuiUtils.showErrorMsg( "Failed to write to file:", path );
 }
}
 
Example #28
Source File: LocalStorageTest.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testDatastreamEditorWriteXml_ManagedAsAttached() throws Exception {
    LocalStorage storage = new LocalStorage();
    LocalObject lobject = storage.create();
    String dsID = "dsID";
    MediaType mime = MediaType.TEXT_XML_TYPE;
    String label = "label";
    String formatUri = "formatUri";
    XmlStreamEditor editor = lobject.getEditor(FoxmlUtils.managedProfile(dsID, formatUri, label));
    assertNotNull(editor);
    assertNotNull(editor.getProfile());
    assertEquals(mime.toString(), editor.getProfile().getDsMIME());
    assertEquals(formatUri, editor.getProfile().getDsFormatURI());
    File attachment = tmp.newFile();
    editor.write(attachment.toURI(), 0, null);
    XmlData xdata = new XmlData("data");
    EditorResult xmlResult = editor.createResult();
    JAXB.marshal(xdata, xmlResult);
    editor.write(xmlResult, editor.getLastModified(), null);
    lobject.flush();

    // is managed
    DigitalObject dobj = lobject.getDigitalObject();
    DatastreamType ds = FoxmlUtils.findDatastream(dobj, dsID);
    assertNotNull(ds);
    assertEquals(ControlGroup.MANAGED.toExternal(), ds.getCONTROLGROUP());

    // is attached
    DatastreamVersionType dsv = FoxmlUtils.findDataStreamVersion(dobj, dsID);
    assertNotNull(dsv);
    assertEquals(mime.toString(), dsv.getMIMETYPE());
    assertEquals(label, dsv.getLABEL());
    assertEquals(formatUri, dsv.getFORMATURI());
    assertNull(dsv.getBinaryContent());
    assertNull(dsv.getXmlContent());
    assertNotNull(dsv.getContentLocation());

    XmlData result = JAXB.unmarshal(attachment, XmlData.class);
    assertEquals(xdata, result);
}
 
Example #29
Source File: ExampleStatsApp.java    From lucene4ir with Apache License 2.0 5 votes vote down vote up
public void readExampleStatsParamsFromFile(String indexParamFile) {
    try {
        IndexParams p = JAXB.unmarshal(new File(indexParamFile), IndexParams.class);
        indexName = p.indexName;

    } catch (Exception e) {
        System.out.println(" caught a " + e.getClass() +
                "\n with message: " + e.getMessage());
        System.exit(1);
    }
}
 
Example #30
Source File: ModEnv.java    From scelight with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized SettingsBean initSettingsBean( final String name, final List< ISetting< ? > > validSettingList ) {
	if ( nameSettingsBeanMap.containsKey( name ) )
		throw new IllegalArgumentException( "A settings bean with the name has already been initialized: " + name );
	
	// A call to getCacheFolder() will also create it if it does not exist yet.
	final Path path = getCacheFolder().resolve( name + ".xml" );
	
	SettingsBean settings = null;
	try {
		settings = JAXB.unmarshal( path.toFile(), SettingsBean.class );
	} catch ( final Exception e ) {
		Env.LOGGER.warning( "Could not read " + manifestBean.getName() + " external module settings, the default settings will be used: " + path );
		if ( Files.exists( path ) ) // Only log exception if file exists but failed to read it.
			Env.LOGGER.debug( "Reason:", e );
		else
			Env.LOGGER.debug( "Reason: File does not exist: " + path );
		
		settings = new SettingsBean();
	}
	settings.configureSave( manifestBean.getName(), manifestBean.getVersion(), path );
	settings.setValidSettingList( validSettingList );
	
	if ( settings.getSaveTime() == null )
		settings.save();
	
	nameSettingsBeanMap.put( name, settings );
	settingsBeanList.add( settings );
	
	return settings;
}