List of usage examples for javax.servlet.http HttpServletRequest getContentType
public String getContentType();
null
if the type is not known. From source file:org.wso2.carbon.bpmn.rest.service.runtime.ProcessInstanceService.java
protected Response createExecutionVariable(Execution execution, boolean override, int variableType, HttpServletRequest httpServletRequest) throws IOException, ServletException { boolean debugEnabled = log.isDebugEnabled(); if (debugEnabled) { log.debug("httpServletRequest.getContentType():" + httpServletRequest.getContentType()); }//w w w .j a v a 2 s . c o m Response.ResponseBuilder responseBuilder = Response.ok(); if (debugEnabled) { log.debug("Processing non binary variable"); } List<RestVariable> inputVariables = new ArrayList<>(); List<RestVariable> resultVariables = new ArrayList<>(); try { if (Utils.isApplicationJsonRequest(httpServletRequest)) { ObjectMapper objectMapper = new ObjectMapper(); @SuppressWarnings("unchecked") List<Object> variableObjects = (List<Object>) objectMapper .readValue(httpServletRequest.getInputStream(), List.class); for (Object restObject : variableObjects) { RestVariable restVariable = objectMapper.convertValue(restObject, RestVariable.class); inputVariables.add(restVariable); } } else if (Utils.isApplicationXmlRequest(httpServletRequest)) { JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(RestVariableCollection.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); RestVariableCollection restVariableCollection = (RestVariableCollection) jaxbUnmarshaller .unmarshal(httpServletRequest.getInputStream()); if (restVariableCollection == null) { throw new ActivitiIllegalArgumentException("xml request body could not be transformed to a " + "RestVariable Collection instance."); } List<RestVariable> restVariableList = restVariableCollection.getRestVariables(); if (restVariableList.size() == 0) { throw new ActivitiIllegalArgumentException( "xml request body could not identify any rest " + "variables to be updated"); } for (RestVariable restVariable : restVariableList) { inputVariables.add(restVariable); } } catch (JAXBException | IOException e) { throw new ActivitiIllegalArgumentException( "xml request body could not be transformed to a " + "RestVariable instance.", e); } } } catch (Exception e) { throw new ActivitiIllegalArgumentException("Failed to serialize to a RestVariable instance", e); } if (inputVariables.size() == 0) { throw new ActivitiIllegalArgumentException("Request didn't contain a list of variables to create."); } RestVariable.RestVariableScope sharedScope = null; RestVariable.RestVariableScope varScope; Map<String, Object> variablesToSet = new HashMap<>(); for (RestVariable var : inputVariables) { // Validate if scopes match varScope = var.getVariableScope(); if (var.getName() == null) { throw new ActivitiIllegalArgumentException("Variable name is required"); } if (varScope == null) { varScope = RestVariable.RestVariableScope.LOCAL; } if (sharedScope == null) { sharedScope = varScope; } if (varScope != sharedScope) { throw new ActivitiIllegalArgumentException( "Only allowed to update multiple variables in the same scope."); } if (!override && hasVariableOnScope(execution, var.getName(), varScope)) { throw new BPMNConflictException("Variable '" + var.getName() + "' is already present on execution '" + execution.getId() + "'."); } RestResponseFactory restResponseFactory = new RestResponseFactory(); Object actualVariableValue = restResponseFactory.getVariableValue(var); variablesToSet.put(var.getName(), actualVariableValue); resultVariables.add(restResponseFactory.createRestVariable(var.getName(), actualVariableValue, varScope, execution.getId(), variableType, false, uriInfo.getBaseUri().toString())); } if (!variablesToSet.isEmpty()) { RuntimeService runtimeService = BPMNOSGIService.getRuntimeService(); if (sharedScope == RestVariable.RestVariableScope.LOCAL) { runtimeService.setVariablesLocal(execution.getId(), variablesToSet); } else { if (execution.getParentId() != null) { // Explicitly set on parent, setting non-local variables on execution itself will override local-variables if exists runtimeService.setVariables(execution.getParentId(), variablesToSet); } else { // Standalone task, no global variables possible throw new ActivitiIllegalArgumentException("Cannot set global variables on execution '" + execution.getId() + "', task is not part of process."); } } } RestVariableCollection restVariableCollection = new RestVariableCollection(); restVariableCollection.setRestVariables(resultVariables); responseBuilder.entity(restVariableCollection); // } return responseBuilder.status(Response.Status.CREATED).build(); }
From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { try {/* ww w . j a va 2 s . c o m*/ if (!initialized.get()) { initializeServer(context); } } catch (Exception e) { context.yield(); throw new ProcessException("Failed to initialize the server", e); } final HttpRequestContainer container = containerQueue.poll(); if (container == null) { return; } final long start = System.nanoTime(); final HttpServletRequest request = container.getRequest(); FlowFile flowFile = session.create(); try { flowFile = session.importFrom(request.getInputStream(), flowFile); } catch (final IOException e) { getLogger().error("Failed to receive content from HTTP Request from {} due to {}", new Object[] { request.getRemoteAddr(), e }); session.remove(flowFile); return; } final String charset = request.getCharacterEncoding() == null ? context.getProperty(URL_CHARACTER_SET).getValue() : request.getCharacterEncoding(); final String contextIdentifier = UUID.randomUUID().toString(); final Map<String, String> attributes = new HashMap<>(); try { putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier); putAttribute(attributes, "mime.type", request.getContentType()); putAttribute(attributes, "http.servlet.path", request.getServletPath()); putAttribute(attributes, "http.context.path", request.getContextPath()); putAttribute(attributes, "http.method", request.getMethod()); putAttribute(attributes, "http.local.addr", request.getLocalAddr()); putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName()); final String queryString = request.getQueryString(); if (queryString != null) { putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset)); } putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost()); putAttribute(attributes, "http.remote.addr", request.getRemoteAddr()); putAttribute(attributes, "http.remote.user", request.getRemoteUser()); putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI()); putAttribute(attributes, "http.request.url", request.getRequestURL().toString()); putAttribute(attributes, "http.auth.type", request.getAuthType()); putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId()); final DispatcherType dispatcherType = request.getDispatcherType(); if (dispatcherType != null) { putAttribute(attributes, "http.dispatcher.type", dispatcherType.name()); } putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding()); putAttribute(attributes, "http.locale", request.getLocale()); putAttribute(attributes, "http.server.name", request.getServerName()); putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort()); final Enumeration<String> paramEnumeration = request.getParameterNames(); while (paramEnumeration.hasMoreElements()) { final String paramName = paramEnumeration.nextElement(); final String value = request.getParameter(paramName); attributes.put("http.param." + paramName, value); } final Cookie[] cookies = request.getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { final String name = cookie.getName(); final String cookiePrefix = "http.cookie." + name + "."; attributes.put(cookiePrefix + "value", cookie.getValue()); attributes.put(cookiePrefix + "domain", cookie.getDomain()); attributes.put(cookiePrefix + "path", cookie.getPath()); attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge())); attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion())); attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure())); } } if (queryString != null) { final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString); for (final String keyValueString : params) { final int indexOf = keyValueString.indexOf("="); if (indexOf < 0) { // no =, then it's just a key with no value attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), ""); } else { final String key = keyValueString.substring(0, indexOf); final String value; if (indexOf == keyValueString.length() - 1) { value = ""; } else { value = keyValueString.substring(indexOf + 1); } attributes.put("http.query.param." + URLDecoder.decode(key, charset), URLDecoder.decode(value, charset)); } } } } catch (final UnsupportedEncodingException uee) { throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated } final Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); final String headerValue = request.getHeader(headerName); putAttribute(attributes, "http.headers." + headerName, headerValue); } final Principal principal = request.getUserPrincipal(); if (principal != null) { putAttribute(attributes, "http.principal.name", principal.getName()); } final X509Certificate certs[] = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); final String subjectDn; if (certs != null && certs.length > 0) { final X509Certificate cert = certs[0]; subjectDn = cert.getSubjectDN().getName(); final String issuerDn = cert.getIssuerDN().getName(); putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn); putAttribute(attributes, "http.issuer.dn", issuerDn); } else { subjectDn = null; } flowFile = session.putAllAttributes(flowFile, attributes); final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP) .asControllerService(HttpContextMap.class); final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(), container.getContext()); if (!registered) { getLogger().warn( "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE", new Object[] { request.getRemoteAddr() }); try { container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode()); container.getResponse().flushBuffer(); container.getContext().complete(); } catch (final Exception e) { getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}", new Object[] { request.getRemoteAddr(), e }); } session.remove(flowFile); return; } final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes), "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn), receiveMillis); session.transfer(flowFile, REL_SUCCESS); getLogger().info("Transferring {} to 'success'; received from {}", new Object[] { flowFile, request.getRemoteAddr() }); }
From source file:org.gatherdata.camel.http.internal.ServletProxyProducerImpl.java
private Map<String, Object> extractHeaders(HttpServletRequest request) { Map<String, Object> headers = new HashMap<String, Object>(); String contentType = ""; //apply the headerFilterStrategy Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Object value = request.getHeader(name); // mapping the content-type if (name.toLowerCase().equals("content-type")) { name = Exchange.CONTENT_TYPE; contentType = (String) value; }/* w ww . jav a 2s.co m*/ headers.put(name, value); } //we populate the http request parameters for GET and POST String method = request.getMethod(); if (method.equalsIgnoreCase("GET") || (method.equalsIgnoreCase("POST") && contentType.equalsIgnoreCase("application/x-www-form-urlencoded"))) { names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Object value = request.getParameter(name); headers.put(name, value); } } // store the method and query and other info in headers headers.put(Exchange.HTTP_METHOD, request.getMethod()); headers.put(Exchange.HTTP_QUERY, request.getQueryString()); //headers.put(Exchange.HTTP_URL, request.getRequestURL()); headers.put(Exchange.HTTP_URI, request.getRequestURI()); headers.put(Exchange.HTTP_PATH, request.getPathInfo()); headers.put(Exchange.CONTENT_TYPE, request.getContentType()); headers.put(Exchange.HTTP_CHARACTER_ENCODING, request.getCharacterEncoding()); return headers; }
From source file:org.sakaiproject.mbm.servlet.SakaiToolServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (log.isDebugEnabled()) { StringBuilder headers = new StringBuilder("Headers ["); StringBuilder params = new StringBuilder("Params ["); Enumeration<String> headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String s = headerNames.nextElement(); headers.append(s).append("={") .append(StringUtils.isNotEmpty(req.getHeader(s)) ? req.getHeader(s) : "null").append("},"); }/* w ww . j a va2 s. c om*/ headers.append("]"); Enumeration<String> paramNames = req.getParameterNames(); while (paramNames.hasMoreElements()) { String s = paramNames.nextElement(); params.append(s).append("={") .append(StringUtils.isNotEmpty(req.getParameter(s)) ? req.getParameter(s) : "null") .append("},"); } params.append("]"); log.debug(new StringBuilder() .append("SakaiToolServlet: service(HttpServletRequest, HttpServletResponse)\n") .append("context path = ").append(req.getContextPath()).append("\n").append("request path = ") .append(StringUtils.isNotEmpty(req.getPathInfo()) ? req.getPathInfo() : "null").append("\n") .append("headers = ").append(headers).append("\n").append("params = ").append(params) .append("\n").append("content type = ") .append(StringUtils.isNotEmpty(req.getContentType()) ? req.getContentType() : "null") .append("\n").append("method = ").append(req.getMethod()).append("\n") .append("query = ") .append(StringUtils.isNotEmpty(req.getQueryString()) ? req.getQueryString() : "null") .append("\n").append("request url = ").append(req.getRequestURL()).append("\n") .append("request uri = ").append(req.getRequestURI()).append("\n").append("locale = ") .append(req.getLocale()).append("\n")); } final String startPage = StringUtils.isNotEmpty(getInitParameter("index")) ? getInitParameter("index") : "/"; final String contextPath = req.getContextPath(); req.setAttribute(Tool.NATIVE_URL, Tool.NATIVE_URL); HttpServletRequest wrappedReq = new HttpServletRequestWrapper(req) { public String getContextPath() { return contextPath; } }; if (StringUtils.isEmpty(req.getPathInfo())) { resp.sendRedirect(contextPath + startPage); } else { RequestDispatcher dispatcher; if (StringUtils.isEmpty(req.getPathInfo())) { dispatcher = req.getRequestDispatcher("/"); } else { dispatcher = req.getRequestDispatcher(req.getPathInfo()); } dispatcher.forward(wrappedReq, resp); } }
From source file:fr.inrialpes.exmo.align.service.HTTPTransport.java
/** * Starts a HTTP server to given port./*from w w w . ja v a2 s .c o m*/ * * @param params: the parameters of the connection, including HTTP port and host * @param manager: the manager which will deal with connections * @param serv: the set of services to be listening on this connection * @throws AServException when something goes wrong (e.g., socket already in use) */ public void init(Properties params, AServProtocolManager manager, Vector<AlignmentServiceProfile> serv) throws AServException { this.manager = manager; services = serv; tcpPort = Integer.parseInt(params.getProperty("http")); tcpHost = params.getProperty("host"); // ******************************************************************** // JE: Jetty implementation server = new Server(tcpPort); // The handler deals with the request // most of its work is to deal with large content sent in specific ways Handler handler = new AbstractHandler() { public void handle(String String, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String method = request.getMethod(); String uri = request.getPathInfo(); Properties params = new Properties(); try { decodeParams(request.getQueryString(), params); } catch (Exception ex) { logger.debug("IGNORED EXCEPTION: {}", ex); } ; // I do not decode them here because it is useless // See below how it is done. Properties header = new Properties(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); header.setProperty(headerName, request.getHeader(headerName)); } // Get the content if any // This is supposed to be only an uploaded file // Note that this could be made more uniform // with the text/xml part stored in a file as well. String mimetype = request.getContentType(); // Multi part: the content provided by an upload HTML form if (mimetype != null && mimetype.startsWith("multipart/form-data")) { try { //if ( !ServletFileUpload.isMultipartContent( request ) ) { // logger.debug( "Does not detect multipart" ); //} DiskFileItemFactory factory = new DiskFileItemFactory(); File tempDir = new File(System.getProperty("java.io.tmpdir")); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (FileItem fi : items) { if (fi.isFormField()) { logger.trace(" >> {} = {}", fi.getFieldName(), fi.getString()); params.setProperty(fi.getFieldName(), fi.getString()); } else { logger.trace(" >> {} : {}", fi.getName(), fi.getSize()); logger.trace(" Stored at {}", fi.getName(), fi.getSize()); try { // FilenameUtils.getName() needed for Internet Explorer problem File uploadedFile = new File(tempDir, FilenameUtils.getName(fi.getName())); fi.write(uploadedFile); params.setProperty("filename", uploadedFile.toString()); params.setProperty("todiscard", "true"); } catch (Exception ex) { logger.warn("Cannot load file", ex); } // Another solution is to run this in /* InputStream uploadedStream = item.getInputStream(); ... uploadedStream.close(); */ } } ; } catch (FileUploadException fuex) { logger.trace("Upload Error", fuex); } } else if (mimetype != null && mimetype.startsWith("text/xml")) { // Most likely Web service request (REST through POST) int length = request.getContentLength(); if (length > 0) { char[] mess = new char[length + 1]; try { new BufferedReader(new InputStreamReader(request.getInputStream())).read(mess, 0, length); } catch (Exception e) { logger.debug("IGNORED Exception", e); } params.setProperty("content", new String(mess)); } // File attached to SOAP messages } else if (mimetype != null && mimetype.startsWith("application/octet-stream")) { File alignFile = new File(File.separator + "tmp" + File.separator + newId() + "XXX.rdf"); // check if file already exists - and overwrite if necessary. if (alignFile.exists()) alignFile.delete(); FileOutputStream fos = new FileOutputStream(alignFile); InputStream is = request.getInputStream(); try { byte[] buffer = new byte[4096]; int bytes = 0; while (true) { bytes = is.read(buffer); if (bytes < 0) break; fos.write(buffer, 0, bytes); } } catch (Exception e) { } finally { fos.flush(); fos.close(); } is.close(); params.setProperty("content", ""); params.setProperty("filename", alignFile.getAbsolutePath()); } // Get the answer (HTTP) HTTPResponse r = serve(uri, method, header, params); // Return it response.setContentType(r.getContentType()); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(r.getData()); ((Request) request).setHandled(true); } }; server.setHandler(handler); // Common part try { server.start(); } catch (Exception e) { throw new AServException("Cannot launch HTTP Server", e); } //server.join(); // ******************************************************************** //if ( params.getProperty( "wsdl" ) != null ){ // wsmanager = new WSAServProfile(); // if ( wsmanager != null ) wsmanager.init( params, manager ); //} //if ( params.getProperty( "http" ) != null ){ // htmanager = new HTMLAServProfile(); // if ( htmanager != null ) htmanager.init( params, manager ); //} myId = "LocalHTMLInterface"; serverId = manager.serverURL(); logger.info("Launched on {}/html/", serverId); localId = 0; }
From source file:org.wso2.carbon.identity.oauth.endpoint.revoke.OAuthRevocationEndpointTest.java
private HttpServletRequest mockHttpRequest(final Map<String, String[]> requestParams, final Map<String, Object> requestAttributes) { HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); doAnswer(new Answer<Object>() { @Override// w ww . j a v a 2 s .c o m public Object answer(InvocationOnMock invocation) throws Throwable { String key = (String) invocation.getArguments()[0]; return requestParams.get(key) != null ? requestParams.get(key)[0] : null; } }).when(httpServletRequest).getParameter(anyString()); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String key = (String) invocation.getArguments()[0]; return requestAttributes.get(key); } }).when(httpServletRequest).getAttribute(anyString()); doAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { String key = (String) invocation.getArguments()[0]; Object value = invocation.getArguments()[1]; requestAttributes.put(key, value); return null; } }).when(httpServletRequest).setAttribute(anyString(), Matchers.anyObject()); when(httpServletRequest.getParameterMap()).thenReturn(requestParams); when(httpServletRequest.getParameterNames()) .thenReturn(new IteratorEnumeration(requestParams.keySet().iterator())); when(httpServletRequest.getMethod()).thenReturn(HttpMethod.POST); when(httpServletRequest.getContentType()).thenReturn(OAuth.ContentType.URL_ENCODED); return httpServletRequest; }
From source file:org.zoxweb.server.http.servlet.HTTPServletUtil.java
@SuppressWarnings("unchecked") public static HTTPRequestAttributes extractRequestAttributes(HttpServletRequest req, boolean readParameters) throws IOException { HTTPRequestAttributes ret = null;//from w w w . jav a2s.c o m DiskFileItemFactory dfif = null; List<FileItem> items = null; // check if the request is of multipart type List<GetNameValue<String>> headers = extractRequestHeaders(req); List<GetNameValue<String>> params = new ArrayList<GetNameValue<String>>(); List<FileInfoStreamSource> streamList = new ArrayList<FileInfoStreamSource>(); /* * Retrieve path info if it exists. If the pathInfo starts or ends with a "/", the "/" is removed * and value is trimmed. */ String pathInfo = req.getPathInfo(); // Removing the first "/" in pathInfo. pathInfo = SharedStringUtil.trimOrNull(SharedStringUtil.valueAfterLeftToken(pathInfo, "/")); // Removing the last "/" in pathInfo. if (pathInfo != null) { if (pathInfo.endsWith("/")) { pathInfo = SharedStringUtil.trimOrNull(pathInfo.substring(0, pathInfo.length() - 1)); } } if (ServletFileUpload.isMultipartContent(req)) { dfif = new DiskFileItemFactory(); try { ServletFileUpload upload = new ServletFileUpload(dfif); upload.setHeaderEncoding(SharedStringUtil.UTF_8); items = upload.parseRequest(req); } catch (FileUploadException e) { throw new IOException("Upload problem:" + e); } for (FileItem fi : items) { if (fi.isFormField()) { String name = fi.getFieldName(); String value = fi.getString(); params.add(new NVPair(name, value)); } else { String content = fi.getContentType(); InputStream is = fi.getInputStream(); String filename = fi.getName(); FileInfoDAO fid = new FileInfoDAO(); fid.setName(filename); fid.setCreationTime(System.currentTimeMillis()); fid.setContentType(content); fid.setLength(fi.getSize()); FileInfoStreamSource fiss = new FileInfoStreamSource(fid, is); streamList.add(fiss); } } ret = new HTTPRequestAttributes(req.getRequestURI(), pathInfo, req.getContentType(), true, headers, params, streamList); } else { if (readParameters) { params = (List<GetNameValue<String>>) SharedUtil.toNVPairs(req.getParameterMap()); } ret = new HTTPRequestAttributes(req.getRequestURI(), pathInfo, req.getContentType(), false, headers, params, streamList, new HTTPRequestStringContentDecoder(req)); } return ret; }
From source file:org.sakaiproject.lti2.LTI2Service.java
public void handleSettingsRequest(HttpServletRequest request, HttpServletResponse response, String[] parts) throws java.io.IOException { String allowSettings = ServerConfigurationService.getString(SakaiBLTIUtil.BASICLTI_SETTINGS_ENABLED, SakaiBLTIUtil.BASICLTI_SETTINGS_ENABLED_DEFAULT); if (!"true".equals(allowSettings)) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, null, "Tool settings not available", null); return;/*w w w . jav a2 s . c o m*/ } String URL = SakaiBLTIUtil.getOurServletPath(request); String scope = parts[4]; // Check to see if we are doing the bubble String bubbleStr = request.getParameter("bubble"); String acceptHdr = request.getHeader("Accept"); String contentHdr = request.getContentType(); System.out.println("accept=" + acceptHdr + " bubble=" + bubbleStr); if (bubbleStr != null && bubbleStr.equals("all") && acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) < 0) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, null, "Simple format does not allow bubble=all", null); return; } boolean bubble = bubbleStr != null && "GET".equals(request.getMethod()); boolean distinct = bubbleStr != null && "distinct".equals(bubbleStr) && "GET".equals(request.getMethod()); boolean bubbleAll = bubbleStr != null && "all".equals(bubbleStr) && "GET".equals(request.getMethod()); // Check our input and output formats boolean acceptSimple = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT) >= 0; boolean acceptComplex = acceptHdr == null || acceptHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0; boolean inputSimple = contentHdr == null || contentHdr.indexOf(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT) >= 0; boolean inputComplex = contentHdr != null && contentHdr.indexOf(StandardServices.TOOLSETTINGS_FORMAT) >= 0; System.out.println( "as=" + acceptSimple + " ac=" + acceptComplex + " is=" + inputSimple + " ic=" + inputComplex); // Check the JSON on PUT and check the oauth_body_hash IMSJSONRequest jsonRequest = null; JSONObject requestData = null; if ("PUT".equals(request.getMethod())) { try { jsonRequest = new IMSJSONRequest(request); requestData = (JSONObject) JSONValue.parse(jsonRequest.getPostBody()); } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Could not parse JSON", e); return; } } String consumer_key = null; String siteId = null; String placement_id = null; Map<String, Object> content = null; Long contentKey = null; Map<String, Object> tool = null; Long toolKey = null; Map<String, Object> proxyBinding = null; Long proxyBindingKey = null; Map<String, Object> deploy = null; Long deployKey = null; if (LTI2Util.SCOPE_LtiLink.equals(scope) || LTI2Util.SCOPE_ToolProxyBinding.equals(scope)) { placement_id = parts[5]; System.out.println("placement_id=" + placement_id); String contentStr = placement_id.substring(8); contentKey = SakaiBLTIUtil.getLongKey(contentStr); if (contentKey >= 0) { // Leave off the siteId - bypass all checking - because we need to // find the siteId from the content item content = ltiService.getContentDao(contentKey); if (content != null) siteId = (String) content.get(LTIService.LTI_SITE_ID); } if (content == null || siteId == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Bad content item", null); return; } toolKey = SakaiBLTIUtil.getLongKey(content.get(LTIService.LTI_TOOL_ID)); if (toolKey >= 0) { tool = ltiService.getToolDao(toolKey, siteId); } if (tool == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Bad tool item", null); return; } // Adjust the content items based on the tool items ltiService.filterContent(content, tool); // Check settings to see if we are allowed to do this if (foorm.getLong(content.get(LTIService.LTI_ALLOWOUTCOMES)) > 0 || foorm.getLong(tool.get(LTIService.LTI_ALLOWOUTCOMES)) > 0) { // Good news } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, "Item does not allow tool settings", null); return; } } if (LTI2Util.SCOPE_ToolProxyBinding.equals(scope) || LTI2Util.SCOPE_LtiLink.equals(scope)) { proxyBinding = ltiService.getProxyBindingDao(toolKey, siteId); if (proxyBinding != null) { proxyBindingKey = SakaiBLTIUtil.getLongKey(proxyBinding.get(LTIService.LTI_ID)); } } // Retrieve the deployment if needed if (LTI2Util.SCOPE_ToolProxy.equals(scope)) { consumer_key = parts[5]; deploy = ltiService.getDeployForConsumerKeyDao(consumer_key); if (deploy == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Bad deploy item", null); return; } deployKey = SakaiBLTIUtil.getLongKey(deploy.get(LTIService.LTI_ID)); } else { if (tool == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Bad tool item", null); return; } deployKey = SakaiBLTIUtil.getLongKey(tool.get(LTIService.LTI_DEPLOYMENT_ID)); if (deployKey >= 0) { deploy = ltiService.getDeployDao(deployKey); } if (deploy == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Bad deploy item", null); return; } consumer_key = (String) deploy.get(LTIService.LTI_CONSUMERKEY); } // Check settings to see if we are allowed to do this if (deploy != null) { if (foorm.getLong(deploy.get(LTIService.LTI_ALLOWOUTCOMES)) > 0) { // Good news } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, "Deployment does not allow tool settings", null); return; } } // The URLs for the various settings resources String settingsUrl = SakaiBLTIUtil.getOurServerUrl() + LTI2_PATH + SVC_Settings; String proxy_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxy + "/" + consumer_key; String binding_url = settingsUrl + "/" + LTI2Util.SCOPE_ToolProxyBinding + "/" + placement_id; String link_url = settingsUrl + "/" + LTI2Util.SCOPE_LtiLink + "/" + placement_id; // Load and parse the old settings... JSONObject link_settings = new JSONObject(); JSONObject binding_settings = new JSONObject(); JSONObject proxy_settings = new JSONObject(); if (content != null) { link_settings = LTI2Util.parseSettings((String) content.get(LTIService.LTI_SETTINGS)); } if (proxyBinding != null) { binding_settings = LTI2Util.parseSettings((String) proxyBinding.get(LTIService.LTI_SETTINGS)); } if (deploy != null) { proxy_settings = LTI2Util.parseSettings((String) deploy.get(LTIService.LTI_SETTINGS)); } /* if ( distinct && link_settings != null && scope.equals(LTI2Util.SCOPE_LtiLink) ) { Iterator i = link_settings.keySet().iterator(); while ( i.hasNext() ) { String key = (String) i.next(); if ( binding_settings != null ) binding_settings.remove(key); if ( proxy_settings != null ) proxy_settings.remove(key); } } if ( distinct && binding_settings != null && scope.equals(LTI2Util.SCOPE_ToolProxyBinding) ) { Iterator i = binding_settings.keySet().iterator(); while ( i.hasNext() ) { String key = (String) i.next(); if ( proxy_settings != null ) proxy_settings.remove(key); } } */ // Get the secret for the request... String oauth_secret = null; if (LTI2Util.SCOPE_LtiLink.equals(scope)) { oauth_secret = (String) content.get(LTIService.LTI_SECRET); if (oauth_secret == null || oauth_secret.length() < 1) { oauth_secret = (String) tool.get(LTIService.LTI_SECRET); } } else if (LTI2Util.SCOPE_ToolProxyBinding.equals(scope)) { oauth_secret = (String) tool.get(LTIService.LTI_SECRET); } else if (LTI2Util.SCOPE_ToolProxy.equals(scope)) { oauth_secret = (String) deploy.get(LTIService.LTI_SECRET); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Bad Setttings Scope=" + scope, null); return; } // Make sure we have a key and secret if (oauth_secret == null || consumer_key == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, "Key or secret is null, key=" + consumer_key, null); return; } // Validate the incoming message Object retval = SakaiBLTIUtil.validateMessage(request, URL, oauth_secret, consumer_key); if (retval instanceof String) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, (String) retval, null); return; } // For a GET request we depend on LTI2Util to do the GET logic if ("GET".equals(request.getMethod())) { Object obj = LTI2Util.getSettings(request, scope, link_settings, binding_settings, proxy_settings, link_url, binding_url, proxy_url); if (obj instanceof String) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, (String) obj, null); return; } if (acceptComplex) { response.setContentType(StandardServices.TOOLSETTINGS_FORMAT); } else { response.setContentType(StandardServices.TOOLSETTINGS_SIMPLE_FORMAT); } JSONObject jsonResponse = (JSONObject) obj; response.setStatus(HttpServletResponse.SC_OK); PrintWriter out = response.getWriter(); System.out.println("jsonResponse=" + jsonResponse); out.println(jsonResponse.toString()); return; } else if ("PUT".equals(request.getMethod())) { // This is assuming the rule that a PUT of the complex settings // format that there is only one entry in the graph and it is // the same as our current URL. We parse without much checking. String settings = null; try { JSONArray graph = (JSONArray) requestData.get(LTI2Constants.GRAPH); if (graph.size() != 1) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Only one graph entry allowed", null); return; } JSONObject firstChild = (JSONObject) graph.get(0); JSONObject custom = (JSONObject) firstChild.get(LTI2Constants.CUSTOM); settings = custom.toString(); } catch (Exception e) { settings = jsonRequest.getPostBody(); } retval = null; if (LTI2Util.SCOPE_LtiLink.equals(scope)) { content.put(LTIService.LTI_SETTINGS, settings); retval = ltiService.updateContentDao(contentKey, content, siteId); } else if (LTI2Util.SCOPE_ToolProxyBinding.equals(scope)) { if (proxyBinding != null) { proxyBinding.put(LTIService.LTI_SETTINGS, settings); retval = ltiService.updateProxyBindingDao(proxyBindingKey, proxyBinding); } else { Properties proxyBindingNew = new Properties(); proxyBindingNew.setProperty(LTIService.LTI_SITE_ID, siteId); proxyBindingNew.setProperty(LTIService.LTI_TOOL_ID, toolKey + ""); proxyBindingNew.setProperty(LTIService.LTI_SETTINGS, settings); retval = ltiService.insertProxyBindingDao(proxyBindingNew); M_log.info("inserted ProxyBinding setting=" + proxyBindingNew); } } else if (LTI2Util.SCOPE_ToolProxy.equals(scope)) { deploy.put(LTIService.LTI_SETTINGS, settings); retval = ltiService.updateDeployDao(deployKey, deploy); } if (retval instanceof String || (retval instanceof Boolean && ((Boolean) retval != Boolean.TRUE))) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, (String) retval, null); return; } response.setStatus(HttpServletResponse.SC_OK); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Method not handled=" + request.getMethod(), null); } }
From source file:org.dspace.app.xmlui.cocoon.servlet.multipart.DSpaceMultipartParser.java
public Hashtable getParts(HttpServletRequest request) throws IOException, MultipartException { this.parts = new Hashtable(); // Copy all parameters coming from the request URI to the parts table. // This happens when a form's action attribute has some parameters Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String[] values = request.getParameterValues(name); Vector v = new Vector(values.length); for (int i = 0; i < values.length; i++) { v.add(values[i]);// w w w . j a v a 2 s .c o m } this.parts.put(name, v); } // upload progress bar support this.session = request.getSession(); this.hasSession = this.session != null; if (this.hasSession) { this.uploadStatus = new Hashtable(); this.uploadStatus.put("started", Boolean.FALSE); this.uploadStatus.put("finished", Boolean.FALSE); this.uploadStatus.put("sent", new Integer(0)); this.uploadStatus.put("total", new Integer(request.getContentLength())); this.uploadStatus.put("filename", ""); this.uploadStatus.put("error", Boolean.FALSE); this.uploadStatus.put("uploadsdone", new Integer(0)); this.session.setAttribute(UPLOAD_STATUS_SESSION_ATTR, this.uploadStatus); } parseParts(request.getContentLength(), request.getContentType(), request.getInputStream()); if (this.hasSession) { this.uploadStatus.put("finished", Boolean.TRUE); } return this.parts; }
From source file:com.grameenfoundation.ictc.controllers.SaleforceIntegrationController.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./* w w w . ja va 2 s. c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Logger log = Logger.getLogger(SaleforceIntegrationController.class.getName()); response.setContentType("text/xml;charset=UTF-8"); BiodataModel biodataModel = new BiodataModel(); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String theString = IOUtils.toString(request.getInputStream(), "UTF-8"); System.out.println("Salesforce data/n " + theString); //gets request input stream InputStream in = request.getInputStream(); InputSource input = null; Transaction tx; tx = ICTCDBUtil.getInstance().getGraphDB().beginTx(); org.neo4j.graphdb.Node FarmerParent; try { System.out.println(" " + request.getContentType()); DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(theString)); System.out.println("After parsing XML"); Document doc = db.parse(is); System.out.println("Should be normalised now"); doc.getDocumentElement().normalize(); Element ele = doc.getDocumentElement(); //System.out.println("Root element :" + doc.getDocumentElement()); Node node = doc.getDocumentElement(); System.out.println("Root element " + doc.getDocumentElement()); //get fields from objects NodeList sObject = doc.getElementsByTagName("sObject"); for (int j = 0; j < sObject.getLength(); j++) { Node rowNode = sObject.item(j); // Map<String,String> m = (Map<String,String>) rowNode.getAttributes(); String salesforceObj = rowNode.getAttributes().getNamedItem("xsi:type").getNodeValue(); System.out.println(salesforceObj); if (salesforceObj.equalsIgnoreCase("sf:Farmer_Biodata__c")) { org.neo4j.graphdb.Node biodataNode = ICTCDBUtil.getInstance().getGraphDB() .createNode(Labels.FARMER); for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) { // System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent()); if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) { System.out.println( "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName())); biodataNode.setProperty( getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id") && !rowNode.getChildNodes().item(k).getNodeName().equals("#text")) { System.out .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName())); biodataNode.setProperty( getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } } FarmerParent = ParentNode.FarmerParentNode(); FarmerParent.createRelationshipTo(biodataNode, ICTCRelationshipTypes.FARMER); log.log(Level.INFO, "new node created {0}", biodataNode.getId()); tx.success(); out.println(sendAck()); } else if (salesforceObj.equals("sf:Harvest__c")) { org.neo4j.graphdb.Node HarvestParent; org.neo4j.graphdb.Node harvestNode = ICTCDBUtil.getInstance().getGraphDB() .createNode(Labels.HARVEST); String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele); System.out.println("farmerid " + farmerID); for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) { //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent()); if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) { System.out.println( "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName())); harvestNode.setProperty( getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id") && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) { System.out .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName())); harvestNode.setProperty( getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } } HarvestParent = ParentNode.HarvestParentNode(); HarvestParent.createRelationshipTo(harvestNode, ICTCRelationshipTypes.HARVEST); log.log(Level.INFO, "new node created {0}", harvestNode.getId()); Biodata b = biodataModel.getBiodata("Id", farmerID); biodataModel.BiodataToHarvest(b.getId(), harvestNode); tx.success(); out.println(sendAck()); } else if (salesforceObj.equals("sf:FarmManagement__c")) { org.neo4j.graphdb.Node FarmManagementParent; org.neo4j.graphdb.Node FarmManagementNode = ICTCDBUtil.getInstance().getGraphDB() .createNode(Labels.FARM_MANAGEMENT); String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele); System.out.println("farmerid " + farmerID); for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) { //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent()); if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) { System.out.println( "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName())); FarmManagementNode.setProperty( getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id") && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) { System.out .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName())); FarmManagementNode.setProperty( getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } } FarmManagementParent = ParentNode.FMParentNode(); FarmManagementParent.createRelationshipTo(FarmManagementNode, ICTCRelationshipTypes.FARM_MANAGEMENT); log.log(Level.INFO, "new node created {0}", FarmManagementNode.getId()); Biodata b = biodataModel.getBiodata("Id", farmerID); biodataModel.BiodataToFarmManagement(b.getId(), FarmManagementNode); tx.success(); out.println(sendAck()); } else if (salesforceObj.equals("sf:FarmOperations__c")) { org.neo4j.graphdb.Node FarmOperationParent; org.neo4j.graphdb.Node FarmOperationNode = ICTCDBUtil.getInstance().getGraphDB() .createNode(Labels.FARM_OPERATION); String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele); System.out.println("farmerid " + farmerID); for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) { //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent()); if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) { System.out.println( "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName())); FarmOperationNode.setProperty( getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id") && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) { System.out .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName())); FarmOperationNode.setProperty( getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } } FarmOperationParent = ParentNode.OperationsParentNode(); FarmOperationParent.createRelationshipTo(FarmOperationNode, ICTCRelationshipTypes.FARM_OPERATION); log.log(Level.INFO, "new node created {0}", FarmOperationNode.getId()); Biodata b = biodataModel.getBiodata("Id", farmerID); biodataModel.BiodataToOperations(b.getId(), FarmOperationNode); tx.success(); out.println(sendAck()); } else if (salesforceObj.equals("sf:Marketing__c")) { org.neo4j.graphdb.Node MarketingParent; org.neo4j.graphdb.Node MarketingNode = ICTCDBUtil.getInstance().getGraphDB() .createNode(Labels.MARKETING); String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele); System.out.println("farmerid " + farmerID); for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) { //System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent()); if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) { System.out.println( "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName())); MarketingNode.setProperty( getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id") && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) { System.out .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName())); MarketingNode.setProperty( getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } } MarketingParent = ParentNode.MarketingParentNode(); MarketingParent.createRelationshipTo(MarketingNode, ICTCRelationshipTypes.MARKETING); log.log(Level.INFO, "new node created {0}", MarketingNode.getId()); Biodata b = biodataModel.getBiodata("Id", farmerID); biodataModel.BiodataToMarketing(b.getId(), MarketingNode); tx.success(); out.println(sendAck()); } else if (salesforceObj.equals("sf:PostHarvest__c")) { org.neo4j.graphdb.Node PostHarvestParent; org.neo4j.graphdb.Node PostHarvestNode = ICTCDBUtil.getInstance().getGraphDB() .createNode(Labels.POSTHARVEST); String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele); System.out.println("farmerid " + farmerID); for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) { // System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent()); if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) { System.out.println( "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName())); PostHarvestNode.setProperty( getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id") && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) { System.out .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName())); PostHarvestNode.setProperty( getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } } PostHarvestParent = ParentNode.PostHarvestParentNode(); PostHarvestParent.createRelationshipTo(PostHarvestNode, ICTCRelationshipTypes.POST_HARVEST); log.log(Level.INFO, "new node created {0}", PostHarvestNode.getId()); Biodata b = biodataModel.getBiodata("Id", farmerID); biodataModel.BiodataToPostHarvest(b.getId(), PostHarvestNode); tx.success(); out.println(sendAck()); } else if (salesforceObj.equals("sf:Storage__c")) { org.neo4j.graphdb.Node StorageParent; org.neo4j.graphdb.Node StorageNode = ICTCDBUtil.getInstance().getGraphDB() .createNode(Labels.STORAGE); String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele); System.out.println("farmerid " + farmerID); for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) { System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent()); if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) { System.out.println( "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName())); StorageNode.setProperty( getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id") && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) { System.out .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName())); StorageNode.setProperty( getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } } StorageParent = ParentNode.StorageParentNode(); StorageParent.createRelationshipTo(StorageNode, ICTCRelationshipTypes.STORAGE); log.log(Level.INFO, "new node created {0}", StorageNode.getId()); Biodata b = biodataModel.getBiodata("Id", farmerID); biodataModel.BiodataToStorage(b.getId(), StorageNode); tx.success(); out.println(sendAck()); } else if (salesforceObj.equals("sf:TechnicalNeeds__c")) { org.neo4j.graphdb.Node TNParent; org.neo4j.graphdb.Node TNNode = ICTCDBUtil.getInstance().getGraphDB() .createNode(Labels.TECHNICAL_NEEDS); String farmerID = getXmlNodeValue("sf:Farmer_Biodata__c", ele); System.out.println("farmerid " + farmerID); for (int k = 0; k < rowNode.getChildNodes().getLength(); k++) { System.out.println("node: " + rowNode.getChildNodes().item(k).getNodeName() + ": " + rowNode.getChildNodes().item(k).getTextContent()); if (rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id")) { System.out.println( "id : " + getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName())); TNNode.setProperty(getObjectFieldId(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } if (!rowNode.getChildNodes().item(k).getNodeName().equals("sf:Id") && !rowNode.getChildNodes().item(k).getNodeName().equals("#text") && !rowNode .getChildNodes().item(k).getNodeName().equals("sf:Farmer_Biodata__c")) { System.out .println(getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName())); TNNode.setProperty( getObjectFieldName(rowNode.getChildNodes().item(k).getNodeName()), rowNode.getChildNodes().item(k).getTextContent()); } } TNParent = ParentNode.TechNeedParentNode(); TNParent.createRelationshipTo(TNNode, ICTCRelationshipTypes.TECHNICAL_NEED); log.log(Level.INFO, "new node created {0}", TNNode.getId()); Biodata b = biodataModel.getBiodata("Id", farmerID); biodataModel.BiodataToTechNeeds(b.getId(), TNNode); tx.success(); out.println(sendAck()); } } } catch (Exception ex) { Logger.getLogger(SaleforceIntegrationController.class.getName()).log(Level.SEVERE, null, ex); tx.failure(); } finally { tx.finish(); } } }