javax.xml.bind.JAXBException Java Examples

The following examples show how to use javax.xml.bind.JAXBException. 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 Project: incubator-atlas   Author: apache   File: FalconHookIT.java    License: Apache License 2.0 6 votes vote down vote up
private <T extends Entity> T loadEntity(EntityType type, String resource, String name) throws JAXBException {
    Entity entity = (Entity) type.getUnmarshaller().unmarshal(this.getClass().getResourceAsStream(resource));
    switch (entity.getEntityType()) {
        case CLUSTER:
            ((Cluster) entity).setName(name);
            break;

        case FEED:
            ((Feed) entity).setName(name);
            break;

        case PROCESS:
            ((org.apache.falcon.entity.v0.process.Process) entity).setName(name);
            break;
    }
    return (T)entity;
}
 
Example #2
Source Project: container   Author: OpenTOSCA   File: ODEEndpointUpdater.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of QName's which are referenced in the ODE deploy.xml File as invoked service.<br>
 *
 * @param deployXML a file object of a valid deploy.xml File
 * @return a list of QNames which represent the PortTypes used by the BPEL process to invoke operations
 * @throws JAXBException if the JAXB parser couldn't work properly
 */
private List<QName> getInvokedDeployXMLPorts(final File deployXML) throws JAXBException {
    // http://svn.apache.org/viewvc/ode/trunk/bpel-schemas/src/main/xsd/
    // grabbed that and using jaxb
    final List<QName> qnames = new LinkedList<>();
    final JAXBContext context =
        JAXBContext.newInstance("org.apache.ode.schemas.dd._2007._03", this.getClass().getClassLoader());
    final Unmarshaller unmarshaller = context.createUnmarshaller();
    final TDeployment deploy = unmarshaller.unmarshal(new StreamSource(deployXML), TDeployment.class).getValue();
    for (final org.apache.ode.schemas.dd._2007._03.TDeployment.Process process : deploy.getProcess()) {
        for (final TInvoke invoke : process.getInvoke()) {
            final QName serviceName = invoke.getService().getName();
            // add only qnames which aren't from the plan itself
            if (!serviceName.getNamespaceURI().equals(process.getName().getNamespaceURI())) {
                qnames.add(new QName(serviceName.getNamespaceURI(), invoke.getService().getPort()));
            }
        }
    }
    return qnames;
}
 
Example #3
Source Project: hottub   Author: dsrg-uoft   File: BinderImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
private Object associativeUnmarshal(XmlNode xmlNode, boolean inplace, Class expectedType) throws JAXBException {
    if (xmlNode == null)
        throw new IllegalArgumentException();

    JaxBeanInfo bi = null;
    if(expectedType!=null)
        bi = context.getBeanInfo(expectedType, true);

    InterningXmlVisitor handler = new InterningXmlVisitor(
        getUnmarshaller().createUnmarshallerHandler(scanner,inplace,bi));
    scanner.setContentHandler(new SAXConnector(handler,scanner.getLocator()));
    try {
        scanner.scan(xmlNode);
    } catch( SAXException e ) {
        throw unmarshaller.createUnmarshalException(e);
    }

    return handler.getContext().getResult();
}
 
Example #4
Source Project: OpenID-Attacker   Author: RUB-NDS   File: XmlPersistenceHelper.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Load the current config from an XML file.
 *
 * @param loadFile
 */
public static void mergeConfigFileToConfigObject(final File loadFile, ToolConfiguration currentToolConfig) throws XmlPersistenceError {
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(ToolConfiguration.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        ToolConfiguration loadedConfig = (ToolConfiguration) jaxbUnmarshaller.unmarshal(loadFile);
        
        //BeanUtils.copyProperties(currentToolConfig, loadedConfig);
        //ServerController controller = new ServerController();
        BeanUtils.copyProperties(currentToolConfig.getAttackerConfig(), loadedConfig.getAttackerConfig());
        BeanUtils.copyProperties(currentToolConfig.getAnalyzerConfig(), loadedConfig.getAnalyzerConfig());
        
        LOG.info(String.format("Loaded successfully config from '%s'", loadFile.getAbsoluteFile()));
    } catch (InvocationTargetException | IllegalAccessException | JAXBException ex) {
        throw new XmlPersistenceError(String.format("Could not load config from File '%s'", loadFile.getAbsoluteFile()), ex);
    }
}
 
