List of usage examples for java.lang StringBuffer delete
@Override public synchronized StringBuffer delete(int start, int end)
From source file:com.gst.portfolio.group.service.GroupReadPlatformServiceImpl.java
private String getGroupExtraCriteria(final SearchParameters searchCriteria) { StringBuffer extraCriteria = new StringBuffer(200); extraCriteria.append(" and g.level_Id = ").append(GroupTypes.GROUP.getId()); String sqlSearch = searchCriteria.getSqlSearch(); if (sqlSearch != null) { sqlSearch = sqlSearch.replaceAll(" display_name ", " g.display_name "); sqlSearch = sqlSearch.replaceAll("display_name ", "g.display_name "); extraCriteria.append(" and ( ").append(sqlSearch).append(") "); }// w w w .ja v a2s. c o m final Long officeId = searchCriteria.getOfficeId(); if (officeId != null) { extraCriteria.append(" and g.office_id = ").append(officeId); } final String externalId = searchCriteria.getExternalId(); if (externalId != null) { extraCriteria.append(" and g.external_id = ").append(ApiParameterHelper.sqlEncodeString(externalId)); } final String name = searchCriteria.getName(); if (name != null) { extraCriteria.append(" and g.display_name like ") .append(ApiParameterHelper.sqlEncodeString("%" + name + "%")); } final String hierarchy = searchCriteria.getHierarchy(); if (hierarchy != null) { extraCriteria.append(" and o.hierarchy like ") .append(ApiParameterHelper.sqlEncodeString(hierarchy + "%")); } if (searchCriteria.isStaffIdPassed()) { extraCriteria.append(" and g.staff_id = ").append(searchCriteria.getStaffId()); } if (StringUtils.isNotBlank(extraCriteria.toString())) { extraCriteria.delete(0, 4); } final Long staffId = searchCriteria.getStaffId(); if (staffId != null) { extraCriteria.append(" and g.staff_id = ").append(staffId); } if (searchCriteria.isOrphansOnly()) { extraCriteria.append(" and g.parent_id IS NULL"); } return extraCriteria.toString(); }
From source file:dao.DirectoryStreamBlobDaoDb.java
/** * Deletes stream Blob //from w w w . j a v a2 s .c o m * @param entryid - entryid * @param userId - userId * @param directoryId - directoryId * @param userLogin - userLogin * @param dirPath - directory path * @param dirName - directory name * @param btitle - blob title * @return none */ public void deleteStreamBlob(String entryid, String userId, String directoryId, String userLogin, String dirPath, String dirName, String btitle) { if (RegexStrUtil.isNull(userId)) { throw new BaseDaoException("params are null"); } if (!isAuthor(directoryId, userId) && !diaryAdmin.isDiaryAdmin(userLogin)) { throw new BaseDaoException("user does not have permission to delete blob for directory " + directoryId + " userId " + userId); } /** * Get scalability datasource for dirblob - partitioned on directoryId */ String sourceName = scalabilityManager.getWriteBlobScalability(directoryId); ds = scalabilityManager.getSource(sourceName); if (ds == null) { throw new BaseDaoException("ds null, deleteStreamBlob " + sourceName); } boolean exists = false; String defId = null; try { Object[] params = { (Object) directoryId }; List result = defaultQuery.execute(params); if (result != null && result.size() > 0) { defId = ((Photo) result.get(0)).getValue(DbConstants.ENTRYID); if (!RegexStrUtil.isNull(defId) && defId.equals(entryid)) { exists = true; } } } catch (Exception e) { throw new BaseDaoException("error " + e.getMessage() + defaultQuery.getSql()); } if (exists) { Connection conn = null; try { conn = ds.getConnection(); deleteDefaultQuery.run(conn, directoryId); } catch (Exception e) { try { if (conn != null) { conn.close(); } } catch (Exception e1) { throw new BaseDaoException( "conn.close() error in deleteDefaultQuery for stream blob in directory = " + directoryId + e.getMessage(), e1); } throw new BaseDaoException( "error deleteDefaultQuery for stream blob in directory = " + directoryId + e.getMessage(), e); } /** * conn.close for default blob */ try { if (conn != null) { conn.close(); } } catch (Exception e) { throw new BaseDaoException( "conn.close() error in deleteDefaultQuery for stream blob in directory = " + directoryId + e.getMessage(), e); } } /** * delete stream blob */ try { if (WebUtil.isSanEnabled()) { SanUtils sanUtils = new SanUtils(); sanUtils.deleteSanFile(dirPath, dirName, btitle, SanConstants.sanPath); } deletestreamblobQuery.run(entryid); } catch (Exception e) { throw new BaseDaoException("exception for deleting a blob() " + deletestreamblobQuery.getSql(), e); } deleteDirImage(directoryId, entryid); /** * generate a key for the directory stream blob (directoryId + entryid) * remove blobstream of directory, from cache * DIR_STREAM_BLOB - with blob data, DIR_PHOTO without the blob data */ Fqn fqn = cacheUtil.fqn(DbConstants.DIR_STREAM_BLOB); StringBuffer sb = new StringBuffer(directoryId); sb.append("-"); sb.append(entryid); String key = sb.toString(); if (treeCache.exists(fqn, key)) { treeCache.remove(fqn, key); } fqn = cacheUtil.fqn(DbConstants.DIR_PHOTO); if (treeCache.exists(fqn, key)) { treeCache.remove(fqn, key); } fqn = cacheUtil.fqn(DbConstants.RECENT_DIR_IMAGES); if (treeCache.exists(fqn, DbConstants.RECENT_DIR_IMAGES)) { treeCache.remove(fqn, DbConstants.RECENT_DIR_IMAGES); } /** remove the existing default photo from cache */ sb.delete(0, sb.length()); sb.append(directoryId); sb.append("-"); sb.append(defId); key = sb.toString(); if (treeCache.exists(fqn, key)) { treeCache.remove(fqn, key); } fqn = cacheUtil.fqn(DbConstants.DIRECTORY_STREAM_BLOBS); if (treeCache.exists(fqn, directoryId)) { treeCache.remove(fqn, directoryId); } sb.delete(0, sb.length()); sb.append(directoryId); sb.append("-"); sb.append(DbConstants.PHOTO_CATEGORY); fqn = cacheUtil.fqn(DbConstants.DIR_CAT); if (treeCache.exists(fqn, sb.toString())) { treeCache.remove(fqn, sb.toString()); } sb.delete(0, sb.length()); sb.append(directoryId); sb.append("-"); sb.append(DbConstants.FILE_CATEGORY); fqn = cacheUtil.fqn(DbConstants.DIR_CAT); if (treeCache.exists(fqn, sb.toString())) { treeCache.remove(fqn, sb.toString()); } fqn = cacheUtil.fqn(DbConstants.DIRECTORY); if (treeCache.exists(fqn, directoryId)) { treeCache.remove(fqn, directoryId); } }
From source file:org.blackdog.lyrics.type.LeoLyrics.java
/** return the page containing the result of the search * @param searchArtist true to search for artist * @param artistTokens a list of String representing the critera for artist * @param searchSong true to search for song * @param songTokens a list of String representing the critera for the song * @return the id of the page containing the lyrics of the first candidate or null if not found */// ww w . jav a2s.c o m private String getResultPage(boolean searchArtist, List<String> artistTokens, boolean searchSong, List<String> songTokens) throws HttpException, IOException { String id = null; if ((searchArtist || searchSong) && ((artistTokens == null ? false : artistTokens.size() > 0) || (songTokens == null ? false : songTokens.size() > 0))) { HttpClient client = new HttpClient(); StringBuffer uri = new StringBuffer(); // create uri : http://www.leoslyrics.com/search.php?search=zero+smashing&sartist=1&ssongtitle=1 uri.append(LEO_URL + SEARCH_SUFFIX); boolean tokenAddedForSong = false; if (searchSong && songTokens != null) { for (int i = 0; i < songTokens.size(); i++) { String currentToken = songTokens.get(i); if (currentToken != null) { currentToken = currentToken.trim(); if (currentToken.length() > 0) { if (tokenAddedForSong) { uri.append("+"); } uri.append(currentToken); tokenAddedForSong = true; } } } } if (searchSong && artistTokens != null) { for (int i = 0; i < artistTokens.size(); i++) { String currentToken = artistTokens.get(i); if (currentToken != null) { currentToken = currentToken.trim(); if (currentToken.length() > 0) { if (tokenAddedForSong) { uri.append("+"); } uri.append(currentToken); tokenAddedForSong = true; } } } } if (searchArtist) { uri.append("&"); uri.append("sartist=1"); } if (searchSong) { uri.append("&"); uri.append("ssongtitle=1"); } logger.info("leo lyrics request : " + uri); GetMethod method = new GetMethod(uri.toString()); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(5, false)); try { int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { InputStream stream = method.getResponseBodyAsStream(); if (stream != null) { /* search first occurrence of '?hid=' */ String hidString = "?hid="; StringBuffer bufferId = new StringBuffer(); StringBuffer bufferTmp = new StringBuffer(hidString.length()); boolean idFound = false; byte[] buffer = new byte[128]; try { int byteRead = stream.read(buffer); while (byteRead != -1) { if (!idFound) { for (int i = 0; i < byteRead; i++) { byte b = buffer[i]; if (!idFound) { if (bufferTmp.length() >= hidString.length()) { if (b != '"') { bufferId.append((char) b); } else { idFound = true; } } else { if (b == hidString.charAt(bufferTmp.length())) { bufferTmp.append((char) b); } else if (bufferTmp.length() > 0) { bufferTmp.delete(0, bufferTmp.length() - 1); } } } } } byteRead = stream.read(buffer); } } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { logger.warn("unable to close the input stream from request " + uri, e); } } } if (bufferId.length() > 0) { id = bufferId.toString(); } } } else { logger.error("getting error while trying to connect to : " + uri + " (error code=" + statusCode + ")"); } } finally { method.releaseConnection(); } } return id; }
From source file:util.FoursquareAPI_backup.java
/** * Command-line interface for the sample Yelp API runner. *///from w w w . j a v a 2s.co m /*private static class YelpAPICLI { //@Parameter(names = {"-q", "--term"}, description = "Search Query Term") //public String term = DEFAULT_TERM; //http://api.yelp.com/v2/search?term=german+food&location=Hayes&cll=37.77493,-122.419415 //cll=latitude,longitude //@Parameter(names = {"-l", "--location"}, description = "Location to be Queried") @Parameter(names = {"-l", "--location"}, description = "Location to be Queried") public String location = DEFAULT_LOCATION; } */ //http://maps.googleapis.com/maps/api/geocode/json?latlng=-9.56189,113.15437&sensor=true //http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=-26.929948,142.401002 public JSONObject searchGoogleMap(String term, double latitude, double longitude) { try { //OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.foursquare.com/v2/venues/search"); int len = Google_htp.length(); Google_htp.append(latitude); Google_htp.append(','); Google_htp.append(longitude); int len1 = Google_htp.length(); //String contents = java.net.URL(); URL url = new URL(Google_htp.toString()); Google_htp.delete(len, len1); URLConnection con = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String input = null; boolean Begin_City = false; int number = 0; JSONObject list1 = new JSONObject(); StringBuffer SaveString = new StringBuffer(); while ((input = br.readLine()) != null) { String[] tempS = input.split(":"); if (Begin_City) { if (tempS[0].contains("short_name")) { SaveString.append(tempS[1].trim()); } if (tempS[0].contains("types")) { String tempType = tempS[1].trim(); if (tempType.length() < 3) { if (tempS.length < 3) { SaveString.setLength(0); continue; } tempType = tempS[2].trim(); } int loc = 1; do { loc = -1; for (int i = 0; i < SaveString.length(); i++) switch (SaveString.charAt(i)) { case '\"': case ',': case ':': loc = i; break; } if (loc >= 0) SaveString.delete(loc, loc + 1); } while (loc >= 0); if (tempType.contains("postal_code")) { list1.put("post_code", SaveString.toString()); number++; } else if (tempType.contains("administrative_area_level_1")) { list1.put("state_code", SaveString.toString()); number++; } else if (tempType.contains("country")) { list1.put("country_code", SaveString.toString()); number++; } else if (tempType.contains("locality")) { list1.put("city_name", SaveString.toString()); number++; } // else // System.out.println(tempType+":"+SaveString.toString()); SaveString.setLength(0); } } if (tempS[0].contains("address_components")) { if (Begin_City) break; Begin_City = true; } } br.close(); return list1; } catch (IOException ex) { Logger.getLogger(FoursquareAPI_backup.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:analytics.storage.store2csv.java
@Override public void storeElementValueData(HashMap<String, Integer> data, String metricName, String dataProvider, String analysisType, String headerColumn, String element, Logger logger, int time) { // TODO Auto-generated method stub String sFileName = dataProvider + analysisType + ".csv"; Properties props = new Properties(); try {/*from w w w. ja va 2s.com*/ props.load(new FileInputStream("configure.properties")); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); System.exit(-1); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); System.exit(-1); } ; File anls = new File(props.getProperty(AnalyticsConstants.resultsPath) + "Analysis_Results"); if (!anls.exists()) anls.mkdir(); else { // if (temporal == false) { // FileUtils.deleteQuietly(anls); // anls.mkdir(); // } } File dir = new File(anls, dataProvider); if (!dir.exists()) dir.mkdir(); File file = new File(dir, sFileName); FileWriter writer; BufferedWriter bw = null; BufferedReader reader = null; try { if (file.exists() && time == 0) file.delete(); // if (!file.exists() && time == 0) { writer = new FileWriter(file); bw = new BufferedWriter(writer); createHeaders(bw, metricName, headerColumn); Set<String> keySet = data.keySet(); Iterator<String> iterator = keySet.iterator(); StringBuffer logString = new StringBuffer(); StringBuffer key = new StringBuffer(); while (iterator.hasNext()) { // String key = iterator.next(); key.append(iterator.next()); Integer value = data.get(key.toString()); if (key.toString().contains(",")) key.replace(0, key.length(), key.toString().replace(",", "/")); // key = key.toString().replace(",", "/"); // bw.append(element); // bw.append(','); bw.append(key); logString.append(dataProvider); logString.append(" " + element); logString.append(" " + key.toString().replace(" ", "_")); // logString.append(" " + key.replace(" ", "_")); bw.append(','); bw.append(String.valueOf(value)); logString.append(" " + String.valueOf(value)); bw.newLine(); logger.info(logString.toString()); logString.delete(0, logString.capacity()); key.delete(0, key.length()); } bw.close(); // } else if (file.exists() && time == 0) { // file.delete(); // writer = new FileWriter(file); // bw = new BufferedWriter(writer); // createHeaders(bw, metricName, headerColumn); // // Set<String> keySet = data.keySet(); // Iterator<String> iterator = keySet.iterator(); // StringBuffer logString = new StringBuffer(); // // StringBuffer key = new StringBuffer(); // // while (iterator.hasNext()) { // // String key = iterator.next(); // key.append(iterator.next()); // // Integer value = data.get(key.toString()); // // if (key.toString().contains(",")) // key.replace(0, key.length(), // key.toString().replace(",", "/")); // // key = key.toString().replace(",", "/"); // // // bw.append(element); // // bw.append(','); // bw.append(key); // logString.append(dataProvider); // logString.append(" " + element); // logString.append(" " + key.toString().replace(" ", "_")); // // logString.append(" " + key.replace(" ", "_")); // bw.append(','); // bw.append(String.valueOf(value)); // logString.append(" " + String.valueOf(value)); // bw.newLine(); // // logger.info(logString.toString()); // logString.delete(0, logString.capacity()); // key.delete(0, key.length()); // } // bw.close(); // } else if (file.exists() && time > 0) { // // reader = new BufferedReader(new FileReader(file)); // // File temp = new File(dir, "temp.csv"); // // writer = new FileWriter(temp); // bw = new BufferedWriter(writer); // // String line; // int counter = 0; // // // Set<String> keySet = data.keySet(); // // Iterator<String> iterator = keySet.iterator(); // StringBuffer logString = new StringBuffer(); // StringBuffer key = new StringBuffer(); // while ((line = reader.readLine()) != null) { // String[] split = line.split(","); // // System.out.println(line); // // if (counter == 0) { // line = line + "," + metricName; // bw.append(line); // bw.newLine(); // // } else { // // String key = iterator.next(); // // String key = split[0]; // key.append(split[0]); // Integer value = data.get(key); // // // if (key.contains(",")) // // key = key.replace(",", "/"); // if (key.toString().contains(",")) // key.replace(0, key.length(), key.toString() // .replace(",", "/")); // // line = line + "," + value; // bw.append(line); // logString.append(dataProvider); // logString.append(" " + element); // logString // .append(" " + key.toString().replace(" ", "_")); // logString.append(" " + value); // // bw.newLine(); // // logger.info(logString.toString()); // logString.delete(0, logString.capacity()); // key.delete(0, key.length()); // } // // counter += 1; // // } // bw.close(); // FileUtils.copyFile(temp, file); // temp.delete(); // reader.close(); // // } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (bw != null) bw.close(); if (reader != null) reader.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
From source file:ro.cs.om.web.security.UserAuth.java
/** * Function that truncates the paris of job-departments * //from w w w . ja va 2 s . co m * @author Adelina * * @return */ public String getJobDepartmentPairsTruncate() { logger.debug("getJobDepartmentPairsTruncate - START"); StringBuffer sb = new StringBuffer(); StringBuffer sbNew = new StringBuffer(); String dots = " ..."; int length = 107; Integer personNameLength = getFirstName().length() + getLastName().length() + 2; if (deptWithJob == null) { logger.debug("getJobDepartmentPairsTruncate - END"); return "-"; } else { int i = 0; boolean hasMoreJobs = false; Set<Department> departments = deptWithJob.keySet(); if (departments != null && departments.size() > 0) { Iterator<Department> iter = departments.iterator(); while (iter.hasNext()) { i++; if (i > 1) { hasMoreJobs = true; break; } Department dept = iter.next(); sb.append(deptWithJob.get(dept).getName().concat(" - ").concat(dept.getName())); String jobDeptPair = deptWithJob.get(dept).getName().concat(" - ").concat(dept.getName()); int remainingCharacters = length - personNameLength; if (remainingCharacters - jobDeptPair.length() < 0) { sbNew = sb.delete(length - dots.length(), jobDeptPair.length() - 1); sbNew.append(dots); return sbNew.toString(); } } if (hasMoreJobs) { sb.append(dots); } } logger.debug("getJobDepartmentPairsTruncate - END"); return sb.toString(); } }
From source file:util.FoursquareAPI.java
/** * Command-line interface for the sample Yelp API runner. *///from w ww.j av a 2s .co m /*private static class YelpAPICLI { //@Parameter(names = {"-q", "--term"}, description = "Search Query Term") //public String term = DEFAULT_TERM; //http://api.yelp.com/v2/search?term=german+food&location=Hayes&cll=37.77493,-122.419415 //cll=latitude,longitude //@Parameter(names = {"-l", "--location"}, description = "Location to be Queried") @Parameter(names = {"-l", "--location"}, description = "Location to be Queried") public String location = DEFAULT_LOCATION; } */ //http://maps.googleapis.com/maps/api/geocode/json?latlng=-9.56189,113.15437&sensor=true //http://maps.googleapis.com/maps/api/geocode/json?sensor=true&latlng=-26.929948,142.401002 public JSONObject searchGoogleMap(String term, double latitude, double longitude) { try { //OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.foursquare.com/v2/venues/search"); int len = Google_htp.length(); Google_htp.append("latlng="); Google_htp.append(latitude); Google_htp.append(','); Google_htp.append(longitude); int len1 = Google_htp.length(); //String contents = java.net.URL(); URL url = new URL(Google_htp.toString()); Google_htp.delete(len, len1); URLConnection con = url.openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); String input = null; boolean Begin_City = false; int number = 0; JSONObject list1 = new JSONObject(); StringBuffer SaveString = new StringBuffer(); while ((input = br.readLine()) != null) { String[] tempS = input.split(":"); if (Begin_City) { if (tempS[0].contains("short_name")) { SaveString.append(tempS[1].trim()); } if (tempS[0].contains("types")) { String tempType = tempS[1].trim(); if (tempType.length() < 3) { if (tempS.length < 3) { SaveString.setLength(0); continue; } tempType = tempS[2].trim(); } int loc = 1; do { loc = -1; for (int i = 0; i < SaveString.length(); i++) switch (SaveString.charAt(i)) { case '\"': case ',': case ':': loc = i; break; } if (loc >= 0) SaveString.delete(loc, loc + 1); } while (loc >= 0); if (tempType.contains("postal_code")) { list1.put("post_code", SaveString.toString()); number++; } else if (tempType.contains("administrative_area_level_1")) { list1.put("state_code", SaveString.toString()); number++; } else if (tempType.contains("country")) { list1.put("country_code", SaveString.toString()); number++; } else if (tempType.contains("locality")) { list1.put("city_name", SaveString.toString()); number++; } // else // System.out.println(tempType+":"+SaveString.toString()); SaveString.setLength(0); } } if (tempS[0].contains("address_components")) { if (Begin_City) break; Begin_City = true; } } br.close(); return list1; } catch (IOException ex) { Logger.getLogger(FoursquareAPI.class.getName()).log(Level.SEVERE, null, ex); } return null; }
From source file:com.aliyun.odps.mapred.LocalJobRunner.java
private void printInputOutput() { StringBuffer sb = new StringBuffer(); System.err.println("Inputs:"); TableInfo[] tableInfos = InputUtils.getTables(conf); if (tableInfos != null) { for (TableInfo tableInfo : tableInfos) { if (sb.length() > 0) { sb.append(","); }/*from w w w .j a v a2s. co m*/ if (tableInfo.getProjectName() != null) { sb.append(tableInfo.getProjectName()); } else { sb.append(odps.getDefaultProject()); } sb.append("."); sb.append(tableInfo.getTableName()); String parts = tableInfo.getPartPath(); if (parts != null && !parts.trim().isEmpty()) { sb.append("/"); if (parts.endsWith("/")) { parts = parts.substring(0, parts.length() - 1); } sb.append(parts); } } } if (sb.length() > 0) { System.err.println("\t" + sb.toString()); sb.delete(0, sb.length()); } System.err.println("Outputs:"); tableInfos = OutputUtils.getTables(conf); if (tableInfos != null) { for (TableInfo tableInfo : tableInfos) { if (sb.length() > 0) { sb.append(","); } if (tableInfo.getProjectName() != null) { sb.append(tableInfo.getProjectName()); } else { sb.append(odps.getDefaultProject()); } sb.append("."); sb.append(tableInfo.getTableName()); String parts = tableInfo.getPartPath(); if (parts != null && !parts.trim().isEmpty()) { sb.append("/"); if (parts.endsWith("/")) { parts = parts.substring(0, parts.length() - 1); } sb.append(parts); } } } if (sb.length() > 0) { System.err.println("\t" + sb.toString()); sb.delete(0, sb.length()); } }
From source file:edu.harvard.hul.ois.pds.ws.PDSWebService.java
/** * Process HTTP GET request.// w w w .java2 s .c o m */ public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, FileNotFoundException { HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req); //Get parameters from the URL String sOp = req.getParameter("op"); char op = 'f'; if (sOp != null) { op = sOp.charAt(0); } String uri = req.getRequestURI(); uri = uri.substring(1); String[] uriElements = uri.split("/"); Integer id = null; String action = null; if (uriElements.length > 2) { action = uriElements[1]; if (action.equalsIgnoreCase(API_SEARCH)) //go straight to fts { String docParam; if ((uriElements[2]).equalsIgnoreCase("global")) { docParam = ""; } else { try { id = new Integer(uriElements[2]); } catch (Exception e) { printError(req, res, "Invalid DRS ID", null); return; } docParam = "G=" + id + "&"; } String format = ""; format = req.getParameter("F"); if (format != null) { format = "&F=" + format; } else { format = "&F=M"; } String range = ""; String advparams = ""; range = req.getParameter("B"); if (range != null) { range = "&B=" + range; } else { range = ""; } String dataQualification = ""; dataQualification = req.getParameter("D"); if (dataQualification != null) { dataQualification = "&D=" + dataQualification; } else { dataQualification = ""; } String contextScope = ""; contextScope = req.getParameter("C"); if (contextScope != null) { contextScope = "&C=" + contextScope; } else { contextScope = ""; } String jumplistRefs = ""; jumplistRefs = req.getParameter("J"); if (jumplistRefs != null) { jumplistRefs = "&J=" + jumplistRefs; } else { jumplistRefs = ""; } String lowerDate = ""; lowerDate = req.getParameter("L"); if (lowerDate != null) { lowerDate = "&L=" + lowerDate; } else { lowerDate = ""; } String upperDate = ""; upperDate = req.getParameter("U"); if (upperDate != null) { upperDate = "&U=" + upperDate; } else { upperDate = ""; } String resultsize = ""; resultsize = req.getParameter("P"); if (resultsize != null) { resultsize = "&P=" + resultsize; } else { resultsize = ""; } advparams = resultsize + range + dataQualification + contextScope + jumplistRefs + lowerDate + upperDate; //Log the search page request WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("search"); message.setMessage("Search Request: " + id); logger.info(message); String Query = req.getParameter("Q"); if (Query == null) { Query = ""; } try { String queryString = new String("?" + docParam + "Q=" + Query + format + advparams); wrapper.setAttribute("searchurl", ftsUrl + queryString); RequestDispatcher rd = req.getRequestDispatcher("/api-search.jsp?"); rd.forward(req, res); //res.sendRedirect(ftsUrl+queryString); return; } catch (Exception e) { message = new WebAppLogMessage(req, true); message.setContext("main"); Throwable root = e; if (e instanceof ServletException) { ServletException se = (ServletException) e; Throwable t = se.getRootCause(); if (t != null) { logger.error(message, t); root = t; } else { logger.error(message, se); } } else { logger.error(message, e); } printError(req, res, "PDS-WS Error", root); } } try { id = new Integer(uriElements[2]); } catch (Exception e) { } } if (id == null) { printError(req, res, "Invalid DRS ID", null); return; } String n = req.getParameter("n"); if (n == null) { n = "1"; } else if (n.equals("")) { printError(req, res, "Page not found", null); return; } //Set scaling factors. s overrides imagesize. Image size select //boxes are based on S. String scale = req.getParameter("s"); String imagesize = req.getParameter("imagesize"); if (scale == null || !(scale.equals("2") || scale.equals("4") || scale.equals("6") || scale.equals("8"))) { if (imagesize != null && imagesize.equals("300")) { scale = "8"; } else if (imagesize != null && imagesize.equals("600")) { scale = "6"; } else if (imagesize != null && imagesize.equals("1200")) { scale = "4"; } else if (imagesize != null && imagesize.equals("2400")) { scale = "2"; } else { scale = "4"; } } if (imagesize == null || !(imagesize.equals("300") || imagesize.equals("600") || imagesize.equals("1200") || imagesize.equals("2400"))) { if (scale.equals("2")) { imagesize = "2400"; } else if (scale.equals("4")) { imagesize = "1200"; } else if (scale.equals("6")) { imagesize = "600"; } else if (scale.equals("8")) { imagesize = "300"; } } String jp2Rotate = req.getParameter("rotation"); if (jp2Rotate == null || jp2Rotate.equals("360") || jp2Rotate.equals("-360")) { jp2Rotate = "0"; } else if (jp2Rotate.equals("-90")) { jp2Rotate = "270"; } String jp2x = req.getParameter("jp2x"); if (jp2x == null) { jp2x = "0"; } String jp2y = req.getParameter("jp2y"); if (jp2y == null) { jp2y = "0"; } String jp2Res = req.getParameter("jp2Res"); String bbx1 = req.getParameter("bbx1"); if (bbx1 == null) { bbx1 = "0"; } String bby1 = req.getParameter("bby1"); if (bby1 == null) { bby1 = "0"; } String bbx2 = req.getParameter("bbx2"); if (bbx2 == null) { bbx2 = "0"; } String bby2 = req.getParameter("bby2"); if (bby2 == null) { bby2 = "0"; } String printThumbnails = req.getParameter("printThumbnails"); if (printThumbnails == null) { printThumbnails = "no"; } wrapper.setAttribute("printThumbnails", printThumbnails); //cg debug System.out.println("debug1- imagesize: " + imagesize + " jp2Res: " + jp2Res + " scale: " + scale); String clickX = req.getParameter("thumbnail.x"); if (clickX != null) { wrapper.setAttribute("clickX", clickX); } else { clickX = (String) wrapper.getAttribute("clickX"); } String clickY = req.getParameter("thumbnail.y"); if (clickX != null) { wrapper.setAttribute("clickY", clickY); } else { clickY = (String) wrapper.getAttribute("clickY"); } //cg debug System.out.println("debug1- thumbnail.x: " + clickX); System.out.println("debug1- X: " + req.getParameter("x")); System.out.println("debug1- thumbnail.y: " + clickY); System.out.println("debug1- Y: " + req.getParameter("y")); /********************************************************** * Create new, or use existing Session **********************************************************/ HttpSession session = req.getSession(true); PdsUserState pdsUser = (PdsUserState) session.getAttribute("PdsUser"); CacheItem item = memcache.getObject(pdsUser.getMeta()); InternalMets mets = item.getMets(); //compare request header if-modified-since with METS DRS last modified //TODO This is temporarily disabled to allow crawlers access to updated // content that they may have already indexed /* Date metsLastModified = item.getLastModifiedDate(); try { long header = req.getDateHeader("If-Modified-Since"); if (header > 0) { Date headerDate = new Date(header); if (metsLastModified.before(headerDate)) { res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } } catch (Exception e) { e.printStackTrace(); // we just ignore this } */ //Set the last modified response value //TODO Warning - this causes browsers to have problems refreshing the // navigation tree html. Possibly this can be set for the content and // citation frames? //res.setDateHeader("Last-Modified", metsLastModified.getTime()); /****************************************************************************** * Get the flags for if doing a page number (p) or sequence number(s) page find * If p is null, look up sequence, if it is not null, look up with page number. * if getContentPage returns null, the page does not exist or an invalid number was * entered. ******************************************************************************/ PageDiv pdiv = null; try { String pageMode = req.getParameter("P"); if (pageMode == null || !pageMode.equals("p")) { pageMode = "s"; } //if a page number search trim n if (pageMode.equals("p")) { n = n.replace(']', ' '); n = n.replace('[', ' '); n = n.trim(); } pdiv = mets.getContentPage(n, pageMode); //if pdiv is a jpeg2000 and res is null then calculate default res value //SET DEFAULT SIZE IF RES NOT SET if (jp2Res == null && pdiv.getDefaultImageMimeType().equals("image/jp2")) { //judaica fix int maxJP2sz = getMaxJP2DisplaySize(pdiv.getDefaultImageID()); if ((maxJP2sz > 300) && (maxJP2sz < 600)) { maxJP2sz = 300; scale = "8"; } else if ((maxJP2sz > 600) && (maxJP2sz < 1200)) { maxJP2sz = 600; scale = "6"; } else if ((maxJP2sz > 1200) && (maxJP2sz < 2400)) { maxJP2sz = 1200; scale = "4"; } else if (maxJP2sz > 2400) { maxJP2sz = 2400; scale = "2"; } String origImagesize = imagesize; if (Integer.parseInt(imagesize) > maxJP2sz) { imagesize = Integer.toString(maxJP2sz); } String filepath = getFilePath(pdiv.getDefaultImageID()); Jpeg2000 jp2 = new Jpeg2000(new File(filepath)); int newRes = jp2.findResolutionLevelContainedBy(Integer.parseInt(origImagesize), Integer.parseInt(origImagesize)); //convert Res to a scaling decimal if (newRes == 1) jp2Res = "1"; else if (newRes == 2) jp2Res = ".5"; else if (newRes == 3) jp2Res = ".25"; else if (newRes == 4) jp2Res = ".125"; else if (newRes == 5) jp2Res = ".0625"; else if (newRes > 5) { jp2Res = "0.625"; } //recalculate newRes if judaica maxres has changed //the actual imagesize if (!imagesize.equals(origImagesize)) { int oldImgsize = Integer.parseInt(origImagesize); int newImgsize = Integer.parseInt(imagesize); float factor = (oldImgsize / newImgsize) / 2; System.out.println("new factor: " + Double.toString(factor)); jp2Res = Double.toString(Double.parseDouble(jp2Res) / factor); } //cg debug //System.out.println("debug2- newRes: " + newRes + " jp2Res is now: " + jp2Res + " scale: " + scale ); } if (pdiv != null && pageMode.equals("p")) { n = String.valueOf(pdiv.getOrder()); //to keep n in the address bar current, redirect to new URL with equivalent n value of page number res.sendRedirect(pdsUrl + "/view/" + id + "?n=" + n + "&s=" + scale + (imagesize != null ? "&imagesize=" + imagesize : "") + (jp2Res != null ? "&jp2Res=" + jp2Res : "") + (jp2Rotate != null ? "&rotation=" + jp2Rotate : "")); return; } } catch (Exception e) { WebAppLogMessage message = new WebAppLogMessage(); message.setContext("find page"); message.setMessage("invalid page number"); message.processSessionRequest(req); logger.error(message, e); } if (pdiv == null) { printError(req, res, "Page not found", null); return; } /********************************************************** * Process appropriately based on the op variable. **********************************************************/ try { /************************* * If image is a JP2 and this is not a frame request, figure * out x,y to create bounding box on thumbnail ***********************/ if (pdiv.getDefaultImageMimeType().equals("image/jp2") && (op != OP_CITATION && op != OP_CONTENT && op != OP_NAVIGATION)) { //judaica fix int maxJP2size = getMaxJP2DisplaySize(pdiv.getDefaultImageID()); if ((maxJP2size > 300) && (maxJP2size < 600)) { maxJP2size = 300; scale = "8"; } else if ((maxJP2size > 600) && (maxJP2size < 1200)) { maxJP2size = 600; scale = "6"; } else if ((maxJP2size > 1200) && (maxJP2size < 2400)) { maxJP2size = 1200; scale = "4"; } else if (maxJP2size > 2400) { maxJP2size = 2400; scale = "2"; } if (Integer.parseInt(imagesize) > maxJP2size) { imagesize = Integer.toString(maxJP2size); } String jp2Action = req.getParameter("action"); if (jp2Action == null) { jp2Action = "noaction"; } int vHeight = Integer.parseInt(imagesize); int vWidth = Integer.parseInt(imagesize); double imgres = Double.parseDouble(jp2Res); //int tWidth = Integer.parseInt(req.getParameter("thumbwidth")); //int tHeight = Integer.parseInt(req.getParameter("thumbheight")); String filepath = getFilePath(pdiv.getDefaultImageID()); Coordinate dimension = new Coordinate(); int x = Integer.parseInt(jp2x); int y = Integer.parseInt(jp2y); Jpeg2000 jp2 = new Jpeg2000(new File(filepath)); //String clickX = req.getParameter("thumbnail.x"); //String clickY = req.getParameter("thumbnail.y"); int thumbX = -1; int thumbY = -1; if (clickX != null && clickY != null) { thumbX = Integer.parseInt(clickX); thumbY = Integer.parseInt(clickY); } if (jp2Action.equals("noaction")) { thumbX = 0; thumbY = 0; } else if (jp2Action.equals("jp2pan")) { x = thumbX; y = thumbY; //panThumbnail is passed thumbnail scale coordinates. It returns //thumbnail scale coordinates so the new X and Y do not need to be //extracted from the method return object dimension = UIUtil.panThumbnail(vHeight, vWidth, x, y, imgres, jp2, jp2Rotate); } else if (jp2Action.equals("jp2zoomin")) { dimension = UIUtil.zoom(vHeight, vWidth, x, y, imgres, jp2, true, jp2Rotate); Coordinate c = UIUtil.convertFullSizeCoordate(jp2, dimension.getX(), dimension.getY(), vWidth, vHeight, imgres, jp2Rotate); thumbX = c.getX(); thumbY = c.getY(); } else if (jp2Action.equals("jp2zoomout")) { dimension = UIUtil.zoom(vHeight, vWidth, x, y, imgres, jp2, false, jp2Rotate); Coordinate c = UIUtil.convertFullSizeCoordate(jp2, dimension.getX(), dimension.getY(), vWidth, vHeight, imgres, jp2Rotate); thumbX = c.getX(); thumbY = c.getY(); } else if (jp2Action.equals("jp2resize")) { String pres = req.getParameter("pres"); double pvRes = Double.valueOf(pres); String previousWidth = req.getParameter("pvWidth"); String previousHeight = req.getParameter("pvHeight"); int pvWidth = Integer.parseInt(previousWidth); int pvHeight = Integer.parseInt(previousHeight); dimension = UIUtil.centerOnResize(vHeight, vWidth, pvHeight, pvWidth, pvRes, x, y, imgres, jp2, jp2Rotate); Coordinate c = UIUtil.convertFullSizeCoordate(jp2, dimension.getX(), dimension.getY(), vWidth, vHeight, imgres, jp2Rotate); thumbX = c.getX(); thumbY = c.getY(); } else if (jp2Action.equals("jp2rotate")) { dimension = UIUtil.panThumbnail(vHeight, vWidth, 0, 0, imgres, jp2, jp2Rotate); thumbX = 0; thumbY = 0; } jp2x = String.valueOf(dimension.getX()); jp2y = String.valueOf(dimension.getY()); req.setAttribute("jp2x", jp2x); req.setAttribute("jp2y", jp2y); //set up coordinates to draw bounding box on thumbnail CoordinatePair bbCoors = UIUtil.getBoundingBoxDimensions(jp2, imgres, vWidth, vHeight, thumbX, thumbY, jp2Rotate); bbx1 = Integer.toString(bbCoors.getPoint1().getX()); bby1 = Integer.toString(bbCoors.getPoint1().getY()); bbx2 = Integer.toString(bbCoors.getPoint2().getX()); bby2 = Integer.toString(bbCoors.getPoint2().getY()); } wrapper.setAttribute("cite", mets.getCitationDiv()); wrapper.setAttribute("pdiv", pdiv); /*if(action.equalsIgnoreCase(ACTION_VIEW) || action.equalsIgnoreCase(ACTION_VIEW_TEXT)) { int imageId = pdiv.getDefaultImageID(); wrapper.setAttribute("lastPage",String.valueOf(mets.getCitationDiv().getLastPageNumber())); wrapper.setAttribute("imageId",String.valueOf(imageId)); wrapper.setAttribute("id",id); wrapper.setAttribute("n",n); wrapper.setAttribute("s",scale); wrapper.setAttribute("mime",pdiv.getDefaultImageMimeType()); wrapper.setAttribute("filepath",getFilePath(imageId)); wrapper.setAttribute("idsUrl",idsUrl); wrapper.setAttribute("cache",cache); wrapper.setAttribute("cacheUrl",pdsUrl+cacheUrl); wrapper.setAttribute("jp2Rotate",jp2Rotate); wrapper.setAttribute("jp2Res",jp2Res); wrapper.setAttribute("jp2x",jp2x); wrapper.setAttribute("jp2y",jp2y); wrapper.setAttribute("imagesize",imagesize); wrapper.setAttribute("bbx1",bbx1); wrapper.setAttribute("bby1",bby1); wrapper.setAttribute("bbx2",bbx2); wrapper.setAttribute("bby2",bby2); wrapper.setAttribute("pdsUrl",pdsUrl); wrapper.setAttribute("ids",idsUrl); wrapper.setAttribute("action",action); if (op == OP_CITATION) { if( pdiv.getDefaultImageMimeType().equals("image/jp2") ) { //get max res for biling code wrapper.setAttribute("maxjp2res", Integer.toString(getMaxJP2DisplaySize(pdiv.getDefaultImageID())) ); } RequestDispatcher rd = req.getRequestDispatcher("/citation.jsp?"); rd.forward(req,res); } else if (op == OP_CONTENT) { //get paths of the ocr files ArrayList<String> ocrPaths = new ArrayList<String>(); for(int i=0;i<pdiv.getOcrID().size();i++) { Integer ocr = (Integer) pdiv.getOcrID().get(i); ocrPaths.add(getFilePath(ocr.intValue())); } wrapper.setAttribute("ocrList",ocrPaths); //if image is a tiff, convert to gif if(pdiv.getDefaultImageMimeType().equals("image/tiff")) { String delv = cache + "/" + imageId + "-" + scale + ".gif"; File file = new File (delv); if (!file.exists ()) { Runtime rt = Runtime.getRuntime(); String tiffpath = getFilePath(imageId); String exec = giffy + " id=" + imageId + " path=" + tiffpath.substring(0,tiffpath.lastIndexOf("/")) + " scale=" + scale + " cache=" + cache; Process child = rt.exec (exec); child.waitFor(); child.destroy(); } } wrapper.setAttribute("caption",item.getImageCaption()); RequestDispatcher rd = req.getRequestDispatcher("/content.jsp?"); rd.forward(req,res); } else if (op == OP_NAVIGATION) { String treeIndex = req.getParameter("index"); String treeAction = req.getParameter("treeaction"); if (treeAction != null) { if (treeAction.equalsIgnoreCase("expand")) { pdsUser.setExpandedNodes(id,item.getAllNodesIndices()); } else if (treeAction.equalsIgnoreCase("collapse")) { pdsUser.setExpandedNodes(id,new ArrayList<String>()); } } if(treeIndex != null) { pdsUser.toggleNode(id,treeIndex); } wrapper.setAttribute("pdsUser",pdsUser); wrapper.setAttribute("maxThumbnails", maxThumbnails); //wrapper.setAttribute("toggleIndex",toggleIndex); //wrapper.setAttribute("treeaction",treeAction); RequestDispatcher rd = req.getRequestDispatcher("/navigation.jsp?"); rd.forward(req,res); } else { //Log the frameset request WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("frameset"); message.setMessage("Frameset Request: " + id); logger.info(message); RequestDispatcher rd = req.getRequestDispatcher("/frameset.jsp?"); rd.forward(req,res); } } else if (action.equalsIgnoreCase(ACTION_CITE_INFO)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("fullcitation"); message.setMessage("Full Citation: " + id + " Seq: " + n); logger.info(message); wrapper.setAttribute("cite",mets.getCitationDiv()); wrapper.setAttribute("pdsUrl",pdsUrl); wrapper.setAttribute("id",id); wrapper.setAttribute("nStr", n+""); String repos = pdsUser.getMeta().getOwner(); if (repos == null || repos.equals("")) repos = "Harvard University Library"; String mainUrn = pdsUser.getMeta().getUrn(); String pageUrn = pdsUser.getMeta().getUrnFromList("?n=" +n); SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy"); String accDate = sdf.format(new Date()); wrapper.setAttribute("accDate", accDate); wrapper.setAttribute("repos", repos); wrapper.setAttribute("mainUrn", nrsUrl + "/" +mainUrn); wrapper.setAttribute("pageUrn", nrsUrl + "/" + pageUrn); StringBuffer sb = new StringBuffer(""); getAllSectionLabels(mets.getCitationDiv(), Integer.parseInt(n), sb); sb.delete(0,2); wrapper.setAttribute("sectLabels", sb.toString()); RequestDispatcher rd = req.getRequestDispatcher("/fullcitation.jsp?"); rd.forward(req,res); } else if (action.equalsIgnoreCase(ACTION_SEARCH)) { //Log the search page request WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("search"); message.setMessage("Search Request: " + id); logger.info(message); wrapper.setAttribute("cite",mets.getCitationDiv()); wrapper.setAttribute("ftsUrl",ftsUrl); wrapper.setAttribute("pdsUrl",pdsUrl); wrapper.setAttribute("id",id); RequestDispatcher rd = req.getRequestDispatcher("/search.jsp?"); rd.forward(req,res); } else if (action.equalsIgnoreCase(ACTION_PRINTOPS)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("printops"); message.setMessage("print options: " + id); logger.info(message); wrapper.setAttribute("pdsUrl",pdsUrl); wrapper.setAttribute("id",id); wrapper.setAttribute("n",n); RequestDispatcher rd = req.getRequestDispatcher("/printoptions.jsp?"); rd.forward(req,res); } else if (action.equalsIgnoreCase(ACTION_PRINT)) { } else if (action.equalsIgnoreCase(ACTION_LINKS)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("links"); message.setMessage("display links: " + id); logger.info(message); wrapper.setAttribute("cite",mets.getCitationDiv()); wrapper.setAttribute("id",id); wrapper.setAttribute("pdsUrl",pdsUrl); RequestDispatcher rd = req.getRequestDispatcher("/links.jsp?"); rd.forward(req,res); }*/ //START API CALLS if (action.equalsIgnoreCase(API_VIEW) || action.equalsIgnoreCase(API_VIEW_TEXT)) { //main api function. shows ocr'd pages int imageId = pdiv.getDefaultImageID(); wrapper.setAttribute("lastPage", String.valueOf(mets.getCitationDiv().getLastPageNumber())); wrapper.setAttribute("imageId", String.valueOf(imageId)); wrapper.setAttribute("id", id); wrapper.setAttribute("n", n); wrapper.setAttribute("s", scale); wrapper.setAttribute("mime", pdiv.getDefaultImageMimeType()); wrapper.setAttribute("filepath", getFilePath(imageId)); wrapper.setAttribute("idsUrl", idsUrl); wrapper.setAttribute("cache", cache); wrapper.setAttribute("cacheUrl", pdsUrl + cacheUrl); wrapper.setAttribute("jp2Rotate", jp2Rotate); wrapper.setAttribute("jp2Res", jp2Res); wrapper.setAttribute("jp2x", jp2x); wrapper.setAttribute("jp2y", jp2y); wrapper.setAttribute("imagesize", imagesize); wrapper.setAttribute("bbx1", bbx1); wrapper.setAttribute("bby1", bby1); wrapper.setAttribute("bbx2", bbx2); wrapper.setAttribute("bby2", bby2); wrapper.setAttribute("pdsUrl", pdsUrl); wrapper.setAttribute("ids", idsUrl); wrapper.setAttribute("action", action); //get paths of the ocr files ArrayList<String> ocrPaths = new ArrayList<String>(); for (int i = 0; i < pdiv.getOcrID().size(); i++) { Integer ocr = (Integer) pdiv.getOcrID().get(i); ocrPaths.add(getFilePath(ocr.intValue())); } wrapper.setAttribute("ocrList", ocrPaths); //if image is a tiff, convert to gif if (pdiv.getDefaultImageMimeType().equals("image/tiff")) { String delv = cache + "/" + imageId + "-" + scale + ".gif"; File file = new File(delv); if (!file.exists()) { Runtime rt = Runtime.getRuntime(); String tiffpath = getFilePath(imageId); String exec = giffy + " id=" + imageId + " path=" + tiffpath.substring(0, tiffpath.lastIndexOf("/")) + " scale=" + scale + " cache=" + cache; Process child = rt.exec(exec); child.waitFor(); child.destroy(); } } wrapper.setAttribute("caption", item.getImageCaption()); RequestDispatcher rd = req.getRequestDispatcher("/api-content.jsp?"); rd.forward(req, res); } else if (action.equalsIgnoreCase(API_LINKS)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("links"); message.setMessage("display links: " + id); logger.info(message); wrapper.setAttribute("cite", mets.getCitationDiv()); wrapper.setAttribute("id", id); wrapper.setAttribute("pdsUrl", pdsUrl); wrapper.setAttribute("n", n); RequestDispatcher rd = req.getRequestDispatcher("/api-links.jsp?"); rd.forward(req, res); } else if (action.equalsIgnoreCase(API_CITE_INFO)) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("fullcitation"); message.setMessage("Full Citation: " + id + " Seq: " + n); logger.info(message); wrapper.setAttribute("cite", mets.getCitationDiv()); wrapper.setAttribute("pdsUrl", pdsUrl); wrapper.setAttribute("id", id); wrapper.setAttribute("nStr", n + ""); String repos = pdsUser.getMeta().getOwner(); if (repos == null || repos.equals("")) repos = "Harvard University Library"; String mainUrn = pdsUser.getMeta().getUrn(); String pageUrn = pdsUser.getMeta().getUrnFromList("?n=" + n); SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy"); String accDate = sdf.format(new Date()); wrapper.setAttribute("accDate", accDate); wrapper.setAttribute("repos", repos); wrapper.setAttribute("mainUrn", nrsUrl + "/" + mainUrn); wrapper.setAttribute("pageUrn", nrsUrl + "/" + pageUrn); StringBuffer sb = new StringBuffer(""); getAllSectionLabels(mets.getCitationDiv(), Integer.parseInt(n), sb); sb.delete(0, 2); wrapper.setAttribute("sectLabels", sb.toString()); RequestDispatcher rd = req.getRequestDispatcher("/api-fullcitation.jsp?"); rd.forward(req, res); } else if (action.equalsIgnoreCase(API_DOC_TREE)) { String treeIndex = req.getParameter("index"); String treeAction = req.getParameter("treeaction"); /*if (treeAction != null) { if (treeAction.equalsIgnoreCase("expand")) { pdsUser.setExpandedNodes(id,item.getAllNodesIndices()); } else if (treeAction.equalsIgnoreCase("collapse")) { pdsUser.setExpandedNodes(id,new ArrayList<String>()); } } if(treeIndex != null) { pdsUser.toggleNode(id,treeIndex); }*/ //expand the tree pdsUser.setExpandedNodes(id, item.getAllNodesIndices()); wrapper.setAttribute("pdsUser", pdsUser); wrapper.setAttribute("pdsUrl", pdsUrl); wrapper.setAttribute("cacheUrl", pdsUrl + cacheUrl); wrapper.setAttribute("cache", cache); wrapper.setAttribute("id", id); wrapper.setAttribute("n", n); wrapper.setAttribute("s", scale); wrapper.setAttribute("action", "get"); wrapper.setAttribute("idsUrl", idsUrl); wrapper.setAttribute("maxThumbnails", maxThumbnails); wrapper.setAttribute("jp2Rotate", jp2Rotate); wrapper.setAttribute("jp2x", jp2x); wrapper.setAttribute("jp2y", jp2y); wrapper.setAttribute("caption", item.getImageCaption()); //wrapper.setAttribute("toggleIndex",toggleIndex); //wrapper.setAttribute("treeaction",treeAction); RequestDispatcher rd = req.getRequestDispatcher("/api-navigation.jsp?"); rd.forward(req, res); } //todo? else if (action.equalsIgnoreCase(API_MAX_SECTIONS)) { } else if (action.equalsIgnoreCase(API_MAX_PAGES)) { } else if (action.equalsIgnoreCase(API_MAX_CHAPTERS)) { } } //END MAIN catch (Exception e) { WebAppLogMessage message = new WebAppLogMessage(req, true); message.setContext("main"); Throwable root = e; if (e instanceof ServletException) { ServletException se = (ServletException) e; Throwable t = se.getRootCause(); if (t != null) { logger.error(message, t); root = t; } else { logger.error(message, se); } } else { logger.error(message, e); } printError(req, res, "PDS-WS Error", root); } }
From source file:com.vmware.bdd.manager.ClusterManager.java
private List<String> validateGivenDS(List<String> specifiedDsNames) { List<String> exitsDs = new ArrayList<String>(); Set<String> allDs = clusterConfigMgr.getDatastoreMgr().getAllDatastoreNames(); StringBuffer nonexistentDsNames = new StringBuffer(); for (String dsName : specifiedDsNames) { if (!allDs.contains(dsName)) nonexistentDsNames.append(dsName).append(","); else//from w ww . j ava2 s . c o m exitsDs.add(dsName); } if (nonexistentDsNames.length() > 0) { nonexistentDsNames.delete(nonexistentDsNames.length() - 1, nonexistentDsNames.length()); throw VcProviderException.DATASTORE_NOT_FOUND(nonexistentDsNames.toString()); } return exitsDs; }