List of usage examples for javax.xml.bind JAXBException printStackTrace
public void printStackTrace()
From source file:org.energyos.espi.thirdparty.web.AuthorizationController.java
@RequestMapping(value = Routes.THIRD_PARTY_OAUTH_CODE_CALLBACK, method = RequestMethod.GET) public String authorization(String code, String state, ModelMap model, Principal principal, @RequestParam(value = "error", required = false) String error, @RequestParam(value = "error_description", required = false) String error_description, @RequestParam(value = "error_uri", required = false) String error_uri) { try {//from w w w .j a va 2 s . c o m // Is /oauth/authorization response valid (i.e. is the "state" // element correct)? Authorization authorization = authorizationService.findByState(state); // Process valid /oauth/authorization response ApplicationInformation applicationInformation = authorization.getApplicationInformation(); // Verify /oauth/authorization Endpoint process completed // successfully if (code != null) { try { // Update Authorization record with returned authorization // code for audit purposes authorization.setCode(code); authorization.setGrantType("authorization_code"); authorization.setUpdated(new GregorianCalendar()); authorizationService.merge(authorization); // Format /oauth/token Endpoint request String url = String.format("%s?redirect_uri=%s&code=%s&grant_type=authorization_code", applicationInformation.getAuthorizationServerTokenEndpoint(), applicationInformation.getRedirectUri(), code); // Build /oauth/token Endpoint request ClientRestTemplate restTemplate = templateFactory.newClientRestTemplate( applicationInformation.getClientId(), applicationInformation.getClientSecret()); // Issue /oauth/token Endpoint request AccessToken token = restTemplate.getForObject(url, AccessToken.class); // Process /oauth/token Endpoint response if (token.getAccessToken() != null) { authorization.setAccessToken(token.getAccessToken()); authorization.setTokenType(token.getTokenType()); authorization.setExpiresIn(token.getExpiresIn()); authorization.setRefreshToken(token.getRefreshToken()); authorization.setScope(token.getScope()); authorization.setAuthorizationURI(token.getAuthorizationURI()); authorization.setResourceURI(token.getResourceURI()); authorization.setUpdated(new GregorianCalendar()); authorization.setStatus("1"); // Set authorization // record status as // "Active" authorization.setState(null); // Clear State as a // security measure // Update authorization record with /oauth/token // response data authorizationService.merge(authorization); // now do the initial import of the Authorized Resource, // if it is // not ready, then we will wait till we receive a Notify // or the UX call for it. // TODO: create a Subscription to work with if needed RetailCustomer currentCustomer = currentCustomer(principal); try { usagePointRESTRepository.findAllByRetailCustomerId(currentCustomer.getId()); } catch (JAXBException e) { // nothing there, so log the fact and move on. It // will get imported later. System.out.printf("\nThirdParty Import Exception: %s\n", e.toString()); e.printStackTrace(); } } else { System.out.printf("\n/oauth/token Request did not return an access token\n"); } } catch (HttpClientErrorException x) { // TODO: Extract error, error_description and error_uri from // JSON response. Currently recording null for all three // fields. // Update authorization record System.out.printf("\nHTTPClientException: %s\n", x.toString()); authorization.setError(error); authorization.setErrorDescription(error_description); authorization.setErrorUri(error_uri); authorization.setUpdated(new GregorianCalendar()); authorization.setStatus("2"); // Set authorization record // status as "Denied" authorization.setState(null); // Clear State as a security // measure authorizationService.merge(authorization); // TODO: Should the "message" differ based on the exception? throw new UserDeniedAuthorizationException("Unable to retrieve OAuth token", x); } } else { System.out.printf("\nOAuth2 authorization_request returned an error:\n"); System.out.printf("Error: " + error + "\n"); System.out.printf("Error_description: " + error_description + "\n"); System.out.printf("Error_uri: " + error_uri + "\n"); // Update authorization record with error response authorization.setError(error); authorization.setErrorDescription(error_description); authorization.setErrorUri(error_uri); authorization.setUpdated(new GregorianCalendar()); authorization.setStatus("2"); // Set authorization record status // as "Denied" authorization.setState(null); // Clear State as a security // measure authorizationService.merge(authorization); throw new UserDeniedAuthorizationException("Error: " + error_description); } } catch (NoResultException | EmptyResultDataAccessException e) { // We received an invalid /oauth/authorization response // TODO: Log receipt of an invalid /oauth/authorization response return "/home"; } return "redirect:/RetailCustomer/" + currentCustomer(principal).getId() + "/AuthorizationList"; }
From source file:com.vmware.vchs.publicapi.samples.GatewayRuleSample.java
/** * This method is to configure NAT and Firewall Rules to the EdgeGateway * //ww w . j av a2 s. co m * @param networkHref * the href to the network on which nat rules to be applied * @param serviceConfHref * the href to the service configure action of gateway * @return */ private void configureRules(String networkHref, String serviceConfHref) { // NAT Rules NatServiceType natService = new NatServiceType(); // To Enable the service using this flag natService.setIsEnabled(Boolean.TRUE); // Configuring Destination nat NatRuleType dnatRule = new NatRuleType(); // Setting Rule type Destination Nat DNAT dnatRule.setRuleType("DNAT"); dnatRule.setIsEnabled(Boolean.TRUE); GatewayNatRuleType dgatewayNat = new GatewayNatRuleType(); ReferenceType refd = new ReferenceType(); refd.setHref(networkHref); // Network on which nat rules to be applied dgatewayNat.setInterface(refd); // Setting Original IP dgatewayNat.setOriginalIp(options.externalIp); dgatewayNat.setOriginalPort("any"); dgatewayNat.setTranslatedIp(options.internalIp); // To allow all ports and all protocols // dgatewayNat.setTranslatedPort("any"); // dgatewayNat.setProtocol("Any"); // To allow only https use Port 443 and TCP protocol dgatewayNat.setTranslatedPort("any"); dgatewayNat.setProtocol("TCP"); // To allow only ssh use Port 22 and TCP protocol // dgatewayNat.setTranslatedPort("22"); // dgatewayNat.setProtocol("TCP"); // Setting Destination IP dnatRule.setGatewayNatRule(dgatewayNat); natService.getNatRule().add(dnatRule); // Configuring Source nat NatRuleType snatRule = new NatRuleType(); // Setting Rule type Source Nat SNAT snatRule.setRuleType("SNAT"); snatRule.setIsEnabled(Boolean.TRUE); GatewayNatRuleType sgatewayNat = new GatewayNatRuleType(); //ReferenceType refd = new ReferenceType(); //refd.setHref(networkHref); // Network on which nat rules to be applied sgatewayNat.setInterface(refd); // Setting Original IP sgatewayNat.setOriginalIp(options.internalIp); //sgatewayNat.setOriginalPort("any"); sgatewayNat.setTranslatedIp(options.externalIp); // Setting Source IP snatRule.setGatewayNatRule(sgatewayNat); natService.getNatRule().add(snatRule); // Firewall Rules FirewallServiceType firewallService = new FirewallServiceType(); // Enable or disable the service using this flag firewallService.setIsEnabled(Boolean.TRUE); // Default action of the firewall set to drop firewallService.setDefaultAction("drop"); // Flag to enable logging for default action firewallService.setLogDefaultAction(Boolean.FALSE); // Firewall Rule settings FirewallRuleType firewallInRule = new FirewallRuleType(); firewallInRule.setIsEnabled(Boolean.TRUE); firewallInRule.setMatchOnTranslate(Boolean.FALSE); firewallInRule.setDescription("Allow incoming https access"); firewallInRule.setPolicy("allow"); FirewallRuleProtocols firewallProtocol = new FirewallRuleProtocols(); firewallProtocol.setAny(Boolean.TRUE); firewallInRule.setProtocols(firewallProtocol); firewallInRule.setDestinationPortRange("any"); firewallInRule.setDestinationIp(options.externalIp); firewallInRule.setSourcePortRange("Any"); firewallInRule.setSourceIp("external"); firewallInRule.setEnableLogging(Boolean.FALSE); firewallService.getFirewallRule().add(firewallInRule); // To create the HttpPost request Body ObjectFactory objectFactory = new ObjectFactory(); GatewayFeaturesType gatewayFeatures = new GatewayFeaturesType(); JAXBElement<NetworkServiceType> serviceType = objectFactory.createNetworkService(natService); JAXBElement<NetworkServiceType> firewallserviceType = objectFactory.createNetworkService(firewallService); gatewayFeatures.getNetworkService().add(serviceType); gatewayFeatures.getNetworkService().add(firewallserviceType); JAXBContext jaxbContexts = null; try { jaxbContexts = JAXBContext.newInstance(GatewayFeaturesType.class); } catch (JAXBException ex) { ex.printStackTrace(); } OutputStream os = null; JAXBElement<GatewayFeaturesType> gateway_Features = objectFactory .createEdgeGatewayServiceConfiguration(gatewayFeatures); try { javax.xml.bind.Marshaller marshaller = jaxbContexts.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); os = new ByteArrayOutputStream(); // Marshal the JAXB class to XML marshaller.marshal(gateway_Features, os); } catch (JAXBException e) { e.printStackTrace(); } HttpPost httpPost = vcd.post(serviceConfHref, options); ContentType contentType = ContentType.create(SampleConstants.CONTENT_TYPE_EDGE_GATEWAY, "ISO-8859-1"); StringEntity rules = new StringEntity(os.toString(), contentType); httpPost.setEntity(rules); InputStream is = null; // Invoking api to add rules to gateway HttpResponse response = HttpUtils.httpInvoke(httpPost); // Make sure the response code is 202 ACCEPTED if (response.getStatusLine().getStatusCode() == HttpStatus.SC_ACCEPTED) { // System.out.println("ResponseCode : " + response.getStatusLine().getStatusCode()); System.out.println("\nRequest To update Gateway initiated sucessfully"); System.out.print("\nUpdating EdgeGateways to add NAT and Firewall Rules..."); taskStatus(response); } }
From source file:controllers.WorkflowViewController.java
private void mapExperimentalProperties(String id, List<String> fileNames) { Map<String, Object> params = new HashMap<String, Object>(); List<String> codes = new ArrayList<String>(); for (Sample s : datahandler.getOpenBisClient().getSamplesOfProjectBySearchService(id)) codes.add(s.getCode());//from ww w . j a va 2 s.c o m params.put("codes", codes); QueryTableModel res = datahandler.getOpenBisClient().getAggregationService("get-property-tsv", params); Set<String> factorNames = new HashSet<String>(); Map<String, String> fileProps = new HashMap<String, String>(); // XML Parser XMLParser p = new XMLParser(); Set<String> secondaryNames = new HashSet<String>(); for (Serializable[] ss : res.getRows()) { String xml = (String) ss[3]; String code = (String) ss[0]; List<String> matches = getMatchingStrings(fileNames, code); if (!xml.isEmpty() && !matches.isEmpty()) { for (String match : matches) { StringBuilder row = new StringBuilder(); String extID = (String) ss[1];// how to use this if it is preferred over secondary name? String secondaryName = (String) ss[2]; while (secondaryNames.contains(secondaryName)) secondaryName += "1"; secondaryNames.add(secondaryName); row.append(secondaryName); List<Property> properties = new ArrayList<Property>(); try { properties = p.getAllPropertiesFromXML(xml); } catch (JAXBException e) { e.printStackTrace(); } for (Property f : properties) { factorNames.add(f.getLabel()); String val = f.getValue(); if (f.hasUnit()) val += f.getUnit(); row.append("\t" + val); } fileProps.put(match, row.toString()); } } } this.expProps = fileProps; this.expFactors = factorNames; }
From source file:gov.usgs.cida.coastalhazards.rest.data.util.MetadataUtilTest.java
/** * Test of getBoundingBoxFromFgdcMetadataCR method, of class MetadataUtil. *///from w ww . ja v a 2 s. com @Test public void testGetBoundingBoxFromFgdcMetadataCR() throws IOException { System.out.println("testGetBoundingBoxFromFgdcMetadataPAE"); // This method tests the parsing that occurs in: Bbox result = MetadataUtil.getBoundingBoxFromFgdcMetadata(metadata); // file is ~40kb // spdom is the WGS84 bbox, format for the Bbox is "BOX(%f %f, %f %f)" //get the metadata from the test file as a string using this package to locate it ... String packageName = this.getClass().getCanonicalName(); System.out.println("PackageName: " + packageName); //PackageName: gov.usgs.cida.coastalhazards.rest.data.util.MetadataUtilTest // this is where the test resource is located - gov.usgs.cida.coastalhazards.rest.data + /ne_AEmeta.xml String replaced = packageName.replaceAll("[.]", "/"); String[] names = replaced.split("/util/MetadataUtilTest"); String packageNameShort = names[0]; String testFileFullName = packageNameShort + "/" + CRxml; String metadataXml = loadResourceAsString(testFileFullName); InputStream in = new ByteArrayInputStream(metadataXml.getBytes("UTF-8")); Metadata metadata = null; // JAXB will require jaxb-api.jar and jaxb-impl.jar part of java 1.6. Much safer way to interrogate xml and maintain than regex try { //File file = new File(xmlFile); // FYI: can also be done via file rather than inputStream JAXBContext jaxbContext = JAXBContext.newInstance(Metadata.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); metadata = (Metadata) jaxbUnmarshaller.unmarshal(in); } catch (JAXBException e) { e.printStackTrace(); } assertNotNull(metadata); Idinfo idinfo = metadata.getIdinfo(); Spdom spdom = idinfo.getSpdom(); Bounding bounding = spdom.getBounding(); double minx = bounding.getWestbc(); double miny = bounding.getSouthbc(); double maxx = bounding.getEastbc(); double maxy = bounding.getNorthbc(); Bbox result = new Bbox(); result.setBbox(minx, miny, maxx, maxy); System.out.println("Parsed Bbox is: " + result.getBbox()); Bbox expResult = new Bbox(); expResult.setBbox("BOX(-77.830618 35.344738, -66.813170 46.642941)"); assertNotNull(result); assertTrue(expResult.getBbox().startsWith("BOX(-77.830618 35.")); assertTrue(expResult.getBbox().equalsIgnoreCase(result.getBbox())); }
From source file:gov.usgs.cida.coastalhazards.rest.data.util.MetadataUtilTest.java
/** * Test of getBoundingBoxFromFgdcMetadataAE method, of class MetadataUtil. *///from w ww . ja va 2s . c o m @Test public void testGetBoundingBoxFromFgdcMetadataAE() throws IOException { System.out.println("testGetBoundingBoxFromFgdcMetadataAE"); // This method tests the parsing that occurs in: Bbox result = MetadataUtil.getBoundingBoxFromFgdcMetadata(metadata); // file is ~40kb // spdom is the WGS84 bbox, format for the Bbox is "BOX(%f %f, %f %f)" //get the metadata from the test file as a string using this package to locate it ... String packageName = this.getClass().getCanonicalName(); System.out.println("PackageName: " + packageName); //PackageName: gov.usgs.cida.coastalhazards.rest.data.util.MetadataUtilTest // this is where the test resource is located - gov.usgs.cida.coastalhazards.rest.data + /ne_AEmeta.xml String replaced = packageName.replaceAll("[.]", "/"); String[] names = replaced.split("/util/MetadataUtilTest"); String packageNameShort = names[0]; String testFileFullName = packageNameShort + "/" + AExml; String metadataXml = loadResourceAsString(testFileFullName); InputStream in = new ByteArrayInputStream(metadataXml.getBytes("UTF-8")); Metadata metadata = null; // JAXB will require jaxb-api.jar and jaxb-impl.jar part of java 1.6. Much safer way to interrogate xml and maintain than regex try { //File file = new File(xmlFile); // FYI: can also be done via file rather than inputStream JAXBContext jaxbContext = JAXBContext.newInstance(Metadata.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); metadata = (Metadata) jaxbUnmarshaller.unmarshal(in); } catch (JAXBException e) { e.printStackTrace(); } assertNotNull(metadata); Idinfo idinfo = metadata.getIdinfo(); Spdom spdom = idinfo.getSpdom(); Bounding bounding = spdom.getBounding(); double minx = bounding.getWestbc(); double miny = bounding.getSouthbc(); double maxx = bounding.getEastbc(); double maxy = bounding.getNorthbc(); Bbox result = new Bbox(); result.setBbox(minx, miny, maxx, maxy); System.out.println("Parsed Bbox is: " + result.getBbox()); Bbox expResult = new Bbox(); expResult.setBbox("BOX(-77.830618 35.344738, -66.813170 46.642941)"); assertNotNull(result); assertTrue(expResult.getBbox().startsWith("BOX(-77.830618 35.")); assertTrue(expResult.getBbox().equalsIgnoreCase(result.getBbox())); }
From source file:gov.usgs.cida.coastalhazards.rest.data.util.MetadataUtilTest.java
/** * Test of getCrsFromFgdcMetadata method, of class MetadataUtil. *///from www. j a v a2s .co m @Test public void testGetCrsFromFgdcMetadata() throws IOException { System.out.println("getCrsFromFgdcMetadata"); //spref is used to determine hte SRS System.out.println("testGetBoundingBoxFromFgdcMetadataAE"); //get the metadata from the test file as a string using this package to locate it ... String packageName = this.getClass().getCanonicalName(); System.out.println("PackageName: " + packageName); //PackageName: gov.usgs.cida.coastalhazards.rest.data.util.MetadataUtilTest // this is where the test resource is located - gov.usgs.cida.coastalhazards.rest.data + /ne_AEmeta.xml String replaced = packageName.replaceAll("[.]", "/"); String[] names = replaced.split("/util/MetadataUtilTest"); String packageNameShort = names[0]; String testFileFullName = packageNameShort + "/" + CRxml; String metadataXml = loadResourceAsString(testFileFullName); InputStream in = new ByteArrayInputStream(metadataXml.getBytes("UTF-8")); Metadata metadata = null; // JAXB will require jaxb-api.jar and jaxb-impl.jar part of java 1.6. Much safer way to interrogate xml and maintain than regex try { //File file = new File(xmlFile); // FYI: can also be done via file rather than inputStream JAXBContext jaxbContext = JAXBContext.newInstance(Metadata.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); metadata = (Metadata) jaxbUnmarshaller.unmarshal(in); } catch (JAXBException e) { e.printStackTrace(); } assertNotNull(metadata); //Spref spref = metadata.getSpref(); Horizsys horizsys = metadata.getSpref().getHorizsys(); assertNotNull(horizsys); String expEllips = "GRS 1980"; String expHorizdn = "North American Datum 1983"; double expDenflat = 298.257222101; double expSemiaxis = 6378137.0; // part I String ellips = horizsys.getGeodetic().getEllips(); String horizdn = horizsys.getGeodetic().getHorizdn(); double denflat = horizsys.getGeodetic().getDenflat(); double semiaxis = horizsys.getGeodetic().getSemiaxis(); assertTrue(expEllips.equalsIgnoreCase(ellips)); assertTrue(expHorizdn.equalsIgnoreCase(horizdn)); assertEquals(expDenflat, denflat, expDenflat - denflat); assertEquals(expSemiaxis, semiaxis, expSemiaxis - semiaxis); // part II String mapprojn = horizsys.getPlanar().getMapproj().getMapprojn(); double feast = horizsys.getPlanar().getMapproj().getMapprojp().getFeast(); double fnorth = horizsys.getPlanar().getMapproj().getMapprojp().getFnorth(); double latprjo = horizsys.getPlanar().getMapproj().getMapprojp().getLatprjo(); double longcm = horizsys.getPlanar().getMapproj().getMapprojp().getLongcm(); double stdparll = horizsys.getPlanar().getMapproj().getMapprojp().getStdparll(); String expMapprojn = "Albers Conical Equal Area"; double expFeast = 0.0; double expFnorth = 0.0; double expLatprjo = 23.0; double expLongcm = -96.0; double expStdparll = 45.5; // the second of the two children assertTrue(expMapprojn.equalsIgnoreCase(mapprojn)); assertEquals(expFeast, feast, expFeast - feast); assertEquals(expFnorth, fnorth, expFnorth - fnorth); assertEquals(expLatprjo, latprjo, expLatprjo - latprjo); assertEquals(expLongcm, longcm, expLongcm - longcm); assertEquals(expStdparll, stdparll, expStdparll - stdparll); //CoordinateReferenceSystem expResult = null; //CoordinateReferenceSystem result = MetadataUtil.getCrsFromFgdcMetadata(metadata); //assertEquals(expResult, result); }
From source file:it.cnr.icar.eric.client.ui.common.UIUtility.java
public Object convertToRimBinding(Object uiBindingObj) throws JAXRException { Object rimBindingObj = null;/*from www .ja va 2 s . c o m*/ StringWriter sw = new StringWriter(); try { Marshaller marshaller = uiJaxbContext.createMarshaller(); if (uiBindingObj instanceof it.cnr.icar.eric.client.ui.common.conf.bindings.InternationalStringType) { it.cnr.icar.eric.client.ui.common.conf.bindings.ObjectFactory oF = new it.cnr.icar.eric.client.ui.common.conf.bindings.ObjectFactory(); marshaller.marshal(oF.createInternationalString((InternationalStringType) uiBindingObj), sw); Unmarshaller unmarshaller = BindingUtility.getInstance().getJAXBContext().createUnmarshaller(); rimBindingObj = JAXBIntrospector .getValue(unmarshaller.unmarshal(new StreamSource(new StringReader(sw.toString())))); } else { marshaller.marshal(uiBindingObj, sw); Unmarshaller unmarshaller = BindingUtility.getInstance().getJAXBContext().createUnmarshaller(); //unmarshaller.setValidating(true); unmarshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { boolean keepOn = false; return keepOn; } }); rimBindingObj = unmarshaller.unmarshal(new StreamSource(new StringReader(sw.toString()))); } } catch (JAXBException e) { e.printStackTrace(); throw new JAXRException(e); } return rimBindingObj; }
From source file:controllers.WorkflowViewController.java
public String submitAndRegisterWf(String type, String id, Workflow workflow, List<DatasetBean> selectedDatasets) throws ConnectException, IllegalArgumentException, SubmitFailedException { SpaceAndProjectCodes spaceandproject = getSpaceAndProjects(type, id); String spaceCode = spaceandproject.space; String projectCode = spaceandproject.project; ParameterSet params = workflow.getParameters(); List<Property> factors = new ArrayList<Property>(); XMLParser xmlParser = new XMLParser(); for (Map.Entry<String, Parameter> entry : workflow.getData().getData().entrySet()) { String key = entry.getKey(); Parameter value = entry.getValue(); if (key.contains("input")) { List<String> files = (List<String>) value.getValue(); List<String> inputFiles = new ArrayList<String>(); for (String f : files) { String[] splitted = f.split("/"); String fileName = splitted[splitted.length - 1]; inputFiles.add(fileName); }// ww w . j a v a2 s. c o m System.out.println(inputFiles.toString()); String concat = String.join("; ", inputFiles); System.out.println(concat); Property newProperty = new Property("input_files", concat, PropertyType.Property); factors.add(newProperty); } else { Property newProperty = new Property("database", value.getValue().toString().replace("/lustre_cfc/qbic/reference_genomes/", ""), PropertyType.Property); factors.add(newProperty); } } for (String p : params.getParamNames()) { Parameter par = params.getParam(p); String[] splitted = par.getTitle().split("\\."); String parName = splitted[splitted.length - 1].replace(" ", "_").toLowerCase(); Property newProperty = new Property(parName, par.getValue().toString(), PropertyType.Property); factors.add(newProperty); } String qProperties = ""; try { qProperties = xmlParser.toString(xmlParser.createXMLFromProperties(factors)); System.out.println(qProperties); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } String experimentCode = registerWFExperiment(spaceCode, projectCode, workflow.getExperimentType(), workflow.getID(), workflow.getVersion(), user, qProperties); List<String> parents = getConnectedSamples(selectedDatasets); String sampleType = workflow.getSampleType(); String sampleCode = registerWFSample(spaceCode, projectCode, experimentCode, sampleType, parents, selectedDatasets); String openbisId = String.format("%s-%s-%s-%s", spaceCode, projectCode, experimentCode, sampleCode); LOGGER.info( "User: " + user + " is submitting workflow " + workflow.getID() + " openbis id is:" + openbisId); String submit_id = submitter.submit(workflow, openbisId, user); LOGGER.info("Workflow has guse id: " + submit_id); setWorkflowID(spaceCode, projectCode, experimentCode, submit_id); return openbisId; }
From source file:eu.betaas.service.securitymanager.service.impl.AuthorizationService.java
/** * Check the condition specified in the token with the condition saved in the * GW (concerning the specific thingService) * @param ct: extracted Condition from the token * @param req: RequestCtx (required by XACML API) * @return boolean true or false (true if the condition matches) */// w w w.j a v a 2 s.co m private boolean checkCondition(ConditionType ct, RequestCtx req) { boolean access = false; JAXBElement<ConditionType> jaxbCT = of.createCondition(ct); JAXBContext jc = null; try { jc = JAXBContext.newInstance(ConditionType.class); Marshaller mar = jc.createMarshaller(); // create DOM Document DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); mar.marshal(jaxbCT, doc); // convert ConditionType to XML Node (org.w3c.dom.Node) DOMResult res = new DOMResult(); res.setNode(doc.getDocumentElement()); Node conditionNode = res.getNode(); // prepare for the Condition PolicyMetaData metadata = new PolicyMetaData(2, 0); VariableManager vm = new VariableManager(new HashMap(), metadata); Condition condition = Condition.getInstance(conditionNode, metadata, vm); // evaluate condition -- first convert RequestCtx into EvaluationCtx EvaluationCtx context = new BasicEvaluationCtx(req); EvaluationResult result = condition.evaluate(context); BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue()); // get the condition evaluation result in boolean access = bool.getValue(); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParsingException e) { // TODO Auto-generated catch block e.printStackTrace(); } log.info("Checking Condition in the Access Right return: " + access); return access; }
From source file:edu.duke.cabig.c3pr.dao.StudyDao.java
public String generateHQL(List<AdvancedSearchCriteriaParameter> searchParameters) { InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream("study-advanced-search.xml"); Unmarshaller unmarshaller;//from w ww . ja v a 2s . co m QueryBuilder queryBuilder = new QueryBuilder(); try { unmarshaller = JAXBContext.newInstance("com.semanticbits.querybuilder").createUnmarshaller(); queryBuilder = (QueryBuilder) unmarshaller.unmarshal(inputStream); } catch (JAXBException e) { e.printStackTrace(); } TargetObject targetObject = (TargetObject) queryBuilder.getTargetObject().get(0); try { return QueryGenerator.generateHQL(targetObject, searchParameters, true); } catch (Exception e) { e.printStackTrace(); } return ""; }