Example #5
Source Project: audiveris   Author: Audiveris   File: TestEntity.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
private void marshall ()
        throws JAXBException, FileNotFoundException, IOException, XMLStreamException
{
    File target = new File(dir, indexFileName);
    Files.deleteIfExists(target.toPath());

    MyBasicIndex<MyEntity> index = new MyBasicIndex<MyEntity>("my-index-name");

    index.register(new MyGlyph("First"));
    index.register(new MySymbol(100));
    index.register(new MyGlyph("Second"));
    index.register(new MyGlyph("Third"));
    index.register(new MySymbol(200));

    new Dumping().dump(index);
    System.out.println("index: " + index);

    System.out.println("Marshalling ...");
    Jaxb.marshal(index, target.toPath(), jaxbContext);
    System.out.println("Marshalled   to   " + target);
    System.out.println("=========================================================");
    Jaxb.marshal(index, System.out, jaxbContext);
}
 
Example #6
Source Project: io   Author: fujitsu-pio   File: MoveODataCollectionAclTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 移動元の親にread権限を持つ_かつ_移動先の親にread権限を持つアカウントでODataコレクションのMOVEをした場合403となること.
 * @throws JAXBException ACLのパース失敗
 */
@Test
public void 移動元の親にread権限を持つ_かつ_移動先の親にread権限を持つアカウントでODataコレクションの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);
    setDefaultAcl(DST_COL_NAME);

    DavResourceUtils.createODataCollection(
            MASTER_TOKEN, HttpStatus.SC_CREATED, CELL_NAME, BOX_NAME, srcColPath);

    // 親にread権限+移動先の親にread権限→403
    token = getToken(ACCOUNT_READ);
    TResponse res = DavResourceUtils.moveWebDav(token, CELL_NAME, path, destination, HttpStatus.SC_FORBIDDEN);
    DcCoreException expectedException = DcCoreException.Auth.NECESSARY_PRIVILEGE_LACKING;
    ODataCommon.checkErrorResponseBody(res, expectedException.getCode(), expectedException.getMessage());
}
 
Example #7
Source Project: openjdk-8-source   Author: keerath   File: JAXBContextImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public JAXBIntrospector createJAXBIntrospector() {
    return new JAXBIntrospector() {
        public boolean isElement(Object object) {
            return getElementName(object)!=null;
        }

        public QName getElementName(Object jaxbElement) {
            try {
                return JAXBContextImpl.this.getElementName(jaxbElement);
            } catch (JAXBException e) {
                return null;
            }
        }
    };
}
 
Example #8
Source Project: Java8CN   Author: Java8-CNAPI-Team   File: AbstractUnmarshallerImpl.java    License: Apache License 2.0 6 votes vote down vote up
public Object unmarshal( Source source ) throws JAXBException {
    if( source == null ) {
        throw new IllegalArgumentException(
            Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
    }

    if(source instanceof SAXSource)
        return unmarshal( (SAXSource)source );
    if(source instanceof StreamSource)
        return unmarshal( streamSourceToInputSource((StreamSource)source));
    if(source instanceof DOMSource)
        return unmarshal( ((DOMSource)source).getNode() );

    // we don't handle other types of Source
    throw new IllegalArgumentException();
}
 
Example #9
Source Project: bonita-studio   Author: bonitasoft   File: BusinessDataModelFormPart.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void commit(boolean onSave) {
    BusinessObjectModel workingCopy = formPage.observeWorkingCopy().getValue();
    JobSafeStructuredDocument document = (JobSafeStructuredDocument) formPage.getDocument();
    DocumentRewriteSession session = null;
    try {
        session = document.startRewriteSession(DocumentRewriteSessionType.STRICTLY_SEQUENTIAL);
        document.set(new String(formPage.getParser().marshall(formPage.getConverter().toEngineModel(workingCopy))));
        BDMArtifactDescriptor bdmArtifactDescriptor = new BDMArtifactDescriptor();
        bdmArtifactDescriptor.setGroupId(workingCopy.getGroupId());
        formPage.getEditorContribution().saveBdmArtifactDescriptor(bdmArtifactDescriptor);
    } catch (final JAXBException | IOException | SAXException e) {
        throw new RuntimeException("Fail to update the document", e);
    } finally {
        if (session != null) {
            document.stopRewriteSession(session);
        }
    }
    super.commit(onSave);
    if (onSave) {
        getManagedForm().dirtyStateChanged();
    }
}
 
Example #10
Source Project: io   Author: fujitsu-pio   File: MoveServiceSourceAccessControlTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 移動元Collectionにread権限を持つアカウントでServiceSourceのMOVEをした場合403エラーとなること.
 * @throws JAXBException ACLのパース失敗
 */
@Test
public void 移動元Collectionにread権限を持つアカウントでServiceSourceのMOVEをした場合403エラーとなること() throws JAXBException {
    String token;
    String path = String.format("%s/%s/__src/%s", BOX_NAME, SRC_COL_NAME, FILE_NAME);
    String destination = UrlUtils.box(CELL_NAME, BOX_NAME, DST_COL_NAME, "__src", FILE_NAME);

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

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

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

    } finally {
        DavResourceUtils.deleteWebDavFile(CELL_NAME, MASTER_TOKEN, BOX_NAME, SRC_COL_NAME + "/__src/" + FILE_NAME);
    }
}
 
Example #11
Source Project: everrest   Author: codenvy   File: JAXBElementEntityProvider.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void writeTo(JAXBElement<?> t,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException {
    Class<?> declaredType = t.getDeclaredType();
    try {
        JAXBContext jaxbContext = getJAXBContext(declaredType, mediaType);
        Marshaller marshaller = jaxbContext.createMarshaller();
        String charset = getCharset(mediaType);
        if (!isNullOrEmpty(charset)) {
            marshaller.setProperty(Marshaller.JAXB_ENCODING, charset);
        }

        marshaller.marshal(t, entityStream);
    } catch (JAXBException e) {
        throw new IOException(String.format("Can't write to output stream, %s", e));
    }
}
 
Example #12
Source Project: cql_engine   Author: DBCG   File: CqlLibraryReader.java    License: Apache License 2.0 6 votes vote down vote up
public static Unmarshaller getUnmarshaller() throws JAXBException {
    // This is supposed to work based on this link:
    // https://jaxb.java.net/2.2.11/docs/ch03.html#compiling-xml-schema-adding-behaviors
    // Override the unmarshal to use the XXXEvaluator classes
    // This doesn't work exactly how it's described in the link above, but this is functional
    if (context == null)
    {
        context = JAXBContext.newInstance(ObjectFactory.class);
    }

    if (unmarshaller == null) {
        unmarshaller = context.createUnmarshaller();
        try {
            // https://bugs.eclipse.org/bugs/show_bug.cgi?id=406032
            //https://javaee.github.io/jaxb-v2/doc/user-guide/ch03.html#compiling-xml-schema-adding-behaviors
            // for jre environment
            unmarshaller.setProperty("com.sun.xml.bind.ObjectFactory", new ObjectFactoryEx());
        } catch (javax.xml.bind.PropertyException e) {
            // for jdk environment
            unmarshaller.setProperty("com.sun.xml.internal.bind.ObjectFactory", new ObjectFactoryEx());
        }
    }

    return unmarshaller;
}
 
Example #13
Source Project: jdk8u60   Author: chenghanpeng   File: UnmarshallerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public final ValidationEventHandler getEventHandler() {
    try {
        return super.getEventHandler();
    } catch (JAXBException e) {
        // impossible
        throw new AssertionError();
    }
}
 
Example #14
Source Project: freehealth-connector   Author: taktik   File: JaxbContextFactory.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static JAXBContext getJaxbContextForClass(Class... classesToBeBound) throws JAXBException {
   String key = calculateKey(classesToBeBound);
   JAXBContext context = (JAXBContext)CACHE.get(key);
   if (context == null) {
      context = JAXBContext.newInstance(classesToBeBound);
      CACHE.put(key, context);
   }

   return context;
}
 
Example #15
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: UnmarshallerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public final ValidationEventHandler getEventHandler() {
    try {
        return super.getEventHandler();
    } catch (JAXBException e) {
        // impossible
        throw new AssertionError();
    }
}
 
Example #16
Source Project: hbase   Author: apache   File: RowResourceBase.java    License: Apache License 2.0 5 votes vote down vote up
protected static Response putValueXML(String url, String table, String row,
    String column, String value) throws IOException, JAXBException {
  RowModel rowModel = new RowModel(row);
  rowModel.addCell(new CellModel(Bytes.toBytes(column),
    Bytes.toBytes(value)));
  CellSetModel cellSetModel = new CellSetModel();
  cellSetModel.addRow(rowModel);
  StringWriter writer = new StringWriter();
  xmlMarshaller.marshal(cellSetModel, writer);
  Response response = client.put(url, Constants.MIMETYPE_XML,
    Bytes.toBytes(writer.toString()));
  Thread.yield();
  return response;
}
 
Example #17
Source Project: micro-integrator   Author: wso2   File: DataSourceRepository.java    License: Apache License 2.0 5 votes vote down vote up
public DataSourceRepository(int tenantId) throws DataSourceException {
	this.tenantId = tenantId;
	this.dataSources = new HashMap<String, CarbonDataSource>();
	try {
	    JAXBContext ctx = JAXBContext.newInstance(DataSourceMetaInfo.class);
	    this.dsmMarshaller = ctx.createMarshaller();
	    this.dsmUnmarshaller = ctx.createUnmarshaller();
	} catch (JAXBException e) {
		throw new DataSourceException(
				"Error creating data source meta info marshaller/unmarshaller: "
		            + e.getMessage(), e);
	}
}
 
Example #18
Source Project: jdk8u60   Author: chenghanpeng   File: AbstractUnmarshallerImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public final Object unmarshal( Reader reader ) throws JAXBException {
    if( reader == null ) {
        throw new IllegalArgumentException(
            Messages.format( Messages.MUST_NOT_BE_NULL, "reader" ) );
    }

    InputSource isrc = new InputSource( reader );
    return unmarshal( isrc );
}
 
Example #19
Source Project: proarc   Author: proarc   File: DcUtils.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Default DC context. Oracle JAXB RI's context should be thread safe.
 * @see <a href='http://jaxb.java.net/faq/index.html#threadSafety'>Are the JAXB runtime API's thread safe?</a>
 */
public static JAXBContext defaultJaxbContext() throws JAXBException {
    if (defaultJaxbContext == null) {
        defaultJaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    }
    return defaultJaxbContext;
}
 
Example #20
Source Project: attic-apex-malhar   Author: apache   File: XmlParser.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void activate(Context context)
{
  try {
    JAXBContext ctx = JAXBContext.newInstance(getClazz());
    unmarshaller = ctx.createUnmarshaller();
    if (schemaXSDFile != null) {
      unmarshaller.setSchema(schema);
    }
  } catch (JAXBException e) {
    DTThrowable.wrapIfChecked(e);
  }
}
 
Example #21
Source Project: openjdk-8   Author: bpupadhyaya   File: ContextFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * If a key is present in the map, remove the value and return it.
 */
private static <T> T getPropertyValue(Map<String, Object> properties, String keyName, Class<T> type ) throws JAXBException {
    Object o = properties.get(keyName);
    if(o==null)     return null;

    properties.remove(keyName);
    if(!type.isInstance(o))
        throw new JAXBException(Messages.INVALID_PROPERTY_VALUE.format(keyName,o));
    else
        return type.cast(o);
}
 
Example #22
Source Project: dss   Author: esig   File: Reports.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * This method returns the XML representation of the JAXB ETSI Validation Report
 * String
 * 
 * @return a String with the XML content of the JAXB
 *         {@code ValidationReportType}
 * @throws DSSReportException - in case of marshalling error
 */
public String getXmlValidationReport() {
	try {
		if (xmlEtsiValidationReport == null) {
			xmlEtsiValidationReport = ValidationReportFacade.newFacade().marshall(getEtsiValidationReportJaxb(), validateXml);
		}
		return xmlEtsiValidationReport;
	} catch (JAXBException | IOException | SAXException e) {
		throw new DSSReportException("An error occurred during marshalling of JAXB Etsi Validation Report", e);
	}
}
 
Example #23
Source Project: hop   Author: project-hop   File: MetaXmlSerializer.java    License: Apache License 2.0 5 votes vote down vote up
public static String serialize( TransformMetaProps transformMetaProps ) {
  try ( ByteArrayOutputStream baos = new ByteArrayOutputStream() ) {
    Marshaller marshalObj = JAXBContext.newInstance( TransformMetaProps.class ).createMarshaller();
    marshalObj.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
    marshalObj.setProperty( Marshaller.JAXB_FRAGMENT, true );
    marshalObj.marshal( transformMetaProps, baos );
    return baos.toString( defaultCharset().name() );
  } catch ( JAXBException | IOException e ) {
    throw new RuntimeException( e );
  }
}
 
Example #24
Source Project: RISE-V2G   Author: V2GClarity   File: ExiCodec.java    License: MIT License 5 votes vote down vote up
public Object unmarshallToMessage(String decodedExiString) {
	try {
		if (getInStream() != null) getInStream().reset();
		setInStream(new ByteArrayInputStream(decodedExiString.getBytes()));
		Object unmarhalledObject = getUnmarshaller().unmarshal(getInStream());
		
		if (isXMLMsgRepresentation()) showXMLRepresentationOfMessage(unmarhalledObject);
		return unmarhalledObject;
	} catch (IOException | JAXBException | RuntimeException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to unmarshall decoded message", e);
		return null;
	}
}
 
Example #25
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: Lister.java    License: GNU General Public License v2.0 5 votes vote down vote up
public String next() throws SAXException, JAXBException {
    last = i.next();
    String id = context.grammar.getBeanInfo(last,true).getId(last,context);
    if(id==null) {
        context.errorMissingId(last);
    }
    return id;
}
 
Example #26
Source Project: bonita-studio   Author: bonitasoft   File: DeployApplicationDescriptorOperation.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void deployApplications(IProgressMonitor monitor) {
    try {
        List<ImportStatus> importStatus = applicationAPI.importApplications(
                converter.marshallToXML(applicationNodeContainer),
                ApplicationImportPolicy.FAIL_ON_DUPLICATES);
        monitor.worked(1);
        if (status.isMultiStatus()) {
            final MultiStatus mStatus = status;
            importStatus.stream()
                    .flatMap(s -> s.getErrors().stream()
                            .map(errorToStatus(displayNameForToken(s.getName(), applicationNodeContainer))))
                    .forEach(mStatus::add);
            applicationNodeContainer.getApplications().stream()
                    .map(ApplicationNode::getToken)
                    .map(name -> new Status(IStatus.OK, LivingApplicationPlugin.PLUGIN_ID,
                            StatusCode.LIVING_APP_DEPLOYMENT.ordinal(),
                            name, null))
                    .forEach(mStatus::add);
        }
    } catch (AlreadyExistsException | ImportException | IOException | JAXBException | SAXException e) {
        if (status.isMultiStatus()) {
            status.add(new Status(IStatus.ERROR, LivingApplicationPlugin.PLUGIN_ID,
                    "Failed to deploy application.", e));
        }
    } finally {
        monitor.done();
    }
}
 
Example #27
Source Project: openjdk-8   Author: bpupadhyaya   File: ExternalMetadataReader.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static JAXBContext createJaxbContext(boolean disableXmlSecurity) {
    Class[] cls = {ObjectFactory.class};
    try {
        if (disableXmlSecurity) {
            Map<String, Object> properties = new HashMap<String, Object>();
            properties.put(JAXBRIContext.DISABLE_XML_SECURITY, disableXmlSecurity);
            return JAXBContext.newInstance(cls, properties);
        } else {
            return JAXBContext.newInstance(cls);
        }
    } catch (JAXBException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #28
Source Project: vjtools   Author: vipshop   File: XmlMapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Java Object->Xml with encoding.
 */
public static String toXml(Object root, Class clazz, String encoding) {
	try {
		StringWriter writer = new StringWriter();
		createMarshaller(clazz, encoding).marshal(root, writer);
		return writer.toString();
	} catch (JAXBException e) {
		throw ExceptionUtil.unchecked(e);
	}
}
 
Example #29
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: MarshallerBridge.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void marshal(Marshaller m, Object object, Result result) throws JAXBException {
    m.setProperty(Marshaller.JAXB_FRAGMENT,true);
    try {
        m.marshal(object,result);
    } finally {
        m.setProperty(Marshaller.JAXB_FRAGMENT,false);
    }
}
 
Example #30
Source Project: dss   Author: esig   File: ASiCManifestUtils.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public JAXBContext getJAXBContext() throws JAXBException {
	if (jc == null) {
		jc = JAXBContext.newInstance(ObjectFactory.class, eu.europa.esig.asic.manifest.jaxb.ObjectFactory.class);
	}
	return jc;
}