/** * Format of a proper get request: <uid>(assessmentUID)</uid> * * <p>or * * <p><taxon>(taxonID)</taxon> * * <p>If the type parameter is null for the latter format, all . * * @param getEntity * @param type * @return */ private String getAssessments(Request request, String user) throws IOException { String type = (String) request.getAttributes().get("type"); Document doc = new DomRepresentation(request.getEntity()).getDocument(); StringBuilder ret = new StringBuilder("<assessments>"); NodeCollection uidNodes = new NodeCollection(doc.getElementsByTagName("uid")); if (uidNodes.size() > 0) { Map<String, List<String>> typeToIDs = new HashMap<String, List<String>>(); for (Node curNode : uidNodes) { String uid = curNode.getTextContent(); int splitIndex = uid.lastIndexOf("_", uid.lastIndexOf("_") - 1); if (splitIndex > 0) { String curType = uid.substring(splitIndex + 1); List<String> typeList = typeToIDs.get(curType); if (typeList == null) { typeList = new ArrayList<String>(); typeToIDs.put(uid.substring(splitIndex + 1), typeList); } typeList.add(uid.substring(0, splitIndex)); } else { System.out.println("Split index for UID " + uid + " is obviously s***e."); } } for (Entry<String, List<String>> curEntry : typeToIDs.entrySet()) for (String curID : curEntry.getValue()) ret.append(AssessmentIO.readAssessmentAsString(vfs, curID, curEntry.getKey(), user)); } NodeCollection taxaNodes = new NodeCollection(doc.getElementsByTagName("taxon")); if (taxaNodes.size() > 0) { for (Node curNode : taxaNodes) { String taxonID = curNode.getTextContent(); if (type == null) for (String cur : AssessmentIO.readAllAssessmentsForTaxonAsStrings(vfs, taxonID, user)) ret.append(cur); else if (type.equals(BaseAssessment.DRAFT_ASSESSMENT_STATUS)) for (String cur : AssessmentIO.readAllDraftAssessmentsAsStrings(vfs, taxonID)) ret.append(cur); else if (type.equals(BaseAssessment.PUBLISHED_ASSESSMENT_STATUS)) for (String cur : AssessmentIO.readPublishedAssessmentsForTaxonAsStrings(vfs, taxonID)) ret.append(cur); } } ret.append("</assessments>"); return ret.toString(); }
private void putAssessment(Request request, Response response, String username) { try { NativeDocument doc = NativeDocumentFactory.newNativeDocument(); doc.parse(request.getEntity().getText()); AssessmentParser parser = new AssessmentParser(doc); AssessmentData assessment = parser.getAssessment(); AssessmentIOWriteResult result = assignIDAndSave(assessment, username); if (result.status.isSuccess()) { response.setEntity(assessment.getAssessmentID(), MediaType.TEXT_PLAIN); response.setStatus(Status.SUCCESS_OK); } else { response.setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED); } } catch (RegionConflictException e) { response.setStatus(Status.CLIENT_ERROR_CONFLICT); } catch (Exception e) { response.setStatus(Status.SERVER_ERROR_INTERNAL); } }
private void postAssessment(Request request, Response response, String username) { try { String entity = request.getEntity().getText(); NativeDocument doc = NativeDocumentFactory.newNativeDocument(); doc.parse(entity); AssessmentParser parser = new AssessmentParser(doc); AssessmentData assessment = parser.getAssessment(); VFSPath assessmentUrl = new VFSPath(ServerPaths.getPathForAssessment(assessment, username)); if (vfs.exists(assessmentUrl)) { Status status = FileLocker.impl.persistentLockAssessment( assessment.getAssessmentID(), BaseAssessment.DRAFT_ASSESSMENT_STATUS, LockType.SAVE_LOCK, username); if (status.isSuccess()) { AssessmentIOWriteResult result = saveAssessment(assessment, username); if (result.status.isSuccess()) { response.setEntity(result.newLastModified + "", MediaType.TEXT_PLAIN); response.setStatus(status); } else { response.setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED); } } else { response.setStatus(status); } } } catch (RegionConflictException e) { response.setStatus(Status.CLIENT_ERROR_CONFLICT); } catch (Exception e) { e.printStackTrace(); response.setStatus(Status.CLIENT_ERROR_BAD_REQUEST); } }
/** * Method responsible for handling incoming POSTs. It will parse the XML document and deserialize * it into a SeedRequest, then create a SeedTask and forward it to the thread pool executor. */ public void doPost(Request req, Response resp) throws RestletException, IOException { String formatExtension = (String) req.getAttributes().get("extension"); SeedRequest sr = null; XStream xs = xmlConfig.getConfiguredXStream(new XStream(new DomDriver())); try { if (formatExtension.equalsIgnoreCase("xml")) { String xml_body = req.getEntity().getText(); log.debug("doPost, xml = " + xml_body); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); ByteArrayInputStream xml_bs = new ByteArrayInputStream(xml_body.getBytes()); Document doc = db.parse(xml_bs); Node rootNode = doc.getFirstChild(); xs.alias("seedRequest", SeedRequest.class); sr = (SeedRequest) xs.unmarshal(new DomReader((Element) rootNode)); log.debug("doPost, sr = " + sr.getLayerName()); } else if (formatExtension.equalsIgnoreCase("json")) { sr = (SeedRequest) xs.fromXML(convertJson(req.getEntity().getText())); } else { throw new RestletException( "Format extension unknown or not specified: " + formatExtension, Status.CLIENT_ERROR_BAD_REQUEST); } } catch (Exception e) { log.error("Exception type = " + e.getClass().getName() + " msg = " + e.getMessage()); e.printStackTrace(); if (e.getCause() != null) { log.error("cause = " + e.getCause().getMessage()); } } StringBuilder strBld = new StringBuilder(); strBld.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); String layerName = null; try { layerName = URLDecoder.decode((String) req.getAttributes().get("layer"), "UTF-8"); } catch (UnsupportedEncodingException uee) { log.error("Exception type = " + uee.getClass().getName() + " msg = " + uee.getMessage()); throw new RestletException(uee.getMessage(), Status.SERVER_ERROR_INTERNAL); } log.debug( "layerName = " + layerName + " sr.GridSetId = " + sr.getGridSetId() + " type = " + sr.getType()); GWCTask[] tasks = null; try { TileLayer tl = null; try { tl = seeder.findTileLayer(layerName); } catch (GeoWebCacheException e) { strBld.append("<GeoWebCacheException>"); strBld.append(e.getMessage()); strBld.append("</GeoWebCacheException>"); resp.setEntity(strBld.toString(), MediaType.TEXT_XML); throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL); } TileRange tr = TileBreeder.createTileRange(sr, tl); tasks = seeder.createTasks(tr, tl, sr.getType(), sr.getThreadCount(), sr.getFilterUpdate()); seeder.dispatchTasks(tasks); // Give the thread executor a chance to run try { Thread.sleep(500); } catch (InterruptedException e) { // Ok, no worries } } catch (IllegalArgumentException e) { log.error("IllegalArgumentException occured: " + e.getMessage()); throw new RestletException(e.getMessage(), Status.CLIENT_ERROR_BAD_REQUEST); } catch (GeoWebCacheException e) { log.error("GeoWebCacheException occured: " + e.getMessage()); throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL); } strBld.append("<Tasks>"); if (tasks.length == 0) { log.debug("No running tasks"); } for (int i = 0; i < tasks.length; i++) { if (i > 0) { strBld.append(","); } strBld.append(tasks[i].getDbId()); } strBld.append("</Tasks>\n"); log.debug("post response = " + strBld.toString()); resp.setEntity(strBld.toString(), MediaType.TEXT_XML); }
/** * Sends the request to the client. Commits the request line, headers and optional entity and send * them over the network. * * @param request The high-level request. * @return The result status. */ @Override public Status sendRequest(Request request) { Status result = null; try { final Representation entity = request.getEntity(); // Set the request headers for (final Parameter header : getRequestHeaders()) { getHttpMethod().addRequestHeader(header.getName(), header.getValue()); } // For those method that accept enclosing entites, provide it if ((entity != null) && (getHttpMethod() instanceof EntityEnclosingMethod)) { final EntityEnclosingMethod eem = (EntityEnclosingMethod) getHttpMethod(); eem.setRequestEntity( new RequestEntity() { public long getContentLength() { return entity.getSize(); } public String getContentType() { return (entity.getMediaType() != null) ? entity.getMediaType().toString() : null; } public boolean isRepeatable() { return !entity.isTransient(); } public void writeRequest(OutputStream os) throws IOException { entity.write(os); } }); } // Ensure that the connection is active this.clientHelper.getHttpClient().executeMethod(getHttpMethod()); // Now we can access the status code, this MUST happen after closing // any open request stream. result = new Status(getStatusCode(), null, getReasonPhrase(), null); // If there is no response body, immediately release the connection if (getHttpMethod().getResponseBodyAsStream() == null) { getHttpMethod().releaseConnection(); } } catch (IOException ioe) { this.clientHelper .getLogger() .log( Level.WARNING, "An error occurred during the communication with the remote HTTP server.", ioe); result = new Status(Status.CONNECTOR_ERROR_COMMUNICATION, ioe); // Release the connection getHttpMethod().releaseConnection(); } return result; }
private String batchCreate(Request request, String username) { NativeDocument doc = NativeDocumentFactory.newNativeDocument(); StringBuffer successfulIDs = new StringBuffer(); StringBuffer extantIDs = new StringBuffer(); StringBuffer unsuccessfulIDs = new StringBuffer(); try { String text = request.getEntity().getText(); doc.parse(text); AssessmentFilter filter = AssessmentFilter.parseXML( doc.getDocumentElement() .getElementsByTagName(AssessmentFilter.HEAD_TAG) .elementAt(0)); NativeNodeList nodes = doc.getDocumentElement().getElementsByTagName("taxon"); boolean useTemplate = Boolean.parseBoolean( doc.getDocumentElement() .getElementsByTagName("useTemplate") .elementAt(0) .getTextContent()); System.out.println("Using template? " + useTemplate); for (int i = 0; i < nodes.getLength(); i++) { TaxonNode taxon = TaxaIO.readNode(nodes.elementAt(i).getTextContent(), vfs); AssessmentData curAss = null; curAss = doCreateAssessmentForBatch( request.getChallengeResponse().getIdentifier(), filter, useTemplate, taxon); try { AssessmentIOWriteResult result = assignIDAndSave(curAss, username); if (result.status.isSuccess()) successfulIDs.append( curAss.getSpeciesName() + (i == nodes.getLength() - 1 ? "" : ", ")); else unsuccessfulIDs.append( curAss.getSpeciesName() + (i == nodes.getLength() - 1 ? "" : ", ")); } catch (RegionConflictException e) { extantIDs.append(curAss.getSpeciesName() + (i == nodes.getLength() - 1 ? "" : ", ")); } } StringBuilder ret = new StringBuilder(); if (unsuccessfulIDs.length() > 0) ret.append( "<div>Unable to create an assessment for the following species: " + unsuccessfulIDs + "</div>\r\n"); if (extantIDs.length() > 0) ret.append( "<div>The following species already have draft assessments with the specific locality: " + extantIDs + "</div>\r\n"); if (successfulIDs.length() > 0) ret.append( "<div>Successfully created an assessment for the following species: " + successfulIDs + "</div>\r\n"); return ret.toString(); } catch (IOException e) { e.printStackTrace(); return null; } catch (NullPointerException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } }