List of usage examples for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT
String JAXB_FORMATTED_OUTPUT
To view the source code for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT.
Click Source Link
From source file:labr_client.xml.ObjToXML.java
public static void saveKmehrRequest(LabrRequest request) { String date = String.format("%1$tY%1$tm%1$td", new Date()); String time = String.format("%1$tH%1$tM%1$tS", new Date()); try {// w w w . j a v a 2 s . co m KmehrMessage kmehrMessage = new KmehrMessage(); JAXBContext context = JAXBContext.newInstance(KmehrMessage.class); Marshaller m = context.createMarshaller(); //for pretty-print XML in JAXB m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //----------HEADER-------------------------- kmehrMessage.header.id.setS("ID-KMEHR"); kmehrMessage.header.id.setSV("1.15"); kmehrMessage.header.id.setValue(request.attributes.getTitle()); kmehrMessage.header.setDate(date); kmehrMessage.header.setTime(time); kmehrMessage.header.standard.cd.setS("CD-STANDARD"); kmehrMessage.header.standard.cd.setSV("1.15"); kmehrMessage.header.standard.cd.setValue("20150901"); //----------HEADER-ZENDER------------------------- kmehrMessage.header.sender.hcparty.id.setS("ID-HCPARTY"); kmehrMessage.header.sender.hcparty.id.setSV("1.15"); kmehrMessage.header.sender.hcparty.id.setValue(request.attributes.getSenderID()); kmehrMessage.header.sender.hcparty.cd.setS("CD-HCPARTY"); kmehrMessage.header.sender.hcparty.cd.setSV("1.15"); kmehrMessage.header.sender.hcparty.cd.setValue("persphysician"); kmehrMessage.header.sender.hcparty.setFamilyname("Pieters"); kmehrMessage.header.sender.hcparty.setFirstname("Piet"); //----------HEADER-ONTVANGER(S)-------------------- Hcparty receiver = new Hcparty(); receiver.id.setS("ID-HCPARTY"); receiver.id.setSV("1.15"); receiver.id.setValue(request.attributes.receiver1ID); receiver.cd.setS("CD-HCPARTY"); receiver.cd.setSV("1.15"); receiver.cd.setValue("persphysician"); receiver.setFamilyname("Pieters"); receiver.setFirstname("Piet"); kmehrMessage.header.receiver.getHcparty().add(receiver); //----------FOLDER-PATIENT------------------------- kmehrMessage.folder.id.setS("ID-HCPARTY"); kmehrMessage.folder.id.setSV("1.15"); kmehrMessage.folder.id.setValue(request.patient.nationalNumber.getValue()); kmehrMessage.folder.patient.setFamilyname(request.patient.name.getValue()); kmehrMessage.folder.patient.setFirstname(request.patient.firstName.getValue()); kmehrMessage.folder.patient.birthdate.setDate(request.patient.birthDate.getValue()); kmehrMessage.folder.patient.sex.cd.setS("CD-SEX"); kmehrMessage.folder.patient.sex.cd.setSV("1.15"); kmehrMessage.folder.patient.sex.cd.setValue("M"); kmehrMessage.folder.patient.address.cd.setS("CD-ADDRESS"); kmehrMessage.folder.patient.address.cd.setSV("1.15"); kmehrMessage.folder.patient.address.country.cd.setS("CD-COUNTRY"); kmehrMessage.folder.patient.address.country.cd.setSV("1.15"); kmehrMessage.folder.patient.address.country.cd.setValue(request.patient.country.getValue()); kmehrMessage.folder.patient.address.setCity(request.patient.city.getValue()); kmehrMessage.folder.patient.address.setStreetandnumber(request.patient.straatAndNumber.getValue()); kmehrMessage.folder.patient.address.setZip(request.patient.zip.getValue()); Transaction t = new Transaction(); t.id.setS("ID-KMEHR"); t.id.setSV("1.15"); t.id.setValue("1"); t.cd.setS("CD-TRANSACTION"); t.cd.setSV("1.15"); t.cd.setValue("request"); t.setDate(date); t.setTime(time); t.author.hcparty.id.setS("ID-HCPARTY"); t.author.hcparty.id.setSV("1.15"); t.author.hcparty.id.setValue(request.attributes.getSenderID()); t.author.hcparty.cd.setS("CD-HCPARTY"); t.author.hcparty.cd.setSV("1.15"); t.author.hcparty.cd.setValue("persphysician"); t.author.hcparty.setFamilyname("Pieters"); t.author.hcparty.setFirstname("Piet"); Item i = new Item(); i.id.setS("ID-KMEHR"); i.id.setSV("1.15"); i.id.setValue("1"); i.cd.setS("CD-ITEM"); i.cd.setSV("1.15"); i.cd.setValue("lab"); List<LabrXMLRequest> requests = request.requests.getRequest(); for (LabrXMLRequest req : requests) { if (req.isSelected() & req.getLoinc() != null) { Cd cd = new Cd(); cd.setS("CD-LAB"); cd.setSV("1.15"); cd.setValue(req.getLoinc()); i.content.getCd().add(cd); } } t.getItem().add(i); kmehrMessage.folder.getTransaction().add(t); kmehrMessage.setXmlns("http://www.ehealth.fgov.be/standards/kmehr/schema/v1"); //START------ZOEK DE PATIENT OP EN BEWAAR AANVRAAG IN DATABASE------------------------- File KmehrRequest = new File("data/tmp/" + date + time + ".xml"); m.marshal(kmehrMessage, KmehrRequest); List<String[]> patientID = PublicVars.getQueries().selectPatient(request.patient.firstName.getValue(), request.patient.name.getValue(), request.patient.birthDate.getValue()); if (patientID.size() == 0) { PublicVars.getQueries().insertPatient(request); patientID = PublicVars.getQueries().selectPatient(request.patient.firstName.getValue(), request.patient.name.getValue(), request.patient.birthDate.getValue()); PublicVars.getQueries().insertLabRequest(marshallRequest(request), FileUtils.readFileToString(KmehrRequest), Integer.parseInt(patientID.get(0)[0]), Integer.parseInt(PublicVars.getUserData()[1]), kmehrMessage.header.id.getValue()); } else { PublicVars.getQueries().insertLabRequest(marshallRequest(request), FileUtils.readFileToString(KmehrRequest), Integer.parseInt(patientID.get(0)[0]), Integer.parseInt(PublicVars.getUserData()[1]), kmehrMessage.header.id.getValue()); } //EIND--------------------------------------------------------------------------------- } catch (JAXBException e) { e.printStackTrace(); } catch (IOException ex) { Logger.getLogger(ObjToXML.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
/** * @param classes Generates all testcases for all the rest-full services found in the classes discovered *///w w w . j ava 2s . c o m @SuppressWarnings({ "rawtypes", "unchecked" }) private void generateRestTestCases(List<Class> classes) { try { Map<String, Integer> classTypes = new HashMap<String, Integer>(); for (Class claz : classes) { classTypes.put(claz.getSimpleName(), 0); Annotation theClassPath = claz.getAnnotation(Path.class); if (theClassPath == null) theClassPath = claz.getAnnotation(RequestMapping.class); if (theClassPath != null) { List<TestCase> tcases = new ArrayList<TestCase>(); Method[] methods = claz.getMethods(); for (Method method : methods) { Annotation theMethodPath = method.getAnnotation(Path.class); if (theMethodPath == null) theMethodPath = method.getAnnotation(RequestMapping.class); if (theMethodPath != null) { TestCase tcase = new TestCase(); String completeServicePath = null; String httpMethod = ""; String consumes = "text/plain"; if (theClassPath instanceof Path && theMethodPath instanceof Path) { Path cpath = (Path) theClassPath; Path mpath = (Path) theMethodPath; completeServicePath = cpath.value() + mpath.value(); } else if (theClassPath instanceof RequestMapping && theMethodPath instanceof RequestMapping) { RequestMapping cpath = (RequestMapping) theClassPath; RequestMapping mpath = (RequestMapping) theMethodPath; completeServicePath = cpath.value()[0] + mpath.value()[0]; httpMethod = mpath.method()[0].name(); consumes = mpath.consumes()[0]; } else { throw new Exception( "Invalid Annotation found on the Service class - " + claz.getSimpleName()); } if (completeServicePath != null && completeServicePath.charAt(0) == '/') { completeServicePath = completeServicePath.substring(1); } String url = getUrl(completeServicePath); String completeServiceSubmitPath = url; Type[] argTypes = method.getGenericParameterTypes(); Annotation[][] argAnot = method.getParameterAnnotations(); boolean mayBemultipartContent = false; if (isDebugEnabled()) getLog().info( "Started looking at " + claz.getSimpleName() + " " + method.getName()); ViewField contentvf = null; Map<String, String> params = new HashMap<String, String>(); Map<String, String> hparams = new HashMap<String, String>(); for (int i = 0; i < argTypes.length; i++) { Annotation[] annotations = getRestArgAnnotation(argAnot[i]); if (annotations[0] != null) { String formpnm = null; if (annotations[0] instanceof FormParam) { formpnm = ((FormParam) annotations[0]).value(); if (annotations[1] != null) params.put(formpnm, ((DefaultValue) annotations[1]).value()); else params.put(formpnm, String.valueOf(getPrimitiveValue(argTypes[i]))); continue; } if (annotations[0] instanceof RequestParam) { if (completeServiceSubmitPath.indexOf("?") == -1) completeServiceSubmitPath += "?"; if (completeServiceSubmitPath .charAt(completeServiceSubmitPath.length() - 1) != '&') completeServiceSubmitPath += "&"; if (((RequestParam) annotations[0]).defaultValue() != null) completeServiceSubmitPath += ((RequestParam) annotations[0]).value() + "={" + ((RequestParam) annotations[0]).defaultValue() + "}&"; else completeServiceSubmitPath += ((RequestParam) annotations[0]).value() + "={" + ((RequestParam) annotations[0]).value() + "}&"; continue; } if (annotations[0] instanceof QueryParam) { if (completeServiceSubmitPath.indexOf("?") == -1) completeServiceSubmitPath += "?"; if (completeServiceSubmitPath .charAt(completeServiceSubmitPath.length() - 1) != '&') completeServiceSubmitPath += "&"; if (annotations[1] != null) completeServiceSubmitPath += ((QueryParam) annotations[0]).value() + "={" + ((DefaultValue) annotations[1]).value() + "}&"; else completeServiceSubmitPath += ((QueryParam) annotations[0]).value() + "={" + ((QueryParam) annotations[0]).value() + "}&"; continue; } if (annotations[0] instanceof HeaderParam) { formpnm = ((HeaderParam) annotations[0]).value(); if (annotations[1] != null) hparams.put(formpnm, ((DefaultValue) annotations[1]).value()); else hparams.put(formpnm, String.valueOf(getPrimitiveValue(argTypes[i]))); continue; } } else { ViewField vf = getViewField(argTypes[i]); if (vf != null) { contentvf = vf; if (isDebugEnabled()) getLog().info("Done looking at " + claz.getSimpleName() + " " + method.getName()); break; } else { mayBemultipartContent = true; } } } classTypes.put(claz.getSimpleName(), classTypes.get(claz.getSimpleName()) + 1); Annotation hm = method.getAnnotation(POST.class); if (hm != null) { httpMethod = "POST"; } else { hm = method.getAnnotation(GET.class); if (hm != null) { httpMethod = "GET"; } else { hm = method.getAnnotation(PUT.class); if (hm != null) { httpMethod = "PUT"; } else { hm = method.getAnnotation(DELETE.class); if (hm != null) { httpMethod = "DELETE"; } } } } Annotation annot = method.getAnnotation(Consumes.class); if (annot != null) { consumes = ((Consumes) annot).value()[0]; } String produces = null; if ("JSON".equalsIgnoreCase(getOutDataType())) { produces = MediaType.APPLICATION_JSON; } else if ("XML".equalsIgnoreCase(getOutDataType())) { produces = MediaType.APPLICATION_XML; } else { produces = MediaType.TEXT_PLAIN; } annot = method.getAnnotation(Produces.class); if (annot != null) { produces = ((Produces) annot).value()[0]; } String content = ""; try { if (!params.isEmpty() || consumes.equals(MediaType.APPLICATION_FORM_URLENCODED)) { for (Map.Entry<String, String> entry : params.entrySet()) { content += entry.getKey() + "=" + entry.getValue() + "&"; } consumes = MediaType.APPLICATION_FORM_URLENCODED; } else if (contentvf != null && contentvf.getValue() != null && contentvf.getValue() instanceof String) { content = (String) contentvf.getValue(); } else if (("JSON".equalsIgnoreCase(getInDataType()) || consumes.equals(MediaType.APPLICATION_JSON)) && contentvf != null && contentvf.getValue() != null) { content = new ObjectMapper().writerWithDefaultPrettyPrinter() .writeValueAsString(contentvf.getValue()); consumes = MediaType.APPLICATION_JSON; } else if (("XML".equalsIgnoreCase(getInDataType()) || consumes.equals(MediaType.APPLICATION_XML)) && contentvf != null && contentvf.getValue() != null) { JAXBContext context = JAXBContext.newInstance(contentvf.getValue().getClass()); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter writer = new StringWriter(); m.marshal(contentvf.getValue(), writer); content = writer.toString(); consumes = MediaType.APPLICATION_XML; } else if ((httpMethod.equals("POST") || httpMethod.equals("PUT")) && mayBemultipartContent) { consumes = MediaType.MULTIPART_FORM_DATA; } else if (httpMethod.equals("GET") || httpMethod.equals("DELETE")) { consumes = ""; } } catch (Exception e) { getLog().error(e); } if (consumes != null && !consumes.trim().isEmpty()) { hparams.put(HttpHeaders.CONTENT_TYPE, consumes); } completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("\\?&", "?"); completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("&&", "&"); completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("/\\?", "?"); completeServiceSubmitPath = completeServiceSubmitPath.trim(); if (completeServiceSubmitPath.charAt(completeServiceSubmitPath.length() - 1) == '&') { completeServiceSubmitPath = completeServiceSubmitPath.substring(0, completeServiceSubmitPath.length() - 1); } tcase.setUrl(completeServiceSubmitPath); tcase.setMethod(httpMethod); tcase.setContent(content); tcase.setName(claz.getName() + "." + method.getName()); tcase.setDescription(tcase.getName()); tcase.setDetailedLog(false); tcase.setSkipTest(false); tcase.setSecure(isOverrideSecure()); tcase.setSoapBase(false); tcase.setExpectedResCode(200); tcase.setExpectedResContentType(produces); if (hparams.size() > 0) tcase.setHeaders(hparams); if (tcase.getNumberOfExecutions() == null) tcase.setNumberOfExecutions(1); if (tcase.getExpectedNodes().size() == 0) tcase.setExpectedNodes(null); if (tcase.getWorkflowContextParameterMap().size() == 0) tcase.setWorkflowContextParameterMap(null); if (tcase.getSoapParameterValues().size() == 0) tcase.setSoapParameterValues(null); if (tcase.getRepeatScenarios().size() == 0) tcase.setRepeatScenarios(null); if (tcase.getMultipartContent().size() == 0) tcase.setMultipartContent(null); tcases.add(tcase); } } if (!tcases.isEmpty()) { if ("json".equalsIgnoreCase(getTestCaseFormat())) { String postManJson = new ObjectMapper().writeValueAsString(tcases); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.json"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(postManJson); bw.close(); } else if ("csv".equalsIgnoreCase(getTestCaseFormat())) { StringBuilder build = new StringBuilder(); for (TestCase testCase : tcases) { build.append(testCase.toCSV()); build.append(SystemUtils.LINE_SEPARATOR); } String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.csv"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(build.toString()); bw.close(); } else { XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new GatfPrettyPrintWriter(out, TestCase.CDATA_NODES); } }); xstream.processAnnotations(new Class[] { TestCase.class }); xstream.alias("TestCases", List.class); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.xml"; xstream.toXML(tcases, new FileOutputStream(file)); } if (getPostmanCollectionVersion() > 0) { PostmanCollection postmanCollection = new PostmanCollection(); postmanCollection.setName(claz.getSimpleName()); postmanCollection.setDescription(postmanCollection.getName()); for (TestCase testCase : tcases) { postmanCollection.addTestCase(testCase, getPostmanCollectionVersion()); } String postManJson = new ObjectMapper().writeValueAsString(postmanCollection); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_postman.json"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(postManJson); bw.close(); } } } } } catch (Exception e) { getLog().error(e); } }
From source file:com.fujitsu.dc.test.utils.DavResourceUtils.java
/** * BoxACL?./* ww w. j a v a2s . c om*/ * <p> * * <pre> * Acl acl = new Acl(); * acl.getAce().add(DavResourceUtils.createAce(false, roleRead, "read")); * acl.getAce().add(DavResourceUtils.createAce(false, roleWrite, "write")); * acl.setXmlbase(String.format("%s/%s/__role/%s/", * UrlUtils.getBaseUrl(), CELL_NAME, Box.DEFAULT_BOX_NAME)); * DavResourceUtils.setAcl(MASTER_TOKEN, CELL_NAME, BOX_NAME, COL_NAME, acl, HttpStatus.SC_OK); * </pre> * </p> * @param token * @param cell ?? * @param box ?? * @param col ?? * @param acl ?ACL * @param code ? * @return ? * @throws JAXBException ACL???????? */ public static TResponse setAcl(String token, String cell, String box, String col, Acl acl, int code) throws JAXBException { StringWriter writer = new StringWriter(); JAXBContext context = JAXBContext.newInstance(Acl.class); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(acl, writer); return Http.request("box/acl-setting-none-body.txt").with("cell", cell).with("box", box) .with("colname", col).with("token", token).with("body", writer.toString()).returns().debug() .statusCode(code); }
From source file:com.axelor.controller.ConnectionToPrestashop.java
@SuppressWarnings("null") @Transactional//from w ww . j a v a 2 s.c o m public void insertGroup(int groupId) { com.axelor.pojo.CustomerGroup pojoCustomerGroup = new com.axelor.pojo.CustomerGroup(); pojoCustomerGroup.setId(0); pojoCustomerGroup.setLanguage("NAME"); pojoCustomerGroup.setDescription("DESCRIPTION"); try { System.out.println("GROUPID :: " + groupId); URL url = new URL("http://localhost/client-lib/crud/action.php?resource=groups&action=retrieve&id=" + groupId + "&Akey=" + apiKey); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); File f = new File("//home//axelor//Desktop//example//k.xml"); connection.setRequestMethod("POST"); JAXBContext jaxbContext = JAXBContext.newInstance(com.axelor.pojo.CustomerGroup.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); connection.setDoOutput(true); connection.setDoInput(true); OutputStream outputStream = connection.getOutputStream(); jaxbMarshaller.marshal(pojoCustomerGroup, outputStream); connection.connect(); InputStream inputStream = connection.getInputStream(); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); pojoCustomerGroup = (com.axelor.pojo.CustomerGroup) jaxbUnmarshaller .unmarshal(new UnmarshalInputStream(connection.getInputStream())); jaxbMarshaller.marshal(pojoCustomerGroup, f); PrestashopCustomerGroup prestashopCustomerGroup = new PrestashopCustomerGroup(); // add this customer into ERP prestashopCustomerGroup.setId_group(groupId); prestashopCustomerGroup.setName(pojoCustomerGroup.getLanguage()); prestashopCustomerGroup.setDescription(pojoCustomerGroup.getDescription()); prestashopCustomerGroup.save(); } catch (Exception e) { System.out.println(e); } }
From source file:de.tu_dortmund.ub.api.paia.auth.PaiaAuthEndpoint.java
/** * PAIAauth services: Prfe jeweils die scopes und liefere die Daten *///w w w . ja v a2s.c o m private void provideService(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String service, String access_token, String requestBody, String format, String language, String redirect_url) throws IOException { ObjectMapper mapper = new ObjectMapper(); switch (service) { case "login": { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); // if access_token not equals "" >> delete token + new login if (!access_token.equals("")) { // AuthorizationInterface.revokeToken() try { boolean isRevoked = authorizationInterface.revokeToken(access_token); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } // delete cookie Cookie cookie = new Cookie("PaiaService", null); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(0); cookie.setPath("/"); httpServletResponse.addCookie(cookie); // cleanup variable access_token = ""; } // analyse on request data LoginRequest loginRequest = null; try { loginRequest = mapper.readValue(requestBody, LoginRequest.class); if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { redirect_url = httpServletRequest.getParameter("redirect_url"); } } catch (Exception e) { if (requestBody != null && !requestBody.equals("")) { String[] params = requestBody.split("&"); if (params.length > 1) { loginRequest = new LoginRequest(); for (String param : params) { if (param.startsWith("grant_type")) { loginRequest.setGrant_type(param.split("=")[1]); } else if (param.startsWith("username")) { loginRequest.setUsername(param.split("=")[1]); } else if (param.startsWith("password")) { loginRequest.setPassword(param.split("=")[1]); } else if (param.startsWith("scope")) { loginRequest.setScope(param.split("=")[1]); } else if (param.startsWith("format")) { format = param.split("=")[1]; this.logger.info("format = " + format); } else if (param.startsWith("redirect_url")) { redirect_url = URLDecoder.decode(param.split("=")[1], "UTF-8"); this.logger.info("redirect_url = " + redirect_url); } else { // Tu nix } } } } else if (httpServletRequest.getParameter("grant_type") != null && !httpServletRequest.getParameter("grant_type").equals("") && httpServletRequest.getParameter("username") != null && !httpServletRequest.getParameter("username").equals("") && httpServletRequest.getParameter("password") != null && !httpServletRequest.getParameter("password").equals("")) { loginRequest = new LoginRequest(); loginRequest.setGrant_type(httpServletRequest.getParameter("grant_type")); loginRequest.setUsername(httpServletRequest.getParameter("username")); loginRequest.setPassword(httpServletRequest.getParameter("password")); if (httpServletRequest.getParameter("scope") != null && !httpServletRequest.getParameter("scope").equals("")) { loginRequest.setScope(httpServletRequest.getParameter("scope")); } if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { redirect_url = httpServletRequest.getParameter("redirect_url"); } } else { loginRequest = null; } } // do login if (loginRequest != null && loginRequest.getUsername() != null && loginRequest.getPassword() != null && loginRequest.getGrant_type() != null && loginRequest.getGrant_type().equals("password")) { String scope = "read_patron read_fees read_items write_items"; // TODO config-properties if (loginRequest.getScope() != null && !loginRequest.getScope().equals("")) { scope = loginRequest.getScope(); } // AuthorizationInterface.getToken() String responseJson = ""; try { responseJson = authorizationInterface.getToken(scope, loginRequest.getUsername(), loginRequest.getPassword()); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } if (!responseJson.equals("")) { LoginResponse loginResponse = mapper.readValue(responseJson, LoginResponse.class); // anpassen des loginResponse loginResponse.setRefresh_token(null); loginResponse.setRefresh_expires_in(null); loginResponse.setPatron(loginRequest.getUsername()); httpServletResponse.setHeader("Access-Control-Allow-Origin", this.config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", this.config.getProperty("Cache-Control")); httpServletResponse.setStatus(HttpServletResponse.SC_OK); // add cookie StringWriter stringWriter = new StringWriter(); mapper.writeValue(stringWriter, loginResponse); Cookie cookie = new Cookie("PaiaService", URLEncoder.encode(stringWriter.toString(), "UTF-8")); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(-1); cookie.setPath("/"); httpServletResponse.addCookie(cookie); // extent redirect_url this.logger.info("redirect_url: " + redirect_url); if (redirect_url.startsWith(this.config.getProperty("service.base_url") + "/core")) { if (redirect_url.endsWith("core/")) { redirect_url += loginResponse.getPatron(); } else if (redirect_url.endsWith("core")) { redirect_url += "/" + loginResponse.getPatron(); } else if (redirect_url.contains("/patronid/")) { redirect_url = redirect_url.replaceAll("/patronid/", "/" + loginResponse.getPatron() + "/"); } else { // nix } } this.logger.info("redirect_url: " + redirect_url); // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(LoginResponse.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(loginResponse, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), loginResponse); } // html >> redirect if (format.equals("html")) { // if QueryString contains redirect_url and value of it contains /paia/core/ >> expand URL with username if (redirect_url.contains("/paia/core/")) { // TODO redirect_url += loginResponse.getPatron(); } this.logger.info("redirect_url = " + redirect_url); httpServletResponse.sendRedirect(redirect_url); } } else { // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2")); requestError.setCode(HttpServletResponse.SC_FORBIDDEN); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } // else Baue HTML-Seite mit login-Formular mittels XSLT else { httpServletResponse.setHeader("WWW-Authentificate", "Bearer"); httpServletResponse.setHeader("WWW-Authentificate", "Bearer realm=\"PAIA auth\""); httpServletResponse.setContentType("application/json"); httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control")); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2")); requestError.setCode(HttpServletResponse.SC_FORBIDDEN); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_FORBIDDEN) + ".2.uri")); if (format.equals("html")) { if (Lookup.lookupAll(ObjectToHtmlTransformation.class).size() > 0) { try { ObjectToHtmlTransformation htmlTransformation = Lookup .lookup(ObjectToHtmlTransformation.class); // init transformator htmlTransformation.init(this.config); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("lang", language); parameters.put("redirect_url", redirect_url); //String provider = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/" + service; String provider = this.config.getProperty("service.base_url") + this.config.getProperty("service.endpoint.auth") + "/" + service; parameters.put("formURL", provider); httpServletResponse.setContentType("text/html;charset=UTF-8"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); httpServletResponse.getWriter() .println(htmlTransformation.transform(new Document(), parameters)); } catch (TransformationException e) { e.printStackTrace(); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering a HTML message."); } } else { this.logger.error("ObjectToHtmlTransformation not configured! Switch to JSON."); format = "json"; } } // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(RequestError.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(requestError, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), requestError); } } } else { this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "logout": { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); if (!access_token.equals("")) { // AuthorizationInterface.revokeToken() try { boolean isRevoked = authorizationInterface.revokeToken(access_token); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } } httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control")); httpServletResponse.setStatus(HttpServletResponse.SC_OK); // delete cookie Cookie cookie = new Cookie("PaiaService", null); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(0); cookie.setPath("/"); httpServletResponse.addCookie(cookie); // html >> redirect if (format.equals("html")) { if (httpServletRequest.getParameter("redirect_url") != null && !httpServletRequest.getParameter("redirect_url").equals("")) { redirect_url = httpServletRequest.getParameter("redirect_url"); } else { redirect_url = this.config.getProperty("service.auth.logout.redirect.default"); } httpServletResponse.sendRedirect(redirect_url); } if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); httpServletResponse.getWriter().println("{\"logged out\":\"true\"}"); } if (format.equals("xml")) { httpServletResponse.setContentType("application/xml;charset=UTF-8"); httpServletResponse.getWriter().println( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><logout status=\"true\" />"); } } else { this.logger.error(HttpServletResponse.SC_SERVICE_UNAVAILABLE + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE))); requestError.setCode(HttpServletResponse.SC_SERVICE_UNAVAILABLE); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_SERVICE_UNAVAILABLE) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } case "change": { // build ChangeRequest object ChangeRequest changeRequest = mapper.readValue(requestBody, ChangeRequest.class); // check token ... boolean isAuthorized = false; if (access_token != null && !access_token.equals("")) { if (Lookup.lookupAll(AuthorizationInterface.class).size() > 0) { AuthorizationInterface authorizationInterface = Lookup.lookup(AuthorizationInterface.class); // init Authorization Service authorizationInterface.init(this.config); try { isAuthorized = authorizationInterface.isTokenValid(httpServletResponse, service, changeRequest.getPatron(), access_token); } catch (AuthorizationException e) { // TODO correct error handling this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + "!"); } } else { // TODO correct error handling this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": " + "Authorization Interface not implemented!"); } } this.logger.debug("Authorization: " + access_token + " - " + isAuthorized); if (!isAuthorized) { // Authorization this.authorize(httpServletRequest, httpServletResponse, format); } else { if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) { LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class); // init ILS libraryManagementSystem.init(this.config); // exists patron? // use LibraryManagementSystem.patron(): failed = Exception! try { Patron patron = libraryManagementSystem.patron(changeRequest.getPatron(), false); boolean isChanged = libraryManagementSystem.changePassword(changeRequest); if (isChanged) { // E-Mail to user Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf")); try { if (this.config.getProperty("isTestMode") != null && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) { mailer.postMail(patron.getEmail(), this.config.getProperty("service.mailer.change.subject"), this.config.getProperty("service.mailer.change.message")); } else { mailer.postMail(this.config.getProperty("service.mailer.change.subject"), this.config.getProperty("service.mailer.change.message")); } } catch (MessagingException e1) { this.logger.error(e1.getMessage(), e1.getCause()); } this.logger.info("Password changed. Mail send to '" + patron.getEmail() + "'."); // 200 OK if (format.equals("html")) { format = "json"; // TODO or what else? } Patron responsePatron = new Patron(); responsePatron.setUsername(patron.getUsername()); responsePatron.setStatus(patron.getStatus()); responsePatron.setEmail(new InternetAddress(patron.getEmail())); if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), responsePatron); } if (format.equals("xml")) { JAXBContext context = JAXBContext.newInstance(Patron.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(responsePatron, httpServletResponse.getWriter()); } } else { // 401 UNAUTHORIZED this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong old password!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } catch (LibraryManagementSystemException e) { // 401 UNAUTHORIZED this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": " + e.getMessage()); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } catch (Exception e) { this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } else { this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } break; } case "renew": { if (Lookup.lookupAll(LibraryManagementSystem.class).size() > 0) { LibraryManagementSystem libraryManagementSystem = Lookup.lookup(LibraryManagementSystem.class); // init ILS libraryManagementSystem.init(this.config); // exists patron? // use LibraryManagementSystem.patron(): failed = Exception! try { // build NewPasswordRequest object NewPasswordRequest newPasswordRequest = mapper.readValue(requestBody, NewPasswordRequest.class); Patron patron = libraryManagementSystem.patron(newPasswordRequest.getPatron(), true); if (patron.getEmail() != null && !patron.getEmail().equals("")) { boolean isRenewed = libraryManagementSystem.renewPassword(newPasswordRequest, patron); if (isRenewed) { // E-Mail to user Mailer mailer = new Mailer(this.config.getProperty("service.mailer.conf")); try { if (this.config.getProperty("isTestMode") != null && !Boolean.parseBoolean(this.config.getProperty("isTestMode"))) { mailer.postMail(patron.getEmail(), this.config.getProperty("service.mailer.renew.subject"), this.config.getProperty("service.mailer.renew.message")); } else { mailer.postMail(this.config.getProperty("service.mailer.renew.subject"), this.config.getProperty("service.mailer.renew.message")); } } catch (MessagingException e1) { this.logger.error(e1.getMessage(), e1.getCause()); } this.logger.info("Password resetted. Mail send to '" + patron.getEmail() + "'."); // 200 OK if (format.equals("html")) { format = "json"; // TODO or what else? } Patron responsePatron = new Patron(); responsePatron.setUsername(patron.getUsername()); responsePatron.setStatus(patron.getStatus()); responsePatron.setEmail(new InternetAddress(patron.getEmail())); if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), responsePatron); } if (format.equals("xml")) { JAXBContext context = JAXBContext.newInstance(Patron.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(responsePatron, httpServletResponse.getWriter()); } } else { // 401 SC_UNAUTHORIZED this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": Wrong usergroup!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } else { // 401 SC_UNAUTHORIZED this.logger.error(HttpServletResponse.SC_UNAUTHORIZED + ": No E-Mail-Address exists!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } catch (LibraryManagementSystemException e) { e.printStackTrace(); // 400 SC_BAD_REQUEST this.logger.error(HttpServletResponse.SC_BAD_REQUEST + ": " + e.getMessage()); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } catch (Exception e) { this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } else { this.logger.error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR + ": Config Error!"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR))); requestError.setCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); requestError.setDescription(this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".description")); requestError.setErrorUri(this.config.getProperty( "error." + Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } break; } default: { this.logger.error(HttpServletResponse.SC_BAD_REQUEST + "Unknown function! (" + service + ")"); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null && !httpServletRequest.getParameter("suppress_response_codes").equals("")) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError( this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST))); requestError.setCode(HttpServletResponse.SC_BAD_REQUEST); requestError.setDescription(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".description")); requestError.setErrorUri(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_BAD_REQUEST) + ".uri")); this.sendRequestError(httpServletResponse, requestError, format, language, redirect_url); } } }
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.smartdeployment.main.SmartDeploymentService.java
@GET @Path("/CAMFTosca/enrich/quelle/{serviceName}") @Consumes(MediaType.APPLICATION_XML)//ww w . j a v a2s .com public String enrichCAMFToscaWithQuelle(@PathParam("serviceName") String serviceName, @QueryParam("f") String[] listOfFunctionality) { List<String> list = Arrays.asList(listOfFunctionality); String file = SalsaConfiguration.getToscaTemplateStorage() + "/" + serviceName + this.enrichedExt; if (!(new File(file).exists())) { try { FileUtils.copyFile( new File( SalsaConfiguration.getToscaTemplateStorage() + "/" + serviceName + this.origineExt), new File(file)); } catch (IOException ex) { EngineLogger.logger.error("The original Tosca is not found to copy. Cannot enrich.", ex); } } if (list.contains(EnrichFunctions.SalsaInfoCompletion.toString())) { // TODO: develop this } if (list.contains(EnrichFunctions.QuelleCloudServiceRecommendation.toString())) { EngineLogger.logger.debug("Start to enrich by using: QuelleCloudServiceRecommendation"); QuelleService quelleService = new QuelleService(); try { TDefinitions def = ToscaXmlProcess.readToscaFile(file); MultiLevelRequirements reqs = generateQuelleRequirementFromCAMFTosca(def); RecommendationSummaries sums = quelleService.getRecommendationSummary(reqs); // load requirements EngineLogger.logger.debug("recommendation sums: " + sums.toXML()); updateCAMFDescriptionWithQuelleResult(def, sums); EngineLogger.logger.debug("Writing down Quelle enriched file"); JAXBContext jaxbContext = JAXBContext.newInstance(TDefinitions.class, CAMFElasticityProperty.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(def, new File(file)); EngineLogger.logger.debug("Writing down Quelle enriched file done"); } catch (JAXBException | IOException ex) { EngineLogger.logger.error("Failure in enriching CAMF TOSCA.", ex); } } try { return FileUtils.readFileToString(new File(file)); } catch (IOException ex) { EngineLogger.logger.error("Cannot read the enriched file. Big problem !", ex); return null; } }
From source file:de.tu_dortmund.ub.api.paia.core.PaiaCoreEndpoint.java
/** * * @param httpServletRequest/*from w ww . j av a 2 s . c o m*/ * @param httpServletResponse * @throws IOException */ private void authorize(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String format, DocumentList documents) throws IOException { httpServletResponse.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin")); httpServletResponse.setHeader("Cache-Control", config.getProperty("Cache-Control")); ObjectMapper mapper = new ObjectMapper(); // Error handling mit suppress_response_codes=true if (httpServletRequest.getParameter("suppress_response_codes") != null) { httpServletResponse.setStatus(HttpServletResponse.SC_OK); } // Error handling mit suppress_response_codes=false (=default) else { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); } // Json fr Response body RequestError requestError = new RequestError(); requestError.setError( this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED))); requestError.setCode(HttpServletResponse.SC_UNAUTHORIZED); requestError.setDescription(this.config .getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".description")); requestError.setErrorUri( this.config.getProperty("error." + Integer.toString(HttpServletResponse.SC_UNAUTHORIZED) + ".uri")); // XML-Ausgabe mit JAXB if (format.equals("xml")) { try { JAXBContext context = JAXBContext.newInstance(RequestError.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to HttpResponse httpServletResponse.setContentType("application/xml;charset=UTF-8"); m.marshal(requestError, httpServletResponse.getWriter()); } catch (JAXBException e) { this.logger.error(e.getMessage(), e.getCause()); httpServletResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error: Error while rendering the results."); } } // JSON-Ausgabe mit Jackson if (format.equals("json")) { httpServletResponse.setContentType("application/json;charset=UTF-8"); mapper.writeValue(httpServletResponse.getWriter(), requestError); } // html > redirect zu "PAIA auth - login" mit redirect_url = "PAIA core - service" if (format.equals("html")) { httpServletResponse.setContentType("text/html;charset=UTF-8"); if (documents != null) { // set Cookie with urlencoded DocumentList-JSON StringWriter stringWriter = new StringWriter(); mapper.writeValue(stringWriter, documents); Cookie cookie = new Cookie("PaiaServiceDocumentList", URLEncoder.encode(stringWriter.toString(), "UTF-8")); if (this.config.getProperty("service.cookie.domain") != null && !this.config.getProperty("service.cookie.domain").equals("")) { cookie.setDomain(this.config.getProperty("service.cookie.domain")); } cookie.setMaxAge(-1); cookie.setPath("/"); httpServletResponse.addCookie(cookie); } //String redirect_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo(); String redirect_url = this.config.getProperty("service.base_url") + this.config.getProperty("service.endpoint.core") + httpServletRequest.getPathInfo(); if (httpServletRequest.getQueryString() != null && !httpServletRequest.getQueryString().equals("")) { redirect_url += "?" + httpServletRequest.getQueryString(); } this.logger.info("redirect_url = " + redirect_url); //String login_url = "http://" + httpServletRequest.getServerName() + ":" + httpServletRequest.getServerPort() + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url; String login_url = this.config.getProperty("service.base_url") + this.config.getProperty("service.endpoint.auth") + "/login?redirect_url=" + redirect_url; this.logger.info("login_url = " + login_url); httpServletResponse.sendRedirect(login_url); } }
From source file:hydrograph.ui.common.util.ExternalOperationExpressionUtil.java
public void marshal(Class<?> clazz, File file, Object object) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(object, file); }
From source file:gov.va.ds4p.ds4pmobileportal.pep.XACMLPolicyEnforcement.java
private String dumpRequestToString() { String res = ""; JAXBElement<RequestType> element = new JAXBElement<RequestType>( new QName("urn:oasis:names:tc:xacml:2.0:context:schema:os", "Request"), RequestType.class, query); try {// ww w.ja va2 s . c o m JAXBContext context = JAXBContext.newInstance(RequestType.class); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(element, sw); res = sw.toString(); } catch (Exception ex) { ex.printStackTrace(); } return res; }
From source file:gov.va.ds4p.ds4pmobileportal.pep.XACMLPolicyEnforcement.java
private String dumpResponseToString(ResultType resp) { String res = ""; JAXBElement<ResultType> element = new JAXBElement<ResultType>( new QName("urn:oasis:names:tc:xacml:2.0:context:schema:os", "Result"), ResultType.class, resp); try {// w w w . j a va2s .c o m JAXBContext context = JAXBContext.newInstance(ResultType.class); Marshaller marshaller = context.createMarshaller(); StringWriter sw = new StringWriter(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); //marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); marshaller.marshal(element, sw); res = sw.toString(); } catch (Exception ex) { ex.printStackTrace(); } return res; }