List of usage examples for org.joda.time.format DateTimeFormatter parseMillis
public long parseMillis(String text)
From source file:io.prestosql.teradata.functions.TeradataDateFunctions.java
License:Apache License
private static long parseMillis(TimeZoneKey timeZoneKey, Locale locale, Slice dateTime, Slice formatString) { DateTimeFormatter formatter = DATETIME_FORMATTER_CACHE.get(formatString) .withChronology(CHRONOLOGIES[timeZoneKey.getKey()]).withLocale(locale); try {/* w ww . j a v a2s.c om*/ return formatter.parseMillis(dateTime.toString(UTF_8)); } catch (IllegalArgumentException e) { throw new PrestoException(INVALID_FUNCTION_ARGUMENT, e); } }
From source file:org.ecocean.servlet.EncounterForm.java
License:Open Source License
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); HashMap fv = new HashMap(); //IMPORTANT - processingNotes can be used to add notes on data handling (e.g., poorly formatted dates) that can be reconciled later by the reviewer //Example usage: processingNotes.append("<p>Error encountered processing this date submitted by user: "+getVal(fv, "datepicker")+"</p>"); StringBuffer processingNotes = new StringBuffer(); HttpSession session = request.getSession(true); String context = "context0"; context = ServletUtilities.getContext(request); Shepherd myShepherd = new Shepherd(context); myShepherd.setAction("EncounterForm.class"); System.out.println("in context " + context); //request.getSession()getServlet().getServletContext().getRealPath("/")); String rootDir = getServletContext().getRealPath("/"); System.out.println("rootDir=" + rootDir); /*//www. j av a 2 s .c o m Vector<String> fbImages = new Vector<String>(); int fbi = 0; while (request.getParameter("socialphoto_" + fbi) != null) { fbImages.add(request.getParameter("socialphoto_" + fbi)); fbi++; } System.out.println(fbImages); if (fbImages.size() > 0) { FacebookClient fbclient = null; try { fbclient = SocialAuth.getFacebookClient(context); } catch (Exception ex) { System.out.println("SocialAuth.getFacebookClient threw exception " + ex.toString()); } WebContext ctx = new J2EContext(request, response); //String callbackUrl = "http://localhost.wildme.org/a/SocialConnect?type=facebook"; String callbackUrl = "http://" + CommonConfiguration.getURLLocation(request) + "/XXXSocialConnect?type=facebook"; if (request.getParameter("disconnect") != null) callbackUrl += "&disconnect=1"; fbclient.setCallbackUrl(callbackUrl); OAuthCredentials credentials = null; try { credentials = fbclient.getCredentials(ctx); } catch (Exception ex) { System.out.println("caught exception on facebook credentials: " + ex.toString()); } if (credentials != null) { FacebookProfile facebookProfile = fbclient.getUserProfile(credentials, ctx); User fbuser = myShepherd.getUserBySocialId("facebook", facebookProfile.getId()); System.out.println("getId() = " + facebookProfile.getId() + " -> user = " + fbuser); if (fbuser != null) System.out.println("user = " + user.getUsername() + "; fbuser = " + fbuser.getUsername()); if ((fbuser != null) && (fbuser.getUsername().equals(user.getUsername())) && (request.getParameter("disconnect") != null)) { fbuser.unsetSocial("facebook"); //myShepherd.getPM().makePersistent(user); session.setAttribute("message", "disconnected from facebook"); response.sendRedirect("myAccount.jsp"); return; } else if (fbuser != null) { session.setAttribute("error", "looks like this account is already connected to an account"); response.sendRedirect("myAccount.jsp"); return; } else { //lets do this user.setSocial("facebook", facebookProfile.getId()); //myShepherd.getPM().makePersistent(user); session.setAttribute("message", "connected to facebook"); response.sendRedirect("myAccount.jsp"); return; } } else { System.out.println("*** trying redirect?"); try { fbclient.redirect(ctx, false, false); } catch (Exception ex) { System.out.println("caught exception on facebook processing: " + ex.toString()); } return; } } */ //private Map<String, Object> measurements = new HashMap<String, Object>(); //Map<String, Object> metalTags = new HashMap<String, Object>(); /* private String acousticTagSerial = ""; private String acousticTagId = ""; private String satelliteTagSerial = ""; private String satelliteTagArgosPttNumber = ""; private String satelliteTagName = ""; */ //set up for response response.setContentType("text/html"); PrintWriter out = response.getWriter(); boolean locked = false; String fileName = "None"; String username = "None"; String fullPathFilename = ""; boolean fileSuccess = false; //kinda pointless now as we just build sentFiles list now at this point (do file work at end) String doneMessage = ""; List<String> filesOK = new ArrayList<String>(); HashMap<String, String> filesBad = new HashMap<String, String>(); List<FileItem> formFiles = new ArrayList<FileItem>(); List<File> socialFiles = new ArrayList<File>(); //Calendar date = Calendar.getInstance(); long maxSizeMB = CommonConfiguration.getMaxMediaSizeInMegabytes(context); long maxSizeBytes = maxSizeMB * 1048576; if (ServletFileUpload.isMultipartContent(request)) { try { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); upload.setHeaderEncoding("UTF-8"); List<FileItem> multiparts = upload.parseRequest(request); //List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : multiparts) { if (item.isFormField()) { //plain field fv.put(item.getFieldName(), ServletUtilities.preventCrossSiteScriptingAttacks(item.getString("UTF-8").trim())); //TODO do we want trim() here??? -jon //System.out.println("got regular field (" + item.getFieldName() + ")=(" + item.getString("UTF-8") + ")"); } else if (item.getName().startsWith("socialphoto_")) { System.out.println(item.getName() + ": " + item.getString("UTF-8")); } else { //file //System.out.println("content type???? " + item.getContentType()); TODO note, the helpers only check extension if (item.getSize() > maxSizeBytes) { filesBad.put(item.getName(), "file is larger than " + maxSizeMB + "MB"); } else if (myShepherd.isAcceptableImageFile(item.getName()) || myShepherd.isAcceptableVideoFile(item.getName())) { formFiles.add(item); filesOK.add(item.getName()); } else { filesBad.put(item.getName(), "invalid type of file"); } } } doneMessage = "File Uploaded Successfully"; fileSuccess = true; } catch (Exception ex) { doneMessage = "File Upload Failed due to " + ex; } } else { doneMessage = "Sorry this Servlet only handles file upload request"; System.out.println("Not a multi-part form submission!"); } if (fv.get("social_files_id") != null) { System.out.println("BBB: Social_files_id: " + fv.get("social_files_id")); //TODO better checking of files (size, type etc) File socDir = new File( ServletUtilities.dataDir(context, rootDir) + "/social_files/" + fv.get("social_files_id")); for (File sf : socDir.listFiles()) { socialFiles.add(sf); System.out.println("BBB: Adding social file : " + sf.getName()); filesOK.add(sf.getName()); } filesBad = new HashMap<String, String>(); fileSuccess = true; } session.setAttribute("filesOKMessage", (filesOK.isEmpty() ? "none" : Arrays.toString(filesOK.toArray()))); String badmsg = ""; for (String key : filesBad.keySet()) { badmsg += key + " (" + getVal(filesBad, key) + ") "; } if (badmsg.equals("")) { badmsg = "none"; } session.setAttribute("filesBadMessage", badmsg); if (fileSuccess) { //////////////////////////////////////////// START //{submitterID=tomcat, submitterProject=, photographerEmail=, metalTag(left)=, sex=unknown, measurement(weight)=34234, location=, acousticTagId=, behavior=yow behavior..., measurement(weightunits)=kilograms, acousticTagSerial=, photographerName=, lifeStage=sub-adult, submitterAddress=, satelliteTagSerial=, releaseDate=, photographerPhone=, measurement(lengthunits)=meters, measurement(weightsamplingProtocol)=samplingProtocol0, measurement(length)=, submitterOrganization=, photographerAddress=, longitude=, year=2014, lat=, measurement(lengthsamplingProtocol)=samplingProtocol0, submitterEmail=, minutes=00, elevation=, measurement(height)=, measurement(heightsamplingProtocol)=samplingProtocol0, scars=None, submitterPhone=, submitterName=tomcat, hour=-1, livingStatus=alive, depth=, country=, satelliteTagName=Wild Life Computers, metalTag(right)=, month=1, measurement(heightunits)=meters, Submit=Send encounter report, informothers=, day=0, satelliteTagArgosPttNumber=, comments=} //check for spamBots TODO possibly move this to Util for general/global usage? boolean spamBot = false; String[] spamFieldsToCheck = new String[] { "submitterPhone", "submitterName", "photographerName", "photographerPhone", "location", "comments", "behavior" }; StringBuffer spamFields = new StringBuffer(); for (int i = 0; i < spamFieldsToCheck.length; i++) { spamFields.append(getVal(fv, spamFieldsToCheck[i])); } if (spamFields.toString().toLowerCase().indexOf("porn") != -1) { spamBot = true; } if (spamFields.toString().toLowerCase().indexOf("href") != -1) { spamBot = true; } System.out.println("spambot: " + spamBot); //else if(spamFields.toString().toLowerCase().indexOf("[url]")!=-1){spamBot=true;} //else if(spamFields.toString().toLowerCase().indexOf("url=")!=-1){spamBot=true;} //else if(spamFields.toString().toLowerCase().trim().equals("")){spamBot=true;} //else if((theForm.getSubmitterID()!=null)&&(theForm.getSubmitterID().equals("N%2FA"))) {spamBot=true;} String locCode = ""; System.out.println(" **** here is what i think locationID is: " + fv.get("locationID")); if ((fv.get("locationID") != null) && !fv.get("locationID").toString().equals("")) { locCode = fv.get("locationID").toString(); } //see if the location code can be determined and set based on the location String reported else if (fv.get("location") != null) { String locTemp = getVal(fv, "location").toLowerCase(); Properties props = new Properties(); try { props = ShepherdProperties.getProperties("submitActionClass.properties", "", context); Enumeration m_enum = props.propertyNames(); while (m_enum.hasMoreElements()) { String aLocationSnippet = ((String) m_enum.nextElement()).trim(); if (locTemp.indexOf(aLocationSnippet) != -1) { locCode = props.getProperty(aLocationSnippet); } } } catch (Exception props_e) { props_e.printStackTrace(); } } //end else //end location code setter fv.put("locCode", locCode); //TODO this should live somewhere else as constant? (e.g. to build in form as well) String[] scarType = new String[] { "None", "Tail (caudal) fin", "1st dorsal fin", "2nd dorsal fin", "Left pectoral fin", "Right pectoral fin", "Head", "Body" }; int scarNum = -1; try { scarNum = Integer.parseInt(getVal(fv, "scars")); } catch (NumberFormatException e) { scarNum = -1; } if ((scarNum < 0) || (scarNum > 7)) { scarNum = -1; } if (scarNum >= 0) { fv.put("scars", scarType[scarNum]); } //System.out.println("about to do int stuff"); //need some ints for day/month/year/hour (other stuff seems to be strings) int day = 0, month = -1, year = 0, hour = 0; String minutes = ""; //try { day = Integer.parseInt(getVal(fv, "day")); } catch (NumberFormatException e) { day = 0; } //try { month = Integer.parseInt(getVal(fv, "month")); } catch (NumberFormatException e) { month = 0; } //try { year = Integer.parseInt(getVal(fv, "year")); } catch (NumberFormatException e) { year = 0; } //switch to datepicker LocalDateTime dt = new LocalDateTime(); if ((getVal(fv, "datepicker") != null) && (!getVal(fv, "datepicker").trim().equals(""))) { //System.out.println("Trying to read date: "+getVal(fv, "datepicker").replaceAll(" ", "T")); //boolean badDate=false; try { DateTimeFormatter parser1 = ISODateTimeFormat.dateOptionalTimeParser(); LocalDateTime reportedDateTime = new LocalDateTime( parser1.parseMillis(getVal(fv, "datepicker").replaceAll(" ", "T"))); StringTokenizer str = new StringTokenizer(getVal(fv, "datepicker").replaceAll(" ", "T"), "-"); int numTokens = str.countTokens(); if (numTokens >= 1) { //try { year = reportedDateTime.getYear(); if (year > (dt.getYear() + 1)) { //badDate=true; year = 0; throw new Exception( " An unknown exception occurred during date processing in EncounterForm. The user may have input an improper format: " + year + " > " + dt.getYear()); } //} catch (Exception e) { year=-1;} } if (numTokens >= 2) { try { month = reportedDateTime.getMonthOfYear(); } catch (Exception e) { month = -1; } } else { month = -1; } //see if we can get a day, because we do want to support only yyy-MM too if (str.countTokens() >= 3) { try { day = reportedDateTime.getDayOfMonth(); } catch (Exception e) { day = 0; } } else { day = 0; } //see if we can get a time and hour, because we do want to support only yyy-MM too StringTokenizer strTime = new StringTokenizer(getVal(fv, "datepicker").replaceAll(" ", "T"), "T"); if (strTime.countTokens() > 1) { try { hour = reportedDateTime.getHourOfDay(); } catch (Exception e) { hour = -1; } try { minutes = (new Integer(reportedDateTime.getMinuteOfHour()).toString()); } catch (Exception e) { } } else { hour = -1; } //System.out.println("At the end of time processing I see: "+year+"-"+month+"-"+day+" "+hour+":"+minutes); } catch (Exception e) { System.out.println( " An unknown exception occurred during date processing in EncounterForm. The user may have input an improper format."); e.printStackTrace(); processingNotes.append("<p>Error encountered processing this date submitted by user: " + getVal(fv, "datepicker") + "</p>"); } } String guess = "no estimate provided"; if ((fv.get("guess") != null) && !fv.get("guess").toString().equals("")) { guess = fv.get("guess").toString(); } //let's handle genus and species for taxonomy String genus = null; String specificEpithet = null; try { //now we have to break apart genus species if (fv.get("genusSpecies") != null) { StringTokenizer tokenizer = new StringTokenizer(fv.get("genusSpecies").toString(), " "); if (tokenizer.countTokens() >= 2) { genus = tokenizer.nextToken(); //enc.setGenus(tokenizer.nextToken()); specificEpithet = tokenizer.nextToken().replaceAll(",", "").replaceAll("_", " "); //enc.setSpecificEpithet(tokenizer.nextToken().replaceAll(",","").replaceAll("_"," ")); } //handle malformed Genus Species formats else { throw new Exception( "The format of the submitted genusSpecies parameter did not have two tokens delimited by a space (e.g., \"Rhincodon typus\"). The submitted value was: " + fv.get("genusSpecies")); } } } catch (Exception le) { le.printStackTrace(); } System.out.println("about to do enc()"); Encounter enc = new Encounter(day, month, year, hour, minutes, guess, getVal(fv, "location")); boolean llSet = false; //Encounter enc = new Encounter(); //System.out.println("Submission detected date: "+enc.getDate()); String encID = enc.generateEncounterNumber(); if ((fv.get("catalogNumber") != null) && (!fv.get("catalogNumber").toString().trim().equals(""))) { if ((!myShepherd.isEncounter(fv.get("catalogNumber").toString()))) { encID = fv.get("catalogNumber").toString().trim(); } } enc.setEncounterNumber(encID); System.out.println("hey, i think i may have made an encounter, encID=" + encID); System.out.println("enc ?= " + enc.toString()); AssetStore astore = AssetStore.getDefault(myShepherd); ArrayList<Annotation> newAnnotations = new ArrayList<Annotation>(); //for directly uploaded files for (FileItem item : formFiles) { //convert each FileItem into a MediaAsset makeMediaAssetsFromJavaFileItemObject(item, encID, astore, enc, newAnnotations, genus, specificEpithet); } ///////////////////TODO social files also!!! System.out.println("BBB: Checking if we have social files..."); if (socialFiles.size() > 0) { int numSocialFiles = socialFiles.size(); System.out.println("BBB: Trying to persist social files: " + numSocialFiles); DiskFileItemFactory factory = new DiskFileItemFactory(); for (int q = 0; q < numSocialFiles; q++) { File item = socialFiles.get(q); makeMediaAssetsFromJavaFileObject(item, encID, astore, enc, newAnnotations, genus, specificEpithet); } } if (fv.get("mediaAssetSetId") != null) { MediaAssetSet maSet = ((MediaAssetSet) (myShepherd.getPM().getObjectById( myShepherd.getPM().newObjectIdInstance(MediaAssetSet.class, fv.get("mediaAssetSetId")), true))); if ((maSet != null) && (maSet.getMediaAssets() != null) && (maSet.getMediaAssets().size() > 0)) { int num = maSet.getMediaAssets().size(); for (MediaAsset ma : maSet.getMediaAssets()) { newAnnotations.add(new Annotation(Util.taxonomyString(genus, specificEpithet), ma)); } session.setAttribute("filesOKMessage", num + " " + ((num == 1) ? "file" : "files")); } } enc.setAnnotations(newAnnotations); enc.setGenus(genus); enc.setSpecificEpithet(specificEpithet); //User management String subN = getVal(fv, "submitterName"); String subE = getVal(fv, "submitterEmail"); String subO = getVal(fv, "submitterOrganization"); if (Util.stringExists(subO)) enc.setSubmitterOrganization(subO); String subP = getVal(fv, "submitterProject"); if (Util.stringExists(subP)) enc.setSubmitterOrganization(subP); //User user=null; List<User> submitters = new ArrayList<User>(); if ((subE != null) && (!subE.trim().equals(""))) { StringTokenizer str = new StringTokenizer(subE, ","); int numTokens = str.countTokens(); for (int y = 0; y < numTokens; y++) { String tok = str.nextToken().trim(); String hashedTok = ServletUtilities.hashString(tok); if (myShepherd.getUserByHashedEmailAddress(hashedTok) != null) { User user = myShepherd.getUserByHashedEmailAddress(hashedTok); submitters.add(user); } else { User user = new User(tok, Util.generateUUID()); user.setAffiliation(subO); user.setUserProject(subP); if ((numTokens == 1) && (subN != null)) { user.setFullName(subN); } myShepherd.getPM().makePersistent(user); myShepherd.commitDBTransaction(); myShepherd.beginDBTransaction(); submitters.add(user); } } } enc.setSubmitters(submitters); //end submitter-user processing //User management - photographer processing String photoN = getVal(fv, "photographerName"); String photoE = getVal(fv, "photographerEmail"); List<User> photographers = new ArrayList<User>(); if ((photoE != null) && (!photoE.trim().equals(""))) { StringTokenizer str = new StringTokenizer(photoE, ","); int numTokens = str.countTokens(); for (int y = 0; y < numTokens; y++) { String tok = str.nextToken().trim(); if (myShepherd.getUserByEmailAddress(tok.trim()) != null) { User user = myShepherd.getUserByEmailAddress(tok); photographers.add(user); } else { User user = new User(tok, Util.generateUUID()); myShepherd.getPM().makePersistent(user); myShepherd.commitDBTransaction(); myShepherd.beginDBTransaction(); photographers.add(user); } } } enc.setPhotographers(photographers); //end photographer-user processing //User management - informOthers processing String othersString = getVal(fv, "informothers"); List<User> informOthers = new ArrayList<User>(); if ((othersString != null) && (!othersString.trim().equals(""))) { StringTokenizer str = new StringTokenizer(othersString, ","); int numTokens = str.countTokens(); for (int y = 0; y < numTokens; y++) { String tok = str.nextToken().trim(); if (myShepherd.getUserByEmailAddress(tok.trim()) != null) { User user = myShepherd.getUserByEmailAddress(tok); informOthers.add(user); } else { User user = new User(tok, Util.generateUUID()); myShepherd.getPM().makePersistent(user); myShepherd.commitDBTransaction(); myShepherd.beginDBTransaction(); informOthers.add(user); } } } enc.setInformOthers(informOthers); //end informOthers-user processing /* String baseDir = ServletUtilities.dataDir(context, rootDir); ArrayList<SinglePhotoVideo> images = new ArrayList<SinglePhotoVideo>(); for (FileItem item : formFiles) { // this will actually write file to filesystem (or [FUTURE] wherever) // TODO: either (a) undo this if any failure of writing encounter; or (b) dont write til success of enc. try { //SinglePhotoVideo spv = new SinglePhotoVideo(encID, item, context, encDataDir); SinglePhotoVideo spv = new SinglePhotoVideo(enc, item, context, baseDir); //images.add(spv); enc.addSinglePhotoVideo(spv); } catch (Exception ex) { System.out.println("failed to save " + item.toString() + ": " + ex.toString()); } } for (File sf : socialFiles) { File encDir = new File(enc.dir(baseDir)); if (!encDir.exists()) encDir.mkdirs(); File targetFile = new File(encDir, sf.getName()); System.out.println("socialFile copy: " + sf.toString() + " ---> " + targetFile.toString()); Files.copy(sf.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); SinglePhotoVideo spv = new SinglePhotoVideo(encID, targetFile); enc.addSinglePhotoVideo(spv); } */ //now let's add our encounter to the database enc.setComments(getVal(fv, "comments").replaceAll("\n", "<br>")); if (fv.get("releaseDate") != null && fv.get("releaseDate").toString().length() > 0) { String dateFormatPattern = CommonConfiguration.getProperty("releaseDateFormat", context); try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatPattern); enc.setReleaseDate(simpleDateFormat.parse(fv.get("releaseDate").toString()).getTime()); } catch (Exception e) { enc.addComments("<p>Reported release date was problematic: " + fv.get("releaseDate") + "</p>"); } } if (fv.get("behavior") != null && fv.get("behavior").toString().length() > 0) { enc.setBehavior(fv.get("behavior").toString()); } if (fv.get("alternateID") != null && fv.get("alternateID").toString().length() > 0) { enc.setAlternateID(fv.get("alternateID").toString()); } if (fv.get("lifeStage") != null && fv.get("lifeStage").toString().length() > 0) { enc.setLifeStage(fv.get("lifeStage").toString()); } if (fv.get("flukeType") != null && fv.get("flukeType").toString().length() > 0) { System.out.println(" ENCOUNTERFORM:"); System.out.println(" ENCOUNTERFORM:"); System.out.println(" ENCOUNTERFORM:"); String kwName = fv.get("flukeType").toString(); Keyword kw = myShepherd.getOrCreateKeyword(kwName); for (Annotation ann : enc.getAnnotations()) { MediaAsset ma = ann.getMediaAsset(); if (ma != null) { ma.addKeyword(kw); System.out.println("ENCOUNTERFORM: added flukeType keyword to encounter: " + kwName); } } System.out.println(" ENCOUNTERFORM:"); System.out.println(" ENCOUNTERFORM:"); } if (fv.get("manualID") != null && fv.get("manualID").toString().length() > 0) { String indID = fv.get("manualID").toString(); MarkedIndividual ind = myShepherd.getMarkedIndividualQuiet(indID); if (ind == null) { ind = new MarkedIndividual(enc); ind.addName(request, indID); // we don't just create the individual using the encounter+indID bc this request might key the name off of the logged-in user myShepherd.storeNewMarkedIndividual(ind); ind.refreshNamesCache(); System.out.println(" ENCOUNTERFORM: created new individual " + indID); } else { ind.addEncounter(enc); ind.addName(request, indID); // adds the just-entered name to the individual System.out.println(" ENCOUNTERFORM: added enc to individual " + indID); } if (ind != null) enc.setIndividual(ind); enc.setFieldID(indID); } if (fv.get("occurrenceID") != null && fv.get("occurrenceID").toString().length() > 0) { String occID = fv.get("occurrenceID").toString(); enc.setOccurrenceID(occID); Occurrence occ = myShepherd.getOccurrence(occID); if (occ == null) { occ = new Occurrence(occID, enc); myShepherd.storeNewOccurrence(occ); System.out.println(" ENCOUNTERFORM: created new Occurrence " + occID); } else { occ.addEncounter(enc); System.out.println(" ENCOUNTERFORM: added enc to Occurrence " + occID); } } List<MetalTag> metalTags = getMetalTags(fv); for (MetalTag metalTag : metalTags) { enc.addMetalTag(metalTag); } List<Measurement> measurements = getMeasurements(fv, encID, context); for (Measurement measurement : measurements) { enc.setMeasurement(measurement, myShepherd); } enc.setAcousticTag(getAcousticTag(fv)); enc.setSatelliteTag(getSatelliteTag(fv)); enc.setSex(getVal(fv, "sex")); enc.setLivingStatus(getVal(fv, "livingStatus")); if (fv.get("scars") != null) { enc.setDistinguishingScar(fv.get("scars").toString()); } int sizePeriod = 0; if ((fv.get("measureUnits") != null) && fv.get("measureUnits").toString().equals("Feet")) { if ((fv.get("depth") != null) && !fv.get("depth").toString().equals("")) { try { double tempDouble = (new Double(fv.get("depth").toString())).doubleValue() / 3.3; String truncDepth = (new Double(tempDouble)).toString(); sizePeriod = truncDepth.indexOf("."); truncDepth = truncDepth.substring(0, sizePeriod + 2); fv.put("depth", (new Double(truncDepth)).toString()); } catch (java.lang.NumberFormatException nfe) { enc.addComments( "<p>Reported depth was problematic: " + fv.get("depth").toString() + "</p>"); fv.put("depth", ""); } catch (NullPointerException npe) { fv.put("depth", ""); } } System.out.println("depth --> " + fv.get("depth").toString()); if ((fv.get("elevation") != null) && !fv.get("elevation").toString().equals("")) { try { double tempDouble = (new Double(fv.get("elevation").toString())).doubleValue() / 3.3; String truncElev = (new Double(tempDouble)).toString(); //String truncElev = ((new Double(elevation)) / 3.3).toString(); sizePeriod = truncElev.indexOf("."); truncElev = truncElev.substring(0, sizePeriod + 2); fv.put("elevation", (new Double(truncElev)).toString()); } catch (java.lang.NumberFormatException nfe) { enc.addComments("<p>Reported elevation was problematic: " + fv.get("elevation").toString() + "</p>"); fv.put("elevation", ""); } catch (NullPointerException npe) { fv.put("elevation", ""); } } if ((fv.get("size") != null) && !fv.get("size").toString().equals("")) { try { double tempDouble = (new Double(fv.get("size").toString())).doubleValue() / 3.3; String truncSize = (new Double(tempDouble)).toString(); //String truncSize = ((new Double(size)) / 3.3).toString(); sizePeriod = truncSize.indexOf("."); truncSize = truncSize.substring(0, sizePeriod + 2); fv.put("size", (new Double(truncSize)).toString()); } catch (java.lang.NumberFormatException nfe) { enc.addComments("<p>Reported size was problematic: " + fv.get("size").toString() + "</p>"); fv.put("size", ""); } catch (NullPointerException npe) { fv.put("size", ""); } } } //measureUnits if ((fv.get("size") != null) && !fv.get("size").toString().equals("")) { try { enc.setSize(new Double(fv.get("size").toString())); } catch (java.lang.NumberFormatException nfe) { enc.addComments("<p>Reported size was problematic: " + fv.get("size").toString() + "</p>"); fv.put("size", ""); } catch (NullPointerException npe) { fv.put("size", ""); } } if ((fv.get("elevation") != null) && !fv.get("elevation").toString().equals("")) { try { enc.setMaximumElevationInMeters(new Double(fv.get("elevation").toString())); } catch (java.lang.NumberFormatException nfe) { enc.addComments( "<p>Reported elevation was problematic: " + fv.get("elevation").toString() + "</p>"); fv.put("elevatoin", ""); } catch (NullPointerException npe) { fv.put("elevation", ""); } } if ((fv.get("depth") != null) && !fv.get("depth").toString().equals("")) { try { enc.setDepth(new Double(fv.get("depth").toString())); } catch (java.lang.NumberFormatException nfe) { enc.addComments("<p>Reported depth was problematic: " + fv.get("depth").toString() + "</p>"); fv.put("depth", ""); } catch (NullPointerException npe) { fv.put("depth", ""); } } //let's handle the GPS if ((fv.get("lat") != null) && (fv.get("longitude") != null) && !fv.get("lat").toString().equals("") && !fv.get("longitude").toString().equals("")) { //enc.setGPSLatitude(lat + "° " + gpsLatitudeMinutes + "\' " + gpsLatitudeSeconds + "\" " + latDirection); try { double degrees = (new Double(fv.get("lat").toString())).doubleValue(); double position = degrees; /* if (!gpsLatitudeMinutes.equals("")) { double minutes2 = ((new Double(gpsLatitudeMinutes)).doubleValue()) / 60; position += minutes2; } if (!gpsLatitudeSeconds.equals("")) { double seconds2 = ((new Double(gpsLatitudeSeconds)).doubleValue()) / 3600; position += seconds2; } if (latDirection.toLowerCase().equals("south")) { position = position * -1; }*/ enc.setDWCDecimalLatitude(position); double degrees2 = (new Double(fv.get("longitude").toString())).doubleValue(); double position2 = degrees2; enc.setDWCDecimalLongitude(position2); llSet = true; } catch (Exception e) { System.out.println("EncounterSetGPS: problem!"); e.printStackTrace(); } } //enc.setMeasureUnits("Meters"); // enc.setSubmitterPhone(getVal(fv, "submitterPhone")); //enc.setSubmitterAddress(getVal(fv, "submitterAddress")); // enc.setPhotographerPhone(getVal(fv, "photographerPhone")); // enc.setPhotographerAddress(getVal(fv, "photographerAddress")); // enc.setPhotographerName(getVal(fv, "photographerName")); // enc.setPhotographerEmail(getVal(fv, "photographerEmail")); enc.addComments("<p>Submitted on " + (new java.util.Date()).toString() + " from address: " + ServletUtilities.getRemoteHost(request) + "</p>"); //enc.approved = false; enc.addComments(processingNotes.toString()); if (CommonConfiguration.getProperty("encounterState0", context) != null) { enc.setState(CommonConfiguration.getProperty("encounterState0", context)); } if (request.getRemoteUser() != null) { enc.setSubmitterID(request.getRemoteUser()); } else { enc.setSubmitterID("N/A"); } if (!getVal(fv, "locCode").equals("")) { enc.setLocationCode(locCode); } if (!getVal(fv, "country").equals("")) { enc.setCountry(getVal(fv, "country")); } // xxxxxxx //add research team for GAq if (!getVal(fv, "researchTeam").equals("")) { enc.setDynamicProperty("Research Team", (getVal(fv, "researchTeam"))); } if (!getVal(fv, "vessel").equals("")) { enc.setDynamicProperty("Vessel", (getVal(fv, "vessel"))); } if (!getVal(fv, "conditions").equals("")) { enc.setDynamicProperty("Conditions", (getVal(fv, "conditions"))); } if (!getVal(fv, "camera").equals("")) { enc.setDynamicProperty("Camera", (getVal(fv, "camera"))); } if (!getVal(fv, "lens").equals("")) { enc.setDynamicProperty("Lens", (getVal(fv, "lens"))); } if (!getVal(fv, "card").equals("")) { enc.setDynamicProperty("Card", (getVal(fv, "card"))); } if (!getVal(fv, "folder").equals("")) { enc.setDynamicProperty("Folder", (getVal(fv, "folder"))); } if (!getVal(fv, "numberOfBoats").equals("")) { enc.setDynamicProperty("Number of boats", (getVal(fv, "numberOfBoats"))); } if (!getVal(fv, "startTime").equals("")) { enc.setDynamicProperty("Start Time", (getVal(fv, "startTime"))); } if (!getVal(fv, "endTime").equals("")) { enc.setDynamicProperty("End Time", (getVal(fv, "endTime"))); } if (!getVal(fv, "endLongitude").equals("")) { enc.setDynamicProperty("End Longitude", (getVal(fv, "endLongitude"))); } if (!getVal(fv, "endLatitude").equals("")) { enc.setDynamicProperty("End Latitude", (getVal(fv, "endLatitude"))); } if (!getVal(fv, "startLongitude").equals("")) { enc.setDynamicProperty("Start Longitude", (getVal(fv, "startLongitude"))); } if (!getVal(fv, "startLatitude").equals("")) { enc.setDynamicProperty("Start Latitude", (getVal(fv, "startLatitude"))); } if (!getVal(fv, "beginWaypoint").equals("")) { enc.setDynamicProperty("Begin Waypoint", (getVal(fv, "beginWaypoint"))); } if (!getVal(fv, "endWaypoint").equals("")) { enc.setDynamicProperty("End Waypoint", (getVal(fv, "endWaypoint"))); } //xxxxxxxx String guid = CommonConfiguration.getGlobalUniqueIdentifierPrefix(context) + encID; //new additions for DarwinCore enc.setDWCGlobalUniqueIdentifier(guid); enc.setDWCImageURL((request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + encID)); //populate DarwinCore dates DateTimeFormatter fmt = ISODateTimeFormat.date(); String strOutputDateTime = fmt.print(dt); enc.setDWCDateAdded(strOutputDateTime); enc.setDWCDateAdded(new Long(dt.toDateTime().getMillis())); //System.out.println("I set the date as a LONG to: "+enc.getDWCDateAddedLong()); enc.setDWCDateLastModified(strOutputDateTime); //this will try to set from MediaAssetMetadata -- ymmv if (!llSet) enc.setLatLonFromAssets(); if (enc.getYear() < 1) enc.setDateFromAssets(); String newnum = ""; if (!spamBot) { newnum = myShepherd.storeNewEncounter(enc, encID); enc.refreshAssetFormats(myShepherd); //*after* persisting this madness, then lets kick MediaAssets to IA for whatever fate awaits them // note: we dont send Annotations here, as they are always(forever?) trivial annotations, so pretty disposable // might want to set detection status here (on the main thread) for (MediaAsset ma : enc.getMedia()) { ma.setDetectionStatus(IBEISIA.STATUS_INITIATED); } Task parentTask = null; //this is *not* persisted, but only used so intakeMediaAssets will inherit its params if (locCode != null) { parentTask = new Task(); JSONObject tp = new JSONObject(); JSONObject mf = new JSONObject(); mf.put("locationId", locCode); tp.put("matchingSetFilter", mf); parentTask.setParameters(tp); } Task task = org.ecocean.ia.IA.intakeMediaAssets(myShepherd, enc.getMedia(), parentTask); //TODO are they *really* persisted for another thread (queue) myShepherd.storeNewTask(task); Logger log = LoggerFactory.getLogger(EncounterForm.class); log.info("New encounter submission: <a href=\"" + request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + encID + "\">" + encID + "</a>"); System.out.println("ENCOUNTER SAVED???? newnum=" + newnum + "; IA => " + task); org.ecocean.ShepherdPMF.getPMF(context).getDataStoreCache().evictAll(); } if (newnum.equals("fail")) { request.setAttribute("number", "fail"); return; } //return a forward to display.jsp System.out.println("Ending data submission."); if (!spamBot) { //send submitter on to confirmSubmit.jsp //response.sendRedirect(request.getScheme()+"://" + CommonConfiguration.getURLLocation(request) + "/confirmSubmit.jsp?number=" + encID); WebUtils.redirectToSavedRequest(request, response, ("/confirmSubmit.jsp?number=" + encID)); //start email appropriate parties if (CommonConfiguration.sendEmailNotifications(context)) { myShepherd.beginDBTransaction(); try { // Retrieve background service for processing emails ThreadPoolExecutor es = MailThreadExecutorService.getExecutorService(); Properties submitProps = ShepherdProperties.getProperties("submit.properties", ServletUtilities.getLanguageCode(request), context); // Email new submission address(es) defined in commonConfiguration.properties Map<String, String> tagMap = NotificationMailer.createBasicTagMap(request, enc); List<String> mailTo = NotificationMailer .splitEmails(CommonConfiguration.getNewSubmissionEmail(context)); String mailSubj = submitProps.getProperty("newEncounter") + enc.getCatalogNumber(); for (String emailTo : mailTo) { NotificationMailer mailer = new NotificationMailer(context, ServletUtilities.getLanguageCode(request), emailTo, "newSubmission-summary", tagMap); mailer.setUrlScheme(request.getScheme()); es.execute(mailer); } // Email those assigned this location code if (enc.getLocationID() != null) { String informMe = null; try { informMe = myShepherd.getAllUserEmailAddressesForLocationID(enc.getLocationID(), context); } catch (Exception ef) { ef.printStackTrace(); } if (informMe != null) { List<String> cOther = NotificationMailer.splitEmails(informMe); for (String emailTo : cOther) { NotificationMailer mailer = new NotificationMailer(context, null, emailTo, "newSubmission-summary", tagMap); mailer.setUrlScheme(request.getScheme()); es.execute(mailer); } } } // Add encounter dont-track tag for remaining notifications (still needs email-hash assigned). tagMap.put(NotificationMailer.EMAIL_NOTRACK, "number=" + enc.getCatalogNumber()); // Email submitter and photographer if ((enc.getPhotographerEmails() != null) && (enc.getPhotographerEmails().size() > 0)) { List<String> cOther = enc.getPhotographerEmails(); for (String emailTo : cOther) { String msg = CommonConfiguration.appendEmailRemoveHashString(request, "", emailTo, context); tagMap.put(NotificationMailer.EMAIL_HASH_TAG, Encounter.getHashOfEmailString(emailTo)); NotificationMailer mailer = new NotificationMailer(context, null, emailTo, "newSubmission", tagMap); mailer.setUrlScheme(request.getScheme()); es.execute(mailer); } } if ((enc.getSubmitterEmails() != null) && (enc.getSubmitterEmails().size() > 0)) { List<String> cOther = enc.getSubmitterEmails(); for (String emailTo : cOther) { String msg = CommonConfiguration.appendEmailRemoveHashString(request, "", emailTo, context); tagMap.put(NotificationMailer.EMAIL_HASH_TAG, Encounter.getHashOfEmailString(emailTo)); NotificationMailer mailer = new NotificationMailer(context, null, emailTo, "newSubmission", tagMap); mailer.setUrlScheme(request.getScheme()); es.execute(mailer); } } // Email interested others if ((enc.getInformOthersEmails() != null) && (enc.getInformOthersEmails().size() > 0)) { List<String> cOther = enc.getInformOthersEmails(); for (String emailTo : cOther) { String msg = CommonConfiguration.appendEmailRemoveHashString(request, "", emailTo, context); tagMap.put(NotificationMailer.EMAIL_HASH_TAG, Encounter.getHashOfEmailString(emailTo)); NotificationMailer mailer = new NotificationMailer(context, null, emailTo, "newSubmission", tagMap); mailer.setUrlScheme(request.getScheme()); es.execute(mailer); } } /* if ((enc.getInformOthers() != null) && (!enc.getInformOthers().trim().equals(""))) { List<String> cOther = NotificationMailer.splitEmails(enc.getInformOthers()); for (String emailTo : cOther) { String msg = CommonConfiguration.appendEmailRemoveHashString(request, "", emailTo, context); tagMap.put(NotificationMailer.EMAIL_HASH_TAG, Encounter.getHashOfEmailString(emailTo)); NotificationMailer mailer=new NotificationMailer(context, null, emailTo, "newSubmission", tagMap); mailer.setUrlScheme(request.getScheme()); es.execute(mailer); } } */ es.shutdown(); } catch (Exception e) { e.printStackTrace(); } finally { myShepherd.rollbackDBTransaction(); } } //end email appropriate parties } else { response.sendRedirect( request.getScheme() + "://" + CommonConfiguration.getURLLocation(request) + "/spambot.jsp"); } } //end "if (fileSuccess) myShepherd.closeDBTransaction(); //return null; }
From source file:org.ecocean.servlet.EncounterResetDate.java
License:Open Source License
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String context = "context0"; context = ServletUtilities.getContext(request); Shepherd myShepherd = new Shepherd(context); myShepherd.setAction("EncounterResetDate.class"); //set up for response response.setContentType("text/html"); PrintWriter out = response.getWriter(); boolean locked = false; boolean isOwner = true; if ((request.getParameter("number") != null)) { myShepherd.beginDBTransaction(); Encounter fixMe = myShepherd.getEncounter(request.getParameter("number")); setDateLastModified(fixMe);//www. java 2 s . co m String oldDate = ""; String newDate = ""; try { oldDate = fixMe.getDate(); if ((request.getParameter("datepicker") == null) || (request.getParameter("datepicker").trim().equals(""))) { fixMe.setYear(0); fixMe.setMonth(0); fixMe.setDay(0); fixMe.setHour(0); newDate = fixMe.getDate(); } else { /** * Old method of parsing fixMe.setDay(Integer.parseInt(request.getParameter("day"))); fixMe.setMonth(Integer.parseInt(request.getParameter("month"))); fixMe.setYear(Integer.parseInt(request.getParameter("year"))); fixMe.setHour(Integer.parseInt(request.getParameter("hour"))); fixMe.setMinutes(request.getParameter("minutes")); */ //new method using a datepicker //switch to datepicker //if(getVal(fv, "datepicker")!=null){ //System.out.println("Trying to read date: "+getVal(fv, "datepicker").replaceAll(" ", "T")); DateTimeFormatter parser1 = ISODateTimeFormat.dateOptionalTimeParser(); //LocalDateTime reportedDateTime=parser1.parseLocalDateTime(request.getParameter("datepicker").replaceAll(" ", "T")); LocalDateTime reportedDateTime = new LocalDateTime( parser1.parseMillis(request.getParameter("datepicker").replaceAll(" ", "T"))); //System.out.println("Day of month is: "+reportedDateTime.getDayOfMonth()); StringTokenizer str = new StringTokenizer( request.getParameter("datepicker").replaceAll(" ", "T"), "-"); int numTokens = str.countTokens(); if (numTokens >= 1) { try { fixMe.setYear(new Integer(reportedDateTime.getYear())); } catch (Exception e) { fixMe.setYear(-1); } } if (numTokens >= 2) { try { fixMe.setMonth(new Integer(reportedDateTime.getMonthOfYear())); } catch (Exception e) { fixMe.setMonth(-1); } } else { fixMe.setMonth(-1); } //see if we can get a day, because we do want to support only yyy-MM too if (str.countTokens() >= 3) { try { fixMe.setDay(new Integer(reportedDateTime.getDayOfMonth())); } catch (Exception e) { fixMe.setDay(0); } } else { fixMe.setDay(0); } //see if we can get a time and hour, because we do want to support only yyy-MM too StringTokenizer strTime = new StringTokenizer( request.getParameter("datepicker").replaceAll(" ", "T"), "T"); if (strTime.countTokens() > 1) { try { fixMe.setHour(new Integer(reportedDateTime.getHourOfDay())); } catch (Exception e) { fixMe.setHour(-1); } try { fixMe.setMinutes(new Integer(reportedDateTime.getMinuteOfHour()).toString()); } catch (Exception e) { } } else { fixMe.setHour(-1); } //} newDate = fixMe.getDate(); fixMe.addComments("<p><em>" + request.getRemoteUser() + " on " + (new java.util.Date()).toString() + "</em><br>Changed encounter date from " + oldDate + " to " + newDate + ".</p>"); if (fixMe.getIndividualID() != null) { String indieName = fixMe.getIndividualID(); if (myShepherd.isMarkedIndividual(indieName)) { MarkedIndividual indie = myShepherd.getMarkedIndividual(indieName); indie.refreshDependentProperties(); } } } //end else } catch (Exception le) { locked = true; le.printStackTrace(); myShepherd.rollbackDBTransaction(); } //out.println(ServletUtilities.getHeader(request)); if (!locked) { myShepherd.commitDBTransaction(); out.println("<strong>Success:</strong> I have changed the encounter date from " + oldDate + " to " + newDate + "."); //out.println("<p><a href=\"http://" + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + request.getParameter("number") + "\">Return to encounter #" + request.getParameter("number") + "</a></p>\n"); String message = "The date of encounter " + request.getParameter("number") + " was changed from " + oldDate + " to " + newDate + "."; ServletUtilities.informInterestedParties(request, request.getParameter("number"), message, context); response.setStatus(HttpServletResponse.SC_OK); } else { out.println( "<strong>Failure:</strong> I have NOT changed the encounter date because another user is currently modifying this encounter. Please try this operation again in a few seconds."); //out.println("<p><a href=\"http://" + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + request.getParameter("number") + "\">Return to encounter " + request.getParameter("number") + "</a></p>\n"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } //out.println(ServletUtilities.getFooter(context)); } else { out.println(ServletUtilities.getHeader(request)); out.println("<strong>Error:</strong> I don't have enough information to complete your request."); //out.println("<p><a href=\"http://" + CommonConfiguration.getURLLocation(request) + "/encounters/encounter.jsp?number=" + request.getParameter("number") + "\">Return to encounter " + request.getParameter("number") + "</a></p>\n"); //out.println(ServletUtilities.getFooter(context)); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } out.close(); myShepherd.closeDBTransaction(); }
From source file:org.logstash.filters.parser.CasualISO8601Parser.java
License:Apache License
@Override public Instant parse(String value) { RuntimeException lastException = null; for (DateTimeFormatter parser : parsers) { try {//from www . j a v a 2s .co m return new Instant(parser.parseMillis(value)); } catch (IllegalArgumentException e) { lastException = e; } } throw lastException; }
From source file:org.logstash.filters.parser.JodaParser.java
License:Apache License
@Override public Instant parseWithTimeZone(String value, String timezone) { DateTimeZone tz = DateTimeZone.forID(timezone); DateTimeFormatter parserWithZone = parser.withZone(tz); if (hasYear) { return new Instant(parserWithZone.parseMillis(value)); } else {//from www .ja va 2s. c o m return parseAndGuessYear(parserWithZone, value); } }
From source file:org.sonar.replay.Main.java
License:LGPL
public static void main(String[] args) { /*/*from w ww .java 2s. co m*/ Inputs: 1) Perforce connection info 2) Sonar db connection info 3) Perforce Depot 4) optional: label filter (regex) 5) optional: time span window (start/end) ? by label name? 6) optional: version pattern (how to parse # out of label name) Logic for version number 1) If it has a checked in version number in pom.xml use that 2) Otherwise if version is a ${..} parse General logic: 1) Get all labels (regarding filter) 2) For each label... 2.1) Find time of label 2.2) If time is not in option span, break. 2.3) p4 sync to that label 2.4) figure out version number 2.5) exec 'mvn clean sonar:sonar' passing it 2.5.1) sonar conn info 2.5.2) sonar project date 2.5.3) conditional: label version as whatever property was found ${} */ Properties props = new Properties(); if (!readPropertiesFile(args, props)) { System.exit(1); } System.getProperties().putAll(props); System.getProperties().put("maven.home", System.getenv("M2_HOME")); if (!System.getProperties().containsKey("mvn.exe")) { System.getProperties().put("mvn.exe", "mvn"); } // Mild-validation if (!System.getProperties().containsKey("p4.file.specs")) { LOGGER.warn( "Not specifying 'p4.file.specs' will default to the entire perforce depot which is probably NOT what you want."); } try { File tempDir = new File(System.getProperty("java.io.tmpdir")); File syncDir = new File(new File(tempDir, "sonar-replay"), "workspace"); syncDir.mkdirs(); LOGGER.debug("Made temp workspace: " + syncDir.getAbsolutePath()); P4JLog.setLogCallback(new LogCallback(System.out)); P4JServer server = P4JServerFactory.getServer(System.getProperty("p4.url"), null); LOGGER.debug("Connecting to server..."); server.connect(); server.setUserName(System.getProperty("p4.user")); server.setAuthTicket(null); // turn off use of tickets. server.login(System.getProperty("p4.password")); LOGGER.info("Logged into perforce server [" + System.getProperty("p4.user") + " @ " + System.getProperty("p4.url") + "]."); server.registerCallback(new P4JCommandCallback() { public void issuingServerCommand(int i, String s) { LOGGER.debug(i + ": Issuing Server Command : " + s); } public void completedServerCommand(int i, long l) { LOGGER.debug(i + ": Completed Server Command : " + l); } public void receivedServerInfoLine(int i, String s) { LOGGER.debug("-- " + i + ": I* Received Server Info : " + s); } public void receivedServerErrorLine(int i, String s) { LOGGER.debug("-- " + i + ": E* Received Server Error : " + s); } public void receivedServerMessage(int i, int i1, int i2, String s) { LOGGER.debug("-- " + i + ": Received Server Message : " + i1 + " : " + i2 + " : " + s); } }); server.registerProgressCallback(new DemoProgressCallback()); List<P4JFileSpec> fileSpecs = parseFileSpecs(System.getProperty("p4.file.specs", "//...")); // System.out.println("validSpecs: " + fileSpecs); P4JClientSpecImpl spec = new P4JClientSpecImpl(); spec.setRoot(syncDir.getAbsolutePath()); final P4JClientViewImpl view = new P4JClientViewImpl(); final List<P4JClientView.P4JClientViewMapping> mappings = new ArrayList<P4JClientView.P4JClientViewMapping>(); final String clientName = "sonar-replay-" + InetAddress.getLocalHost().getHostName(); for (P4JFileSpec fileSpec : fileSpecs) { LOGGER.debug("Adding file spec: " + fileSpec.getDisplayPath()); mappings.add(new P4JClientViewImpl.P4JClientViewMappingImpl(0, fileSpec.getDisplayPath(), "//" + clientName + "/...")); } view.setMapping(mappings); spec.setClientView(view); spec.setName(clientName); spec.setOwnerName(server.getUserName()); spec.setHostName(""); P4JClient clientStub = new P4JClientImpl(server, spec, false); LOGGER.debug("Creating client..."); server.newClient(clientStub); P4JClient client = server.getClient(clientStub.getName()); LOGGER.debug("Client created."); server.setCurrentClient(client); LOGGER.debug("Clearing workspace..."); List<P4JFileSpec> cleared = client.sync( P4JFileSpecBuilder .getValidFileSpecs(P4JFileSpecBuilder.makeFileSpecList(new String[] { "#0" })), false, false, false, false); LOGGER.debug("Files cleared: " + cleared.size()); LOGGER.debug("Getting labels."); // Get all the labels for the project... List<P4JLabel> labels = new ArrayList<P4JLabel>(); if (System.getProperties().containsKey("p4.label.name.filters")) { for (String nameFilter : System.getProperty("p4.label.name.filters").split(",")) { labels.addAll(server.getLabelList(ALL_USERS, MAX_LABEL_COUNT, nameFilter, fileSpecs)); } } else { labels.addAll(server.getLabelList(ALL_USERS, MAX_LABEL_COUNT, NO_LABEL_FILTER, fileSpecs)); } Collections.sort(labels, new Comparator<P4JLabel>() { public int compare(P4JLabel o1, P4JLabel o2) { return Long.valueOf(o1.getLastUpdate().getTime()).compareTo(o2.getLastUpdate().getTime()); } }); LOGGER.info("Labels retrieved: " + labels.size()); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd"); ReadableInterval interval = new Interval( fmt.parseMillis(System.getProperty("p4.interval.start", "1900-01-01")), fmt.parseMillis(System.getProperty("p4.interval.end", "2100-01-01"))); Pattern labelFilter = Pattern.compile(System.getProperty("p4.label.filter", ".*")); for (P4JLabel label : labels) { // If the labels last update time is within the filtering time interval... final DateTime lastUpdatedOn = new DateTime(label.getLastUpdate().getTime()); if (interval.contains(lastUpdatedOn)) { final Matcher matcher = labelFilter.matcher(label.getName()); // If the label matches the regex if (matcher.matches()) { LOGGER.info("Processing label: " + label.getName()); // Parse out the version String version = matcher.group(1); System.getProperties().put("sonar.projectDate", fmt.print(lastUpdatedOn)); if (version != null) { System.getProperties().put("build.number", version); } LOGGER.debug("Syncing label."); List<P4JFileSpec> synced = client.sync( P4JFileSpecBuilder.getValidFileSpecs(P4JFileSpecBuilder .makeFileSpecList(new String[] { "@" + label.getName() })), false, false, false, false); LOGGER.debug("Files synced: " + synced.size()); LOGGER.debug("Starting Maven..."); try { ProcessBuilder b = new ProcessBuilder().command( System.getenv("M2_HOME") + "/bin/" + System.getProperty("mvn.exe"), // "-X", "--batch-mode", "-e", "-Dbuild.number=" + version, "-Dsonar.projectDate=" + System.getProperty("sonar.projectDate"), "-Dsonar.exclusions=" + System.getProperty("sonar.exclusions", ""), "-s", System.getProperty("m2.settings", System.getProperty("user.home") + "/.m2/settings.xml"), "clean", "install", "sonar:sonar").directory(syncDir); Process p = b.start(); // Process p = Runtime.getRuntime().exec( // new String[]{ // System.getenv("M2_HOME") + "/bin/mvn", // "-Dbuild.number=" + version, // "-Dsonar.projectDate=" + System.getProperty("sonar.projectDate"), // "clean", // "validate" // } // ); new Thread(new StreamRedirector(p.getErrorStream(), true)).start(); new Thread(new StreamRedirector(p.getInputStream(), false)).start(); p.waitFor(); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); } catch (InterruptedException e) { LOGGER.warn(e.getMessage(), e); } // try { // // Now we are synced, fire up maven // Configuration configuration = new DefaultConfiguration() // .setUserSettingsFile( MavenEmbedder.DEFAULT_USER_SETTINGS_FILE ) // .setGlobalSettingsFile( MavenEmbedder.DEFAULT_GLOBAL_SETTINGS_FILE ) // .setClassLoader( Thread.currentThread().getContextClassLoader() ) // .setSystemProperties(System.getProperties()) // .setLocalRepository(new File(new File(System.getProperty("user.home"), ".m2"), "repository")) // ; // // ConfigurationValidationResult validationResult = MavenEmbedder.validateConfiguration( configuration ); // // if ( validationResult.isValid() ) // { // // MavenEmbedder embedder = new MavenEmbedder( configuration ); // // MavenExecutionRequest request = new DefaultMavenExecutionRequest() // .setBaseDirectory( syncDir ) // .setGoals( Arrays.asList( new String[]{"help:effective-settings"} ) ) // ; // // MavenExecutionResult result = embedder.execute( request ); // // if ( result.hasExceptions() ) // { // for (Exception exception : (List<Exception>) result.getExceptions()) { // exception.printStackTrace(); // } // return; // } // } else { // final Exception settingsException = validationResult.getGlobalSettingsException(); // if(settingsException != null) settingsException.printStackTrace(); // final Exception exception = validationResult.getUserSettingsException(); // if(exception != null) { // exception.printStackTrace(); // } // validationResult.display(); // } // } catch (MavenEmbedderException e) { // e.printStackTrace(); // } } } } LOGGER.debug("Clearing workspace..."); List<P4JFileSpec> synced = client.sync( P4JFileSpecBuilder .getValidFileSpecs(P4JFileSpecBuilder.makeFileSpecList(new String[] { "#0" })), false, false, false, false); LOGGER.debug("Files cleared: " + synced.size()); server.setCurrentClient(null); server.deleteClient(client.getName(), false); } catch (URISyntaxException e) { LOGGER.warn(e.getMessage(), e); } catch (P4JConnectionException e) { LOGGER.warn(e.getMessage(), e); } catch (P4JNoSuchObjectException e) { LOGGER.warn(e.getMessage(), e); } catch (P4JConfigException e) { LOGGER.warn(e.getMessage(), e); } catch (P4JResourceException e) { LOGGER.warn(e.getMessage(), e); } catch (P4JAccessException e) { LOGGER.warn(e.getMessage(), e); } catch (P4JRequestException e) { LOGGER.warn(e.getMessage(), e); } catch (UnknownHostException e) { LOGGER.warn(e.getMessage(), e); } // ReplayConfig config = buildReplayConfig(args); }
From source file:playRepository.SVNRepository.java
License:Apache License
private ObjectNode fileAsJson(String path, org.tmatesoft.svn.core.io.SVNRepository repository) throws SVNException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); SVNProperties prop = new SVNProperties(); repository.getFile(path, -1l, prop, baos); SVNDirEntry entry = repository.info(path, -1l); long size = entry.getSize(); boolean isBinary; String mimeType;/* ww w. j a va 2 s . c o m*/ String data = null; if (size > MAX_FILE_SIZE_CAN_BE_VIEWED) { isBinary = true; mimeType = "application/octet-stream"; } else { byte[] bytes = baos.toByteArray(); isBinary = RawText.isBinary(bytes); if (!isBinary) { data = new String(bytes, FileUtil.detectCharset(bytes)); } mimeType = new Tika().detect(bytes, path); } String author = prop.getStringValue(SVNProperty.LAST_AUTHOR); User user = User.findByLoginId(author); String commitDate = prop.getStringValue(SVNProperty.COMMITTED_DATE); DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTime(); Long commitTime = dateFormatter.parseMillis(commitDate); ObjectNode result = Json.newObject(); result.put("type", "file"); result.put("revisionNo", prop.getStringValue(SVNProperty.COMMITTED_REVISION)); result.put("author", author); result.put("avatar", getAvatar(user)); result.put("userName", user.name); result.put("userLoginId", user.loginId); result.put("createdDate", commitTime); result.put("commitMessage", entry.getCommitMessage()); result.put("commiter", author); result.put("size", size); result.put("isBinary", isBinary); result.put("mimeType", mimeType); result.put("data", data); return result; }
From source file:uk.ac.susx.tag.method51.core.params.codec.concrete.TimestampCodec.java
License:Apache License
@Override public Long decode(Object value) throws DecodeException { if (value instanceof Number) { return ((Number) value).longValue(); } else if (value instanceof String) { for (DateTimeFormatter format : dateTimeFormatters) { try { return format.parseMillis((String) value); } catch (IllegalArgumentException e1) { // ignore }//www. j ava 2 s . c o m } try { final long timestamp = Long.parseLong((String) value); if (timestamp >= 0) return timestamp; } catch (NumberFormatException e) { } throw new DecodeException("Could not parse time string " + value); } else { throw new DecodeException( "Value should be a string or a number, but found " + value.getClass().getName()); } }