Java Code Examples for javax.xml.bind.JAXBException

The following are top voted examples for showing how to use javax.xml.bind.JAXBException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: openjdk-jdk10   File: UnmarshallerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public <T> JAXBElement<T> unmarshal( Source source, Class<T> expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example 2
Project: openjdk-jdk10   File: JAXBContextWithAbstractFactory.java   Source Code and License 6 votes vote down vote up
public static void test() throws JAXBException {
    System.clearProperty(JAXBContext.JAXB_CONTEXT_FACTORY);
    System.out.println(JAXBContext.JAXB_CONTEXT_FACTORY + " = "
            + System.getProperty(JAXBContext.JAXB_CONTEXT_FACTORY, ""));
    System.out.println("Calling "
            + "JAXBContext.newInstance(JAXBContextWithAbstractFactory.class)");
    tmp = JAXBContext.newInstance(JAXBContextWithAbstractFactory.class);
    System.setProperty(JAXBContext.JAXB_CONTEXT_FACTORY,
            "JAXBContextWithAbstractFactory$Factory");
    System.out.println(JAXBContext.JAXB_CONTEXT_FACTORY + " = "
            + System.getProperty(JAXBContext.JAXB_CONTEXT_FACTORY));
    System.out.println("Calling "
            + "JAXBContext.newInstance(JAXBContextWithAbstractFactory.class)");
    JAXBContext ctxt = JAXBContext.newInstance(JAXBContextWithAbstractFactory.class);
    System.out.println("Successfully loaded JAXBcontext: " +
            System.identityHashCode(ctxt) + "@" + ctxt.getClass().getName());
    if (ctxt != tmp) {
        throw new RuntimeException("Wrong JAXBContext instance"
            + "\n\texpected: "
            + System.identityHashCode(tmp) + "@" + tmp.getClass().getName()
            + "\n\tactual:   "
            + System.identityHashCode(ctxt) + "@" + ctxt.getClass().getName());
    }
}
 
Example 3
Project: ditb   File: TestScannersWithLabels.java   Source Code and License 6 votes vote down vote up
@Test
public void testSimpleScannerXMLWithLabelsThatReceivesNoData() throws IOException, JAXBException {
  final int BATCH_SIZE = 5;
  // new scanner
  ScannerModel model = new ScannerModel();
  model.setBatch(BATCH_SIZE);
  model.addColumn(Bytes.toBytes(COLUMN_1));
  model.addLabel(PUBLIC);
  StringWriter writer = new StringWriter();
  marshaller.marshal(model, writer);
  byte[] body = Bytes.toBytes(writer.toString());
  // recall previous put operation with read-only off
  conf.set("hbase.rest.readonly", "false");
  Response response = client.put("/" + TABLE + "/scanner", Constants.MIMETYPE_XML, body);
  assertEquals(response.getCode(), 201);
  String scannerURI = response.getLocation();
  assertNotNull(scannerURI);

  // get a cell set
  response = client.get(scannerURI, Constants.MIMETYPE_XML);
  // Respond with 204 as there are no cells to be retrieved
  assertEquals(response.getCode(), 204);
  assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
}
 
Example 4
Project: OpenJSharp   File: JAXBSource.java   Source Code and License 6 votes vote down vote up
public void parse() throws SAXException {
    // parses a content object by using the given marshaller
    // SAX events will be sent to the repeater, and the repeater
    // will further forward it to an appropriate component.
    try {
        marshaller.marshal( contentObject, (XMLFilterImpl)repeater );
    } catch( JAXBException e ) {
        // wrap it to a SAXException
        SAXParseException se =
            new SAXParseException( e.getMessage(),
                null, null, -1, -1, e );

        // if the consumer sets an error handler, it is our responsibility
        // to notify it.
        if(errorHandler!=null)
            errorHandler.fatalError(se);

        // this is a fatal error. Even if the error handler
        // returns, we will abort anyway.
        throw se;
    }
}
 
Example 5
Project: elastic-db-tools-for-java   File: SchemaInfo.java   Source Code and License 6 votes vote down vote up
/**
 * Initializes a new instance of the <see cref="SchemaInfo"/> class.
 */
public SchemaInfo(ResultSet reader,
        int offset) {
    try (StringReader sr = new StringReader(reader.getSQLXML(offset).getString())) {
        JAXBContext jc = JAXBContext.newInstance(SchemaInfo.class);

        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader xsr = xif.createXMLStreamReader(sr);

        SchemaInfo schemaInfo = (SchemaInfo) jc.createUnmarshaller().unmarshal(xsr);

        this.referenceTables = new ReferenceTableSet(schemaInfo.getReferenceTables());
        this.shardedTables = new ShardedTableSet(schemaInfo.getShardedTables());
    }
    catch (SQLException | JAXBException | XMLStreamException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 
Example 6
Project: ExtremeGuiMakeover   File: MovieApp.java   Source Code and License 6 votes vote down vote up
private void showMasterDetailInWindow(final Stage stage, final Database database, final MasterDetailViewFeatures features) throws JAXBException, IOException {
    final Parent viewRoot = ViewFactory.createMasterDetailView(database, features);

    final Rectangle clip = new Rectangle();
    clip.setArcHeight(18);
    clip.setArcWidth(18);
    clip.widthProperty().bind(stage.widthProperty());
    clip.heightProperty().bind(stage.heightProperty());

    //TODO: Only clipping or PerspectiveCamera is working... :(
    features.customWindowClipProperty().addListener((obs, oldVal, newVal) -> {
        if (newVal) {
            viewRoot.setClip(clip);
        } else {
            viewRoot.setClip(null);
        }
    });

    final Scene scene = new Scene(viewRoot);

    features.useCssProperty().addListener((obs, oldVal, newVal) -> {
        updateStylesheets(scene, newVal);
    });

    updateStylesheets(scene, features.isUseCss());

    scene.setFill(Color.TRANSPARENT);
    scene.setCamera(new PerspectiveCamera());

    if (features.isCustomWindowUI()) {
        stage.initStyle(StageStyle.TRANSPARENT);
    }

    stage.setTitle("Movie Database");
    stage.setScene(scene);
    stage.setWidth(1100);
    stage.setHeight(720);
    stage.centerOnScreen();
    stage.show();

    final FeaturesDialog featuresDialog = new FeaturesDialog(stage);
    featuresDialog.addFeature(new Feature("Layout & Style", "demo2-css", features.useCssProperty()));
    featuresDialog.addFeature(new Feature("Image Background", "demo2-image-background",features.movieBackgroundProperty()));
    featuresDialog.addFeature(new Feature("List Animation", "demo2-list-animation",features.listAnimationProperty()));
    featuresDialog.addFeature(new Feature("List Shadow", "demo2-list-shadow",features.listShadowProperty()));
    // featuresDialog.addFeature(new Feature("List Cache", "demo2-list-cache",features.listCacheProperty()));
    featuresDialog.addFeature(new Feature("Poster Transform", "demo2-poster-transform",features.posterTransformProperty()));
    featuresDialog.addFeature(new Feature("Custom Window UI", "demo2-custom-window-ui",features.customWindowUIProperty()));
    featuresDialog.addFeature(new Feature("Custom Window Clip", "demo2-custom-window-clip", features.customWindowClipProperty()));
    featuresDialog.show();
}
 
Example 7
Project: OpenJSharp   File: JAXBContextFactory.java   Source Code and License 6 votes vote down vote up
/**
 * The JAXB API will invoke this method via reflection
 */
public static JAXBContext createContext( String contextPath,
                                         ClassLoader classLoader, Map properties ) throws JAXBException {

    List<Class> classes = new ArrayList<Class>();
    StringTokenizer tokens = new StringTokenizer(contextPath,":");

    // each package should be pointing to a JAXB RI generated
    // content interface package.
    //
    // translate them into a list of private ObjectFactories.
    try {
        while(tokens.hasMoreTokens()) {
            String pkg = tokens.nextToken();
            classes.add(classLoader.loadClass(pkg+IMPL_DOT_OBJECT_FACTORY));
        }
    } catch (ClassNotFoundException e) {
        throw new JAXBException(e);
    }

    // delegate to the JAXB provider in the system
    return JAXBContext.newInstance(classes.toArray(new Class[classes.size()]),properties);
}
 
Example 8
Project: personium-core   File: ServiceSourceAccessControlTest.java   Source Code and License 6 votes vote down vote up
/**
 * テスト用のコレクションを作成し、テストに必要なAccountやACLの設定を作成する.
 * @throws JAXBException リクエストに設定したACLの定義エラー
 */
private void createTestCollection() throws JAXBException {

    // Collection作成
    CellUtils.create(CELL_NAME, MASTER_TOKEN, HttpStatus.SC_CREATED);
    BoxUtils.create(CELL_NAME, BOX_NAME, MASTER_TOKEN, HttpStatus.SC_CREATED);
    DavResourceUtils.createServiceCollection(AbstractCase.BEARER_MASTER_TOKEN, HttpStatus.SC_CREATED, CELL_NAME,
            BOX_NAME, PARENT_COL_NAME);
    DavResourceUtils.createWebDavFile(MASTER_TOKEN, CELL_NAME,
            BOX_NAME + "/" + PARENT_COL_NAME + "/" + TARGET_SOURCE_FILE_PATH, "testFileBody",
            MediaType.TEXT_PLAIN,
            HttpStatus.SC_CREATED);

    // Role作成
    RoleUtils.create(CELL_NAME, MASTER_TOKEN, ROLE, HttpStatus.SC_CREATED);

    // Account作成
    AccountUtils.create(MASTER_TOKEN, CELL_NAME, ACCOUNT, PASSWORD, HttpStatus.SC_CREATED);
    LinksUtils.createLinks(CELL_NAME, Account.EDM_TYPE_NAME, ACCOUNT, null,
            Role.EDM_TYPE_NAME, ROLE, null, MASTER_TOKEN, HttpStatus.SC_NO_CONTENT);
}
 
Example 9
Project: OpenJSharp   File: JAXBDispatch.java   Source Code and License 6 votes vote down vote up
Object toReturnValue(Packet response) {
    try {
        Unmarshaller unmarshaller = jaxbcontext.createUnmarshaller();
        Message msg = response.getMessage();
        switch (mode) {
            case PAYLOAD:
                return msg.<Object>readPayloadAsJAXB(unmarshaller);
            case MESSAGE:
                Source result = msg.readEnvelopeAsSource();
                return unmarshaller.unmarshal(result);
            default:
                throw new WebServiceException("Unrecognized dispatch mode");
        }
    } catch (JAXBException e) {
        throw new WebServiceException(e);
    }
}
 
Example 10
Project: OpenJSharp   File: SOAPFaultBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Creates a DOM node that represents the complete stack trace of the exception,
 * and attach that to {@link DetailType}.
 */
final void captureStackTrace(@Nullable Throwable t) {
    if(t==null)     return;
    if(!captureStackTrace)  return;     // feature disabled

    try {
        Document d = DOMUtil.createDom();
        ExceptionBean.marshal(t,d);

        DetailType detail = getDetail();
        if(detail==null)
        setDetail(detail=new DetailType());

        detail.getDetails().add(d.getDocumentElement());
    } catch (JAXBException e) {
        // this should never happen
        logger.log(Level.WARNING, "Unable to capture the stack trace into XML",e);
    }
}
 
Example 11
Project: personium-core   File: ServiceSourceAccessControlTest.java   Source Code and License 6 votes vote down vote up
/**
 * 親コレクションにwrite権限があるアカウントでファイルの作成を行い201となること.
 * @throws JAXBException ACLのパース失敗
 */
@Test
public void 親コレクションにwrite権限があるアカウントでファイルの作成を行い201となること() throws JAXBException {
    String token;
    String path = String.format("%s/%s", PARENT_COL_NAME, TARGET_SOURCE_FILE_PATH + "new");

    // ACL設定
    setAcl(PARENT_COL_NAME, ROLE, "write");

    // アクセストークン取得
    token = getToken(ACCOUNT);

    // リクエスト実行
    DavResourceUtils.createWebDavFile(token, CELL_NAME, BOX_NAME + "/" + path, "testFileBody",
            MediaType.TEXT_PLAIN, HttpStatus.SC_CREATED);
}
 
Example 12
Project: incubator-netbeans   File: WadlSaas.java   Source Code and License 6 votes vote down vote up
public Metadata getOauthMetadata() throws IOException, JAXBException {
    if (wadlModel == null) {
        throw new IllegalStateException("Should transition state to at least RETRIEVED");
    }
    if (wadlModel.getGrammars() == null || wadlModel.getGrammars().getAny() == null) {
        return null;
    }
    List<Object> otherGrammars = wadlModel.getGrammars().getAny();
    for (Object g : otherGrammars) {
        if (g instanceof Element) {
            Element el = (Element)g;
            if ("http://netbeans.org/ns/oauth/metadata/1".equals(el.getNamespaceURI()) && //NOI18N
                    "metadata".equals(el.getLocalName())) { //NOI18N
                JAXBContext jc = JAXBContext.newInstance("org.netbeans.modules.websvc.saas.model.oauth"); //NOI18N
                Unmarshaller u = jc.createUnmarshaller();
                JAXBElement<Metadata> jaxbEl = u.unmarshal(el, Metadata.class);
                return jaxbEl.getValue();
            }
        }
    }
    return null;
}
 
Example 13
Project: personium-core   File: FileAccessControlTest.java   Source Code and License 6 votes vote down vote up
/**
 * 親コレクションにreadproperties権限がある_かつ_対象ファイルにreadacl権限があるアカウントでファイルのPROPFINDを行い全ての情報が表示されること.
 * @throws JAXBException ACLのパース失敗
 */
@Test
public void 親コレクションにreadproperties権限がある_かつ_対象ファイルにreadacl権限があるアカウントでファイルのPROPFINDを行い全ての情報が表示されること()
        throws JAXBException {
    String token;
    String path = String.format("%s/%s", PARENT_COL_NAME, TARGET_FILE_NAME);
    String pathForPropfind = String.format("%s/%s/%s", BOX_NAME, PARENT_COL_NAME, TARGET_FILE_NAME);

    // ACL設定
    setAcl(PARENT_COL_NAME, ROLE, "read-properties");
    setAcl(path, ROLE, "read-acl");

    // アクセストークン取得
    token = getToken(ACCOUNT);

    // リクエスト実行
    TResponse res = DavResourceUtils.propfind(token, CELL_NAME, pathForPropfind, "1", HttpStatus.SC_MULTI_STATUS);
    String expectedUrl = UrlUtils.box(CELL_NAME, BOX_NAME, path);
    DavResourceUtils.assertContainsHrefUrl(expectedUrl, res);
    DavResourceUtils.assertContainsNodeInResXml(res, "ace");
}
 
Example 14
Project: OpenJSharp   File: UnmarshallerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public <T> JAXBElement<T> unmarshal( Source source, Class<T> expectedType ) throws JAXBException {
    if (source instanceof SAXSource) {
        SAXSource ss = (SAXSource) source;

        XMLReader locReader = ss.getXMLReader();
        if (locReader == null) {
            locReader = getXMLReader();
        }

        return unmarshal(locReader, ss.getInputSource(), expectedType);
    }
    if (source instanceof StreamSource) {
        return unmarshal(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
    }
    if (source instanceof DOMSource) {
        return unmarshal(((DOMSource) source).getNode(), expectedType);
    }

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example 15
Project: textmd   File: EditorExportDocxItem.java   Source Code and License 6 votes vote down vote up
@Override
public void getClickAction(final Dictionary dictionary, final TabFactory tabFactory, final DialogFactory dialogFactory) {
    EditorTab currTab = ((EditorTab) tabFactory.getSelectedTab());
    try {
        if (currTab.getEditorPane().saveDocx()) {
            dialogFactory.buildConfirmationDialogBox(
                    dictionary.DIALOG_EXPORT_SUCCESS_TITLE,
                    dictionary.DIALOG_EXPORT_SUCCESS_DOCX_CONTENT
            ).showAndWait();
        }
    } catch (Docx4JException | JAXBException e1) {
        dialogFactory.buildExceptionDialogBox(
                dictionary.DIALOG_EXCEPTION_TITLE,
                dictionary.DIALOG_EXCEPTION_EXPORT_DOCX_CONTENT,
                e1.getMessage(),
                e1
        ).showAndWait();
    }
}
 
Example 16
Project: OpenJSharp   File: EndpointArgumentsBuilder.java   Source Code and License 6 votes vote down vote up
public void readRequest(Message msg, Object[] args) throws JAXBException {
    com.sun.xml.internal.ws.api.message.Header header = null;
    Iterator<com.sun.xml.internal.ws.api.message.Header> it =
        msg.getHeaders().getHeaders(headerName,true);
    if (it.hasNext()) {
        header = it.next();
        if (it.hasNext()) {
            throw createDuplicateHeaderException();
        }
    }

    if(header!=null) {
        setter.put( header.readAsJAXB(bridge), args );
    } else {
        // header not found.
    }
}
 
Example 17
Project: personium-core   File: MoveServiceCollectionAclTest.java   Source Code and License 6 votes vote down vote up
/**
 * 移動元の親にread権限を持つ_かつ_移動対象にread権限を持つアカウントでServiceコレクションのMOVEをした場合403となること.
 * @throws JAXBException ACLのパース失敗
 */
@Test
public void 移動元の親にwrite権限を持つ_かつ_移動先の親にread権限を持つアカウントでServiceコレクションのMOVEをした場合403となること()
        throws JAXBException {
    String token;
    String path = String.format("%s/%s/%s", BOX_NAME, SRC_COL_NAME, COL_NAME);
    String destination = UrlUtils.box(CELL_NAME, BOX_NAME, DST_COL_NAME, COL_NAME);
    String srcColPath = SRC_COL_NAME + "/" + COL_NAME;

    // 事前準備
    setDefaultAcl(SRC_COL_NAME);
    setAcl(DST_COL_NAME, ROLE_WRITE, "read");

    DavResourceUtils.createServiceCollection(
            BEARER_MASTER_TOKEN, HttpStatus.SC_CREATED, CELL_NAME, BOX_NAME, srcColPath);

    // 親にwrite権限+移動先の親にread権限→403
    token = getToken(ACCOUNT_WRITE);
    TResponse res = DavResourceUtils.moveWebDav(token, CELL_NAME, path, destination, HttpStatus.SC_FORBIDDEN);
    PersoniumCoreException expectedException = PersoniumCoreException.Auth.NECESSARY_PRIVILEGE_LACKING;
    ODataCommon.checkErrorResponseBody(res, expectedException.getCode(), expectedException.getMessage());
}
 
Example 18
Project: sumo   File: SumoXPathSafeReader.java   Source Code and License 6 votes vote down vote up
public void readAcquisitionPeriod() throws JAXBException, SAXException {
	acquPeriod = new AcquisitionPeriod();

	String xPathStartTime = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData//*[name()='safe:startTime']";
	String xPathStopTime = "/xfdu:XFDU/metadataSection/metadataObject/metadataWrap/xmlData//*[name()='safe:stopTime']";

	XPathExpression<Element> expr = xFactory.compile(xPathStartTime,
			Filters.element(), null, xfdu, safeNs);
	Element e = expr.evaluateFirst(safe);

	if (e != null)
		acquPeriod.setStartTime(e.getValue());

	expr = xFactory.compile(xPathStopTime, Filters.element(), null, xfdu,
			safeNs);
	e = expr.evaluateFirst(safe);
	if (e != null)
		acquPeriod.setStopTime(e.getValue());
}
 
Example 19
Project: oxygen-dita-translation-package-builder   File: HistoryUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Loads chosen paths for the package location from disk.
 * 
 * @return A list with the absolute file paths of the package.
 * 
 * @throws JAXBException  Problems with JAXB, serialization/deserialization of a file.
 * @throws IOException  Problems reading the file/directory.
 */
public static ArrayList<ComboItem> loadSelectedPaths() {
  ArrayList<ComboItem> entries = null;
  JAXBContext context;
  try {
    context = JAXBContext.newInstance(ComboHistory.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    String option = optionsStorage.getOption(REPORT_DIALOG_HISTORY, null);
    if (option != null) {
      ComboHistory resources = (ComboHistory) unmarshaller.unmarshal(new StringReader(option));
      entries = resources.getEntries();
    }
  } catch (JAXBException e) {
    logger.error(e, e);
  }

  return entries;
}
 
Example 20
Project: Steam-trader-tools   File: AppController.java   Source Code and License 6 votes vote down vote up
@FXML
private void saveNewAppListToXml(ActionEvent event)
{
    JAXBContext context;
    try
    {
        context = JAXBContext.newInstance(UserAppList.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        FileChooser fc = new FileChooser();
        File file = fc.showSaveDialog(null);
        if (file != null)
        {
            marshaller.marshal(userAppList, file);
            JFXSnackbar info = new JFXSnackbar(root);
            info.show(I18n.getMessage("savedtoxml") + file.getAbsolutePath(), 3000);
            prefs.put(PreferencesKeys.SAVE_PATH.toString(), file.getAbsolutePath());
        }
    } catch (JAXBException e)
    {
        e.printStackTrace();
    }

}
 
Example 21
Project: personium-core   File: ServiceSourceAccessControlTest.java   Source Code and License 6 votes vote down vote up
/**
 * 移動元の親コレクションに権限がないアカウントでファイルの移動を行い403になること.
 * @throws JAXBException ACLのパース失敗
 */
@Test
public void 移動元の親コレクションに権限がないアカウントでファイルの移動を行い403になること() throws JAXBException {
    String token;
    String path = String.format("%s/%s", PARENT_COL_NAME, TARGET_SOURCE_FILE_PATH);
    String dstColName = "dstColName";
    String destination = UrlUtils.box(CELL_NAME, BOX_NAME, dstColName, "destFile.js");

    // 移動先コレクション作成
    DavResourceUtils.createWebDavCollection(MASTER_TOKEN, HttpStatus.SC_CREATED, CELL_NAME, BOX_NAME,
            dstColName);
    setAcl(dstColName, ROLE, "write");

    // アクセストークン取得
    token = getToken(ACCOUNT);

    // リクエスト実行
    TResponse res = DavResourceUtils.moveWebDav(token, CELL_NAME, BOX_NAME + "/" + path, destination,
            HttpStatus.SC_FORBIDDEN);
    PersoniumCoreException expectedException = PersoniumCoreException.Auth.NECESSARY_PRIVILEGE_LACKING;
    ODataCommon.checkErrorResponseBody(res, expectedException.getCode(), expectedException.getMessage());
}
 
Example 22
Project: JavaRushTasks   File: Solution.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws JAXBException {
    String xmlData =
            "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                    "<shop>\n" +
                    "    <goods>\n" +
                    "        <names>S1</names>\n" +
                    "        <names>S2</names>\n" +
                    "    </goods>\n" +
                    "    <count>12</count>\n" +
                    "    <profit>123.4</profit>\n" +
                    "    <secretData>String1</secretData>\n" +
                    "    <secretData>String2</secretData>\n" +
                    "    <secretData>String3</secretData>\n" +
                    "    <secretData>String4</secretData>\n" +
                    "    <secretData>String5</secretData>\n" +
                    "</shop>";

    StringReader reader = new StringReader(xmlData);

    JAXBContext context = JAXBContext.newInstance(getClassName());
    Unmarshaller unmarshaller = context.createUnmarshaller();

    Object o = unmarshaller.unmarshal(reader);

    System.out.println(o.toString());
}
 
Example 23
Project: personium-core   File: MoveFileAccessControlTest.java   Source Code and License 6 votes vote down vote up
/**
 * 移動先Collectionに権限を持たないアカウントでファイルのMOVEをした場合403エラーとなること.
 * @throws JAXBException ACLのパース失敗
 */
@Test
public void 移動先Collectionに権限を持たないアカウントでファイルのMOVEをした場合403エラーとなること() throws JAXBException {
    String token;
    String path = String.format("%s/%s/%s", BOX_NAME, SRC_COL_NAME, FILE_NAME);
    String destination = UrlUtils.box(CELL_NAME, BOX_NAME, DST_COL_NAME, FILE_NAME);

    try {
        // 事前準備
        setPrincipalAllAcl(SRC_COL_NAME);
        setDefaultAcl(DST_COL_NAME);

        DavResourceUtils.createWebDavFile(MASTER_TOKEN, CELL_NAME, path, FILE_BODY, MediaType.TEXT_PLAIN,
                HttpStatus.SC_CREATED);

        // 権限なし→403
        token = getToken(ACCOUNT_NO_PRIVILEGE);
        TResponse res = DavResourceUtils.moveWebDav(token, CELL_NAME, path, destination,
                HttpStatus.SC_FORBIDDEN);
        PersoniumCoreException expectedException = PersoniumCoreException.Auth.NECESSARY_PRIVILEGE_LACKING;
        ODataCommon.checkErrorResponseBody(res, expectedException.getCode(), expectedException.getMessage());

    } finally {
        DavResourceUtils.deleteWebDavFile(CELL_NAME, MASTER_TOKEN, BOX_NAME, SRC_COL_NAME + "/" + FILE_NAME);
    }
}
 
Example 24
Project: cf-mta-deploy-service   File: XmlNamespaceIgnoringMessageBodyReader.java   Source Code and License 5 votes vote down vote up
private XMLFilter createXmlFilter(Unmarshaller unmarshaller, String namespaceToSet) throws JAXBException {
    try {
        XMLFilter filter = new XmlNamespaceInjectionFilter(createXmlReader(), namespaceToSet);
        filter.setContentHandler(unmarshaller.getUnmarshallerHandler());
        return filter;
    } catch (SAXException | ParserConfigurationException e) {
        throw new JAXBException(e);
    }
}
 
Example 25
Project: NGB-master   File: PdbDataManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testParseMapPdp() throws IOException, ExternalDbUnavailableException, InterruptedException,
        JAXBException {
    // arrange
    String fetchRes = readFile("pbd_map_id_2k8d.xml");

    Mockito.when(
            httpDataManager.fetchData(Mockito.any(String.class), Mockito.any(ParameterNameValue[].class))
    ).thenReturn(fetchRes);

    final Dasalignment dataset = pdbDataManager.fetchPdbMapEntry("2K8F");
    Assert.assertNotNull(dataset);
    Assert.assertNotNull(dataset.getAlignment());
    final List<Alignment> alignmentList = dataset.getAlignment();
    Assert.assertFalse(alignmentList.isEmpty());
    final Alignment alignment = alignmentList.get(0);
    Assert.assertNotNull(alignment);
    Assert.assertFalse(alignment.getBlock().isEmpty());
    Assert.assertNotNull(alignment.getBlock());
    final PdbBlock pdbBlock = alignment.getBlock().get(0);
    Assert.assertNotNull(pdbBlock);
    Assert.assertNotNull(pdbBlock.getSegment());
    Assert.assertFalse(pdbBlock.getSegment().isEmpty());
    final Segment segment = pdbBlock.getSegment().get(0);
    Assert.assertNotNull(segment);
    Assert.assertNotNull(segment.getIntObjectId());
    Assert.assertNotNull(segment.getStart());
    Assert.assertNotNull(segment.getEnd());
}
 
Example 26
Project: ditb   File: TestTableResource.java   Source Code and License 5 votes vote down vote up
@Test
public void testTableListXML() throws IOException, JAXBException {
  Response response = client.get("/", Constants.MIMETYPE_XML);
  assertEquals(response.getCode(), 200);
  assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
  TableListModel model = (TableListModel)
    context.createUnmarshaller()
      .unmarshal(new ByteArrayInputStream(response.getBody()));
  checkTableList(model);
}
 
Example 27
Project: openjdk-jdk10   File: JAXBContextWithAbstractFactory.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws JAXBException {
    System.out.println("\nWithout security manager\n");
    test();

    System.out.println("\nWith security manager\n");
    Policy.setPolicy(new Policy() {
        @Override
        public boolean implies(ProtectionDomain domain, Permission permission) {
            return true; // allow all
        }
    });
    System.setSecurityManager(new SecurityManager());
    test();
}
 
Example 28
Project: ditb   File: RowResourceBase.java   Source Code and License 5 votes vote down vote up
protected static void checkValueJSON(String table, String row, String column,
    String value) throws IOException, JAXBException {
  Response response = getValueJson(table, row, column);
  assertEquals(response.getCode(), 200);
  assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type"));
  ObjectMapper mapper = new JacksonProvider()
  .locateMapper(CellSetModel.class, MediaType.APPLICATION_JSON_TYPE);
  CellSetModel cellSet = mapper.readValue(response.getBody(), CellSetModel.class);
  RowModel rowModel = cellSet.getRows().get(0);
  CellModel cell = rowModel.getCells().get(0);
  assertEquals(Bytes.toString(cell.getColumn()), column);
  assertEquals(Bytes.toString(cell.getValue()), value);
}
 
Example 29
Project: Steam-trader-tools   File: AllAppList.java   Source Code and License 5 votes vote down vote up
public void saveToXml()
{
    JAXBContext context;
    try {
        context = JAXBContext.newInstance(this.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        File file = new File("steamAppList.xml");
        marshaller.marshal(this,file);
    } catch (JAXBException e) {
        e.printStackTrace();
    }
}
 
Example 30
Project: personium-core   File: MoveODataCollectionAclTest.java   Source Code and License 5 votes vote down vote up
/**
 * 指定されたコレクションに対し、Role毎に対応するPrivilegeを設定.
 * @param collection コレクション名
 * @param roleRead read権限を設定するRole名
 * @param roleWrite writed権限を設定するRole名
 * @param roleAll all権限を設定するRole名
 * @throws JAXBException ACLのパースに失敗
 */
private void setDefaultAcl(String collection, String roleRead, String roleWrite, String roleAll)
        throws JAXBException {
    Acl acl = new Acl();
    acl.getAce().add(DavResourceUtils.createAce(false, roleRead, "read"));
    acl.getAce().add(DavResourceUtils.createAce(false, roleWrite, "write"));
    acl.getAce().add(DavResourceUtils.createAce(false, roleAll, "all"));
    List<String> privileges = new ArrayList<String>();
    privileges.add("read");
    privileges.add("write");
    acl.getAce().add(DavResourceUtils.createAce(false, ROLE_COMB_PRIVILEGE, privileges));
    acl.setXmlbase(String.format("%s/%s/__role/%s/", UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME));

    DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, collection, acl, HttpStatus.SC_OK);
}
 
Example 31
Project: OpenJSharp   File: RuntimeClassInfoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public RuntimePropertySeed createAccessorSeed(Method getter, Method setter) {
    Accessor acc;
    try {
        acc = accessorFactory.createPropertyAccessor(clazz, getter, setter);
    } catch(JAXBException e) {
        builder.reportError(new IllegalAnnotationException(
            Messages.CUSTOM_ACCESSORFACTORY_PROPERTY_ERROR.format(
            nav().getClassName(clazz), e.toString()), this ));
        acc = Accessor.getErrorInstance(); // error recovery
    }
    return new RuntimePropertySeed( super.createAccessorSeed(getter,setter),
      acc );
}
 
Example 32
Project: OpenJSharp   File: AbstractHeaderImpl.java   Source Code and License 5 votes vote down vote up
public <T> T readAsJAXB(Unmarshaller unmarshaller) throws JAXBException {
    try {
        return (T)unmarshaller.unmarshal(readHeader());
    } catch (Exception e) {
        throw new JAXBException(e);
    }
}
 
Example 33
Project: LIRE-Lab   File: CollectionAssembler.java   Source Code and License 5 votes vote down vote up
public Collection assembleCollectionFrom(Path collectionPath) throws JAXBException {
    CollectionXMLDAO dao = new CollectionXMLDAO(collectionPath.toFile());
    Collection collection = dao.readCollection();

    collection.setImages(getImagesOf(collection));

    return collection;
}
 
Example 34
Project: personium-core   File: FileAccessControlTest.java   Source Code and License 5 votes vote down vote up
/**
 * 親コレクションに権限がない_かつ_対象ファイルに権限がないアカウントでファイルのDELETEを行い403エラーとなること.
 * @throws JAXBException ACLのパース失敗
 */
@Test
public void 親コレクションに権限がない_かつ_対象ファイルに権限がないアカウントでファイルのDELETEを行い403エラーとなること() throws JAXBException {
    String token;
    String path = String.format("%s/%s", PARENT_COL_NAME, TARGET_FILE_NAME);

    // アクセストークン取得
    token = getToken(ACCOUNT);

    // リクエスト実行
    TResponse res = DavResourceUtils.deleteWebDavFile(CELL_NAME, token, BOX_NAME, path);
    assertThat(res.getStatusCode()).isEqualTo(HttpStatus.SC_FORBIDDEN);
    PersoniumCoreException expectedException = PersoniumCoreException.Auth.NECESSARY_PRIVILEGE_LACKING;
    ODataCommon.checkErrorResponseBody(res, expectedException.getCode(), expectedException.getMessage());
}
 
Example 35
Project: OpenJSharp   File: TransducedAccessor.java   Source Code and License 5 votes vote down vote up
public String print(BeanT bean) throws AccessorException, SAXException {
    TargetT target = acc.get(bean);
    if(target==null)    return null;

    XMLSerializer w = XMLSerializer.getInstance();
    try {
        String id = w.grammar.getBeanInfo(target,true).getId(target,w);
        if(id==null)
            w.errorMissingId(target);
        return id;
    } catch (JAXBException e) {
        w.reportError(null,e);
        return null;
    }
}
 
Example 36
Project: Open_Source_ECOA_Toolset_AS5   File: NodePropertySource.java   Source Code and License 5 votes vote down vote up
private String[] getSimpleTypes() {
	ArrayList<String> ret = new ArrayList<String>();
	ret.add("");
	try {
		TypesUtil util = TypesUtil.getInstance(node.getContainerName());
		util.setFileName("");
		ret.addAll(util.getAllTypesForSimpleWizard());
	} catch (IOException | JAXBException e) {
		e.printStackTrace();
	}
	return ret.toArray(new String[0]);
}
 
Example 37
Project: redirector   File: JSONSerializer.java   Source Code and License 5 votes vote down vote up
private <T> T deserializeInternal(StreamSource streamSource, Class<T> clazz) throws SerializerException {
    try {
        Unmarshaller unmarshaller = context.createUnmarshaller();
        unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json");
        unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
        unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true);
        return unmarshaller.unmarshal(streamSource, clazz).getValue();
    } catch (JAXBException e) {
        log.error("Can't deserialize object of type {}", clazz.getSimpleName());
        throw new SerializerException("Can't deserialize object of type " + clazz.getSimpleName(), e);
    }
}
 
Example 38
Project: jaffa-framework   File: RoleManager.java   Source Code and License 5 votes vote down vote up
/**
 * registerResource - Registers the roles into the role repository from the roles.xml files found in META-INF/roles.xml
 * that exist in the classpath.
 * @param resource the object that contains the xml config file.
 * @param context  key with which config file to be registered.
 * @throws JAXBException
 * @throws SAXException
 * @throws IOException
 */
@Override
public void registerResource(Resource resource, String context, String variation) throws JAXBException, SAXException, IOException {

    Roles roles = JAXBHelper.unmarshalConfigFile(Roles.class, resource, CONFIGURATION_SCHEMA_FILE);
    if (roles.getRole() != null) {
        for (final Role role : roles.getRole()) {
            ContextKey key = new ContextKey(role.getName(), resource.getURI().toString(), variation, context);
            registerRole(key, role);
        }
    }
}
 
Example 39
Project: openjdk-jdk10   File: MarshallerBridge.java   Source Code and License 5 votes vote down vote up
public void marshal(Marshaller m, Object object, XMLStreamWriter output) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        m.marshal(object,output);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example 40
Project: stvs   File: StvsMainScene.java   Source Code and License 5 votes vote down vote up
/**
 * Code that should be executed before the scene is destroyed on exit.
 */
public void onClose() {
  StvsRootModel stvsRootModel = rootModelProperty.get();
  if (stvsRootModel != null) {
    try {
      stvsRootModel.getGlobalConfig().autosaveConfig();
      stvsRootModel.getHistory().autosaveHistory();
      stvsRootModel.autosaveSession();
    } catch (IOException | ExportException | JAXBException e) {
      AlertFactory.createAlert(Alert.AlertType.ERROR, "Autosave error",
          "Error saving the current" + " configuration",
          "The current configuration could not be saved.", e.getMessage()).showAndWait();
    }
  }
}