static { tempCalGMT.setLenient(false); sdfd.setCalendar(new GregorianCalendar(TimeZone.getTimeZone("GMT"))); sdfd.setLenient(false); sdft.setCalendar(new GregorianCalendar(TimeZone.getTimeZone("GMT"))); sdft.setLenient(false); sdfts.setCalendar(new GregorianCalendar(TimeZone.getTimeZone("GMT"))); sdfts.setLenient(false); }
public Object objectDone() { Object o = super.objectDone(); BSONObject b = (BSONObject) o; if (!_lastArray) { if (b.containsField("$oid")) { o = new ObjectId((String) b.get("$oid")); if (!isStackEmpty()) { gotObjectId(_lastName, (ObjectId) o); } else { setRoot(o); } } else if (b.containsField("$date")) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); o = format.parse((String) b.get("$date"), new ParsePosition(0)); if (!isStackEmpty()) { cur().put(_lastName, o); } else { setRoot(o); } } else if (b.containsField("$regex")) { o = Pattern.compile((String) b.get("$regex"), BSON.regexFlags((String) b.get("$options"))); if (!isStackEmpty()) { cur().put(_lastName, o); } else { setRoot(o); } } } return o; }
@org.testng.annotations.Test public void testJSONEncoding() throws ParseException { String json = "{ 'str' : 'asdfasd' , 'long' : 123123123123 , 'int' : 5 , 'float' : 0.4 , 'bool' : false , 'date' : { '$date' : '2011-05-18T18:56:00Z'} , 'pat' : { '$regex' : '.*' , '$options' : ''} , 'oid' : { '$oid' : '4d83ab3ea39562db9c1ae2ae'} , 'ref' : { '$ref' : 'test.test' , '$id' : { '$oid' : '4d83ab59a39562db9c1ae2af'}} , 'code' : { '$code' : 'asdfdsa'} , 'codews' : { '$code' : 'ggggg' , '$scope' : { }} , 'ts' : { '$ts' : 1300474885 , '$inc' : 10} , 'null' : null, 'uuid' : { '$uuid' : '60f65152-6d4a-4f11-9c9b-590b575da7b5' }}"; BasicDBObject a = (BasicDBObject) JSON.parse(json); assert (a.get("str").equals("asdfasd")); assert (a.get("int").equals(5)); assert (a.get("long").equals(123123123123L)); assert (a.get("float").equals(0.4d)); assert (a.get("bool").equals(false)); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); assert (a.get("date").equals(format.parse("2011-05-18T18:56:00Z"))); Pattern pat = (Pattern) a.get("pat"); Pattern pat2 = Pattern.compile(".*", BSON.regexFlags("")); assert (pat.pattern().equals(pat2.pattern())); assert (pat.flags() == (pat2.flags())); ObjectId oid = (ObjectId) a.get("oid"); assert (oid.equals(new ObjectId("4d83ab3ea39562db9c1ae2ae"))); DBRef ref = (DBRef) a.get("ref"); assert (ref.equals(new DBRef(null, "test.test", new ObjectId("4d83ab59a39562db9c1ae2af")))); assert (a.get("code").equals(new Code("asdfdsa"))); assert (a.get("codews").equals(new CodeWScope("ggggg", new BasicBSONObject()))); assert (a.get("ts").equals(new BSONTimestamp(1300474885, 10))); assert (a.get("uuid").equals(UUID.fromString("60f65152-6d4a-4f11-9c9b-590b575da7b5"))); String json2 = JSON.serialize(a); BasicDBObject b = (BasicDBObject) JSON.parse(json2); a.equals(b); assert (a.equals(b)); }
/** * Construction du titre de l'excel * * @return */ public String getExcelTitle() { StringBuffer buffer = new StringBuffer(); String title = "Planning mensuelle des pilotes : "; Date date = (Date) session.get(PilotageConstants.PLANNING_SELECT_DATE); Calendar c = Calendar.getInstance(); c.setTime(date); // String DateSelect = String.valueOf(c.get(Calendar.DATE)); // DateSelect += "/" + String.valueOf(c.get(Calendar.MONTH)+1); // DateSelect += "/" + String.valueOf(c.get(Calendar.YEAR)); SimpleDateFormat sdf = new SimpleDateFormat(); sdf.setCalendar(c); sdf.applyPattern("MMMM"); String libelleMois = sdf.format(c.getTime()); String DateSelect = libelleMois.trim() + "_" + String.valueOf(c.get(Calendar.YEAR)).trim(); buffer.append(title.trim()); buffer.append(DateSelect.trim()); buffer.append(".xls"); return buffer.toString(); }
/** * sets complete date text and member variable value * * @param date */ private void setCompleteDate(Calendar date) { // format date for display SimpleDateFormat sdf = new SimpleDateFormat(pattern); sdf.setCalendar(date); mDateCompleteText.setText(sdf.format(date.getTime())); // convert to unix and store mCompleteTimeUnix = date.getTimeInMillis() / 1000; Log.i("TIME", Long.toString(mCompleteTimeUnix)); }
public static Date FormatDate(final String date, final String pattern) { final Calendar cal = Calendar.getInstance(TimeZone.getDefault()); final SimpleDateFormat format = new SimpleDateFormat(pattern); format.setCalendar(cal); try { return format.parse(date); } catch (Throwable t) { return null; } }
/** * Gets current time in the following format Month, Date, Hours, Minutes, Seconds, Millisecond. * * @return Current date. */ public String getCurrentTimeStampString() { java.util.Date date = new java.util.Date(); SimpleDateFormat sd = new SimpleDateFormat("MMddHHmmssSS"); TimeZone timeZone = TimeZone.getDefault(); Calendar cal = Calendar.getInstance(new SimpleTimeZone(timeZone.getOffset(date.getTime()), "GMT")); sd.setCalendar(cal); return sd.format(date); }
@org.testng.annotations.Test public void testDate() { Date d = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); String formattedDate = format.format(d); String serialized = JSON.serialize(d); assertEquals("{ \"$date\" : \"" + formattedDate + "\"}", serialized); Date d2 = (Date) JSON.parse(serialized); assertEquals(d.toString(), d2.toString()); assertTrue(d.equals(d2)); }
private String getSoapEnvelope(String onBehalfOf) { Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.500Z'"); format.setCalendar(calendar); String created = format.format(new Date(calendar.getTimeInMillis())); long now = calendar.getTimeInMillis(); now += 60000; String expires = format.format(new Date(now)); String body = SOAP_ENV; body = body.replace("ON_BEHALF_OF", onBehalfOf); body = body.replace("CREATED", created); body = body.replace("EXPIRES", expires); return body; }
private String getDate() throws CloudException { if (provider.getEC2Provider().isStorage() && "google".equalsIgnoreCase(provider.getProviderName())) { SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ssz", new Locale("US")); Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT")); format.setCalendar(cal); return format.format(new Date()); } else { SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); // TODO: sync regularly with CloudFront return fmt.format(new Date()); } }
/** * Parses a string using {@link SimpleDateFormat} and a given pattern. This method parses a string * at the specified parse position and if successful, updates the parse position to the index * after the last character used. The parsing is strict and requires months to be less than 12, * days to be less than 31, etc. * * @param s string to be parsed * @param pattern {@link SimpleDateFormat} pattern * @param tz time zone in which to interpret string. Defaults to the Java default time zone * @param pp position to start parsing from * @return a Calendar initialized with the parsed value, or null if parsing failed. If returned, * the Calendar is configured to the GMT time zone. * @pre pattern != null */ private static Calendar parseDateFormat(String s, String pattern, TimeZone tz, ParsePosition pp) { assert pattern != null; SimpleDateFormat df = new SimpleDateFormat(pattern); if (tz == null) { tz = DEFAULT_ZONE; } Calendar ret = Calendar.getInstance(tz); df.setCalendar(ret); df.setLenient(false); java.util.Date d = df.parse(s, pp); if (null == d) { return null; } ret.setTime(d); ret.setTimeZone(GMT_ZONE); return ret; }
/** * Convert a String to a java.sql.Timestamp object * * @param t The timestamp String * @param selfGenerated Is this a self generated timestamp (e.g. it has .999 on the end) * @return The converted Timestamp * @throws ParseException */ private static Timestamp toTimestamp(String t, boolean selfGenerated) throws ParseException { SimpleDateFormat df; // Choose the correct date format based on string length if (t.length() == 10) { df = new SimpleDateFormat("yyyy-MM-dd"); } else if (t.length() == 20) { df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); } else if (selfGenerated) { df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); } else { // Not self generated, and not in a guessable format throw new ParseException("", 0); } // Parse the date df.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("UTC"))); return new Timestamp(df.parse(t).getTime()); }
/** * Given a time value in milliseconds, this method returns a human readable representation. Here * are a few examples: * * <p> * * <UL> * <LI>If time is negative, the human readable representation is "N/A". * <LI>If time is 3000, the human readable representation is "00:03". * <LI>If time is 300000, the human readable representation is "05:00". * <LI>If time is 302000, the human readable representation is "05:02". * <LI>If time is 3601000, the human readable representation is "01:00:01". * </UL> * * @param time Time in millseconds. * @return Human Readable Representation of Time. */ public static String getTimeString(long time) { if (time < 0) { return NOT_AVAILABLE_STR; } else { // Use GMT Time Zone so that we start exactly at the // Epoch: midnight, GM, January 1st, 1970. SimpleDateFormat dateFormat; TimeZone timeZone = TimeZone.getTimeZone("GMT"); Calendar calendar = Calendar.getInstance(timeZone); calendar.setTimeInMillis(time); if (calendar.get(Calendar.HOUR) >= 1) { dateFormat = new SimpleDateFormat("HH:mm:ss"); } else { dateFormat = new SimpleDateFormat("mm:ss"); } dateFormat.setCalendar(calendar); return dateFormat.format(calendar.getTime()); } }
private static long parseTimestamp(String timestamp) { if (timestamp == null) { return -1; } long creationTs; SimpleDateFormat fmt; // some response dates have MS component, some do not. if (timestamp.contains(".")) { fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); } else { fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); } Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT")); fmt.setCalendar(cal); try { creationTs = fmt.parse(timestamp).getTime(); } catch (ParseException e) { creationTs = System.currentTimeMillis(); } return creationTs; }
/** * @param testY candidate year * @param testM candidate month in range 1 to 12 * @param testD candidate day in range 1 to 31 * @param leniant succeed even if the day and month might be ambiguous * @return Formatted date if certain date fields are OK and wouldn't be OK in a different order, * else null */ private String populateDateFieldsIfUnambiguous(int testY, int testM, int testD, boolean leniant) { if ((testY < 1600) || (testY > 4500)) { // Year does not fit within what Outlook allows, probably not what is intended return null; } int firstAllowableDay = leniant ? 1 : 13; if ((testD < firstAllowableDay) || (testD > 31)) { // Either an invalid date or could be a month number if guessed date string order wrong return null; } if ((testM < 1) || (testM > 12)) { // Not a valid month return null; } ICalTimeZone tzUTC = ICalTimeZone.getUTC(); GregorianCalendar cal = new GregorianCalendar(tzUTC); cal.set(testY, testM - 1, 1, 0, 0); if (testD > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) return null; cal.set(Calendar.DAY_OF_MONTH, testD); SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd"); ymd.setCalendar(cal); return ymd.format(cal.getTime()); }
/** A test to reproduce bug 2201869. */ @Test public void testBug2201869() { TimeZone tz = TimeZone.getTimeZone("GMT"); GregorianCalendar c = new GregorianCalendar(tz, Locale.UK); DateAxis axis = new DateAxis("Date", tz, Locale.UK); SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yyyy", Locale.UK); sdf.setCalendar(c); axis.setTickUnit(new DateTickUnit(DateTickUnit.MONTH, 1, sdf)); Day d1 = new Day(1, 3, 2008); d1.peg(c); Day d2 = new Day(30, 6, 2008); d2.peg(c); axis.setRange(d1.getStart(), d2.getEnd()); BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, 200, 100); axis.setTickMarkPosition(DateTickMarkPosition.END); List ticks = axis.refreshTicks(g2, new AxisState(), area, RectangleEdge.BOTTOM); assertEquals(3, ticks.size()); DateTick t1 = (DateTick) ticks.get(0); assertEquals("31-Mar-2008", t1.getText()); DateTick t2 = (DateTick) ticks.get(1); assertEquals("30-Apr-2008", t2.getText()); DateTick t3 = (DateTick) ticks.get(2); assertEquals("31-May-2008", t3.getText()); // now repeat for a vertical axis ticks = axis.refreshTicks(g2, new AxisState(), area, RectangleEdge.LEFT); assertEquals(3, ticks.size()); t1 = (DateTick) ticks.get(0); assertEquals("31-Mar-2008", t1.getText()); t2 = (DateTick) ticks.get(1); assertEquals("30-Apr-2008", t2.getText()); t3 = (DateTick) ticks.get(2); assertEquals("31-May-2008", t3.getText()); }
/** * Format. * * @param calendar the calendar * @return the string */ private String format(GregorianCalendar calendar) { SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy"); fmt.setCalendar(calendar); String dateFormatted = fmt.format(calendar.getTime()); return dateFormatted; }
static { // Workaround for setting the timezone since there is a bug in android 2.2 and earlier // http://code.google.com/p/android/issues/detail?id=8258 isoDateFormatter.setCalendar(Calendar.getInstance(utc)); }
/** * Parses a text string to set variables dynamically at run time. * * @param _parse * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalAccessException * @throws IOException */ private void read(String _parse) throws SecurityException, NoSuchFieldException, IllegalAccessException, IOException { StringTokenizer stk = new StringTokenizer(_parse); tk = stk.nextToken(); // Try to retrieve a Field by the name provided as a token. If it is // unavailable then return back to the while. Field f = this.getClass().getField(tk); Type t = f.getType(); // If the identified field is of type int: if (t.toString().equalsIgnoreCase("int")) { Integer i = Integer.parseInt(stk.nextToken()); f.setInt(this, i); parse = br.readLine(); } // If the identified field is of type long: else if (t.toString().equalsIgnoreCase("long")) { Long l = Long.parseLong(stk.nextToken()); f.setLong(this, l); parse = br.readLine(); } // If the identified field is of type double: else if (t.toString().equalsIgnoreCase("double")) { f.setDouble(this, Double.parseDouble(stk.nextToken())); parse = br.readLine(); } // If the identified field is of type boolean: else if (t.toString().equalsIgnoreCase("boolean")) { String ntk = stk.nextToken(); if (!ntk.equalsIgnoreCase("true") && !ntk.equalsIgnoreCase("false")) { System.out.println( "Invalid parameter value provided for variable " + f.getName() + ", setting to false"); } f.setBoolean(this, Boolean.valueOf(ntk)); parse = br.readLine(); } // If the identified field is of type int[]: else if (t.toString().equalsIgnoreCase("class [I")) { int[] ia = new int[stk.countTokens()]; int i = 0; while (stk.hasMoreTokens()) { ia[i] = Integer.parseInt(stk.nextToken()); i++; } f.set(this, ia); parse = br.readLine(); } // If the identified field is of type double[]: else if (t.toString().equalsIgnoreCase("class [F")) { float[] fa = new float[stk.countTokens()]; int i = 0; while (stk.hasMoreTokens()) { fa[i] = Integer.parseInt(stk.nextToken()); i++; } f.set(this, fa); parse = br.readLine(); } // If the identified field is of type double[]: else if (t.toString().equalsIgnoreCase("class [D")) { double[] da = new double[stk.countTokens()]; int i = 0; while (stk.hasMoreTokens()) { da[i] = Integer.parseInt(stk.nextToken()); i++; } f.set(this, da); parse = br.readLine(); } // If the identified field is of type String: else if (t.toString().equalsIgnoreCase("class java.lang.String")) { f.set(this, stk.nextToken()); parse = br.readLine(); } // If the identified field is of type Date: else if (t.toString().equalsIgnoreCase("class java.util.Date")) { // Appropriate filtering needs to be added here; try { SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy_HH:mm:ss", Locale.US); sdf.setCalendar(Calendar.getInstance()); Date d = sdf.parse(stk.nextToken()); f.set(this, d); } catch (IllegalAccessException ex2) { ex2.printStackTrace(); } catch (IllegalArgumentException ex2) { ex2.printStackTrace(); } catch (ParseException ex2) { ex2.printStackTrace(); } parse = br.readLine(); } else if (t.toString().equalsIgnoreCase("class java.io.File")) { File iFile = new File(stk.nextToken()); f.set(this, iFile); parse = br.readLine(); } // If the type is none of the above, conversion hasn't been // implemented therefore ignore and continue. else { System.out.println("Type " + t.toString() + " cannot be converted. Continuing..."); parse = br.readLine(); } }
protected static Element createCommentElem(Comment comm, Document doc) { Element commentElem; Element elem; SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATE_PATTERN); sdf.setCalendar(Calendar.getInstance(new SimpleTimeZone(0, "GMT"))); commentElem = doc.createElement("Comment"); elem = doc.createElement(Comment.ID); setValue(elem, doc, comm.getId()); commentElem.appendChild(elem); elem = doc.createElement(Comment.REPLY_TO); setValue(elem, doc, comm.getReplyTo()); commentElem.appendChild(elem); elem = doc.createElement(Comment.EMAIL); setValue(elem, doc, comm.getEmail()); commentElem.appendChild(elem); elem = doc.createElement(Comment.OWNER_ID); setValue(elem, doc, comm.getOwnerId()); commentElem.appendChild(elem); elem = doc.createElement(Comment.DESIGNER_ID); setValue(elem, doc, comm.getDesignerId()); commentElem.appendChild(elem); // elem = doc.createElement(Comment.ORDER); // setValue(elem, doc, Float.toString(comm.getOrder())); // commentElem.appendChild(elem); // elem = doc.createElement(Comment.DEPTH); // setValue(elem, doc, Short.toString(comm.getDepth())); // commentElem.appendChild(elem); elem = doc.createElement(Comment.PAGE_NAME); setValue(elem, doc, comm.getPageName()); commentElem.appendChild(elem); elem = doc.createElement(Comment.PAGE_STATE); setValue(elem, doc, comm.getPageState()); commentElem.appendChild(elem); elem = doc.createElement(Comment.VIEW_SCENE); setValue(elem, doc, comm.getViewScene()); commentElem.appendChild(elem); elem = doc.createElement(Comment.SUBJECT); setValue(elem, doc, comm.getSubject()); commentElem.appendChild(elem); elem = doc.createElement(Comment.CONTENT); setValue(elem, doc, comm.getContent()); commentElem.appendChild(elem); elem = doc.createElement(Comment.CREATED); setValue(elem, doc, sdf.format(comm.getCreated())); commentElem.appendChild(elem); elem = doc.createElement(Comment.DRAWING_JSON); setValue(elem, doc, comm.getDrawingJson()); commentElem.appendChild(elem); elem = doc.createElement(Comment.SEVERITY); setValue(elem, doc, comm.getSeverity()); commentElem.appendChild(elem); elem = doc.createElement(Comment.TYPE); setValue(elem, doc, comm.getType()); commentElem.appendChild(elem); elem = doc.createElement(Comment.STATUS); setValue(elem, doc, comm.getStatus()); commentElem.appendChild(elem); return commentElem; }
/** * @api {get} /rest2/openrosa/:studyOID/formList Get Form List * @apiName getFormList * @apiPermission admin * @apiVersion 1.0.0 * @apiParam {String} studyOID Study Oid. * @apiGroup Form * @apiDescription Retrieves a listing of the available OpenClinica forms. * @apiParamExample {json} Request-Example: { "studyOid": "S_SAMPLTE", } * @apiSuccessExample {xml} Success-Response: HTTP/1.1 200 OK { <xforms * xmlns="http://openrosa.org/xforms/xformsList"> <xform> <formID>F_FIRSTFORM_1</formID> * <name>First Form</name> <majorMinorVersion>1</majorMinorVersion> <version>1</version> * <hash>8678370cd92814d4e3216d58d821403f</hash> * <downloadUrl>http://oc1.openclinica.com/OpenClinica-web/rest2/openrosa/S_SAMPLTE/formXml? * formId=F_FIRSTFORM_1</downloadUrl> </xform> <xform> <formID>F_SECONDFORM_1</formID> * <name>Second Form</name> <majorMinorVersion>1</majorMinorVersion> <version>1</version> * <hash>7ee60d1c6516b730bbe9bdbd7cad942f</hash> * <downloadUrl>http://oc1.openclinica.com/OpenClinica-web/rest2/openrosa/S_SAMPLTE/formXml? * formId=F_SECONDFORM_1</downloadUrl> </xform> </xforms> */ @GET @Path("/{studyOID}/formList") @Produces(MediaType.TEXT_XML) public String getFormList( @Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("studyOID") String studyOID, @QueryParam("formID") String crfOID, @RequestHeader("Authorization") String authorization, @Context ServletContext context) throws Exception { if (!mayProceedPreview(studyOID)) return null; StudyDAO sdao = new StudyDAO(getDataSource()); StudyBean study = sdao.findByOid(studyOID); CRFDAO cdao = new CRFDAO(getDataSource()); Collection<CRFBean> crfs = cdao.findAll(); CRFVersionDAO cVersionDao = new CRFVersionDAO(getDataSource()); Collection<CRFVersionBean> crfVersions = cVersionDao.findAll(); CrfVersionMediaDao mediaDao = (CrfVersionMediaDao) SpringServletAccess.getApplicationContext(context).getBean("crfVersionMediaDao"); try { XFormList formList = new XFormList(); for (CRFBean crf : crfs) { for (CRFVersionBean version : crfVersions) { if (version.getCrfId() == crf.getId()) { XForm form = new XForm(crf, version); // TODO: Need to generate hash based on contents of // XForm. Will be done in a later story. // TODO: For now all XForms get a date based hash to // trick Enketo into always downloading // TODO: them. Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); form.setHash(DigestUtils.md5Hex(String.valueOf(cal.getTimeInMillis()))); String urlBase = getCoreResources().getDataInfo().getProperty("sysURL").split("/MainMenu")[0]; form.setDownloadURL( urlBase + "/rest2/openrosa/" + studyOID + "/formXml?formId=" + version.getOid()); List<CrfVersionMedia> mediaList = mediaDao.findByCrfVersionId(version.getId()); if (mediaList != null && mediaList.size() > 0) { form.setManifestURL( urlBase + "/rest2/openrosa/" + studyOID + "/manifest?formId=" + version.getOid()); } formList.add(form); } } } // Create the XML formList using a Castor mapping file. XMLContext xmlContext = new XMLContext(); Mapping mapping = xmlContext.createMapping(); mapping.loadMapping(getCoreResources().getURL("openRosaFormListMapping.xml")); xmlContext.addMapping(mapping); Marshaller marshaller = xmlContext.createMarshaller(); StringWriter writer = new StringWriter(); marshaller.setWriter(writer); marshaller.marshal(formList); // Set response headers Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Date currentDate = new Date(); cal.setTime(currentDate); SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zz"); format.setCalendar(cal); response.setHeader("Content-Type", "text/xml; charset=UTF-8"); response.setHeader("Date", format.format(currentDate)); response.setHeader("X-OpenRosa-Version", "1.0"); return writer.toString(); } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); return "<Error>" + e.getMessage() + "</Error>"; } }
public static void main(String argv[]) throws Exception { int i, start, end; ; SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mm:ss a"); GregorianCalendar cal = new GregorianCalendar(); SmbFile f; if (argv.length < 2) { throw new IllegalArgumentException("usage: FileInfo <url> <opindex>"); } if (argv.length == 3) { SmbFile tmp = new SmbFile(argv[0]); f = new SmbFile(tmp.toString(), argv[1]); start = Integer.parseInt(argv[2]); } else { f = new SmbFile(argv[0]); start = Integer.parseInt(argv[1]); } sdf.setCalendar(cal); i = end = start; do { switch (i) { case 0: System.out.println(" toString: " + f.toString()); break; case 1: System.out.println(" toURL: " + f.toURL()); break; case 2: System.out.println(" getName: " + f.getName()); break; case 3: System.out.println(" length: " + f.length()); break; case 4: System.out.println(" getLastModified: " + sdf.format(new Date(f.getLastModified()))); break; case 5: System.out.println(" isHidden: " + f.isHidden()); break; case 6: System.out.println(" isFile: " + f.isFile()); break; case 7: System.out.println(" isDirectory: " + f.isDirectory()); break; case 8: System.out.println(" hashCode: " + f.hashCode()); break; case 9: System.out.println(" getUncPath: " + f.getUncPath()); break; case 10: System.out.println(" getType: " + TYPES[f.getType()]); break; case 11: System.out.println(" getShare: " + f.getShare()); break; case 12: System.out.println(" getServer: " + f.getServer()); break; case 13: System.out.println(" getPath: " + f.getPath()); break; case 14: System.out.println(" getParent: " + f.getParent()); break; case 15: System.out.println(" lastModified: " + sdf.format(new Date(f.lastModified()))); break; case 16: System.out.println("getDiskFreeSpace: " + f.getDiskFreeSpace()); break; case 17: System.out.println(" getDate: " + sdf.format(new Date(f.getDate()))); break; case 18: System.out.println("getContentLength: " + f.getContentLength()); break; case 19: System.out.println("getCanonicalPath: " + f.getCanonicalPath()); break; case 20: System.out.println(" exists: " + f.exists()); break; case 21: System.out.println(" canRead: " + f.canRead()); break; case 22: System.out.println(" canWrite: " + f.canWrite()); break; case 23: ACE[] security = f.getSecurity(true); System.out.println(" Security:"); for (int ai = 0; ai < security.length; ai++) { System.out.println(security[ai].toString()); } System.out.println(" Share Perm:"); security = f.getShareSecurity(true); for (int ai = 0; ai < security.length; ai++) { System.out.println(security[ai].toString()); } break; case 24: System.out.println(" getDfsPath: " + f.getDfsPath()); break; } i++; if (i == 25) { i = 0; } } while (i != end); }
/** * @api {get} /rest2/openrosa/:studyOID/manifest Get Form Manifest * @apiName getManifest * @apiPermission admin * @apiVersion 1.0.0 * @apiParam {String} studyOID Study Oid. * @apiGroup Form * @apiDescription Gets additional information on a particular Form, including links to associated * media. */ @GET @Path("/{studyOID}/manifest") @Produces(MediaType.TEXT_XML) public String getManifest( @Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("studyOID") String studyOID, @QueryParam("formId") String crfOID, @RequestHeader("Authorization") String authorization, @Context ServletContext context) throws Exception { if (!mayProceedPreview(studyOID)) return null; CRFVersionDAO cVersionDao = new CRFVersionDAO(getDataSource()); CrfVersionMediaDao mediaDao = (CrfVersionMediaDao) SpringServletAccess.getApplicationContext(context).getBean("crfVersionMediaDao"); CRFVersionBean crfVersion = cVersionDao.findByOid(crfOID); List<MediaFile> mediaFiles = new ArrayList<MediaFile>(); Manifest manifest = new Manifest(); List<CrfVersionMedia> mediaList = mediaDao.findByCrfVersionId(crfVersion.getId()); if (mediaList != null && mediaList.size() > 0) { for (CrfVersionMedia media : mediaList) { Calendar cal = Calendar.getInstance(); cal.setTime(new Date()); String urlBase = getCoreResources().getDataInfo().getProperty("sysURL").split("/MainMenu")[0]; MediaFile mediaFile = new MediaFile(); mediaFile.setFilename(media.getName()); mediaFile.setHash(DigestUtils.md5Hex(String.valueOf(cal.getTimeInMillis()))); mediaFile.setDownloadUrl( urlBase + "/rest2/openrosa/" + studyOID + "/downloadMedia?crfVersionMediaId=" + media.getCrfVersionMediaId()); manifest.add(mediaFile); } } try { // Create the XML manifest using a Castor mapping file. XMLContext xmlContext = new XMLContext(); Mapping mapping = xmlContext.createMapping(); mapping.loadMapping(getCoreResources().getURL("openRosaManifestMapping.xml")); xmlContext.addMapping(mapping); Marshaller marshaller = xmlContext.createMarshaller(); StringWriter writer = new StringWriter(); marshaller.setWriter(writer); marshaller.marshal(manifest); // Set response headers Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Date currentDate = new Date(); cal.setTime(currentDate); SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zz"); format.setCalendar(cal); response.setHeader("Content-Type", "text/xml; charset=UTF-8"); response.setHeader("Date", format.format(currentDate)); response.setHeader("X-OpenRosa-Version", "1.0"); return writer.toString(); } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); return "<Error>" + e.getMessage() + "</Error>"; } }
/** * @api {post} /pages/api/v1/editform/:studyOid/submission Submit form data * @apiName doSubmission * @apiPermission admin * @apiVersion 1.0.0 * @apiParam {String} studyOid Study Oid. * @apiParam {String} ecid Key that will be used to look up subject context information while * processing submission. * @apiGroup Form * @apiDescription Submits the data from a completed form. */ @POST @Path("/{studyOID}/submission") @Produces(MediaType.APPLICATION_XML) public Response doSubmission( @Context HttpServletRequest request, @Context HttpServletResponse response, @Context ServletContext servletContext, @PathParam("studyOID") String studyOID, @QueryParam(FORM_CONTEXT) String context) { String output = null; Response.ResponseBuilder builder = Response.noContent(); String studySubjectOid = null; Integer studyEventDefnId = null; Integer studyEventOrdinal = null; String crfVersionOID = null; CRFVersionDAO crfvdao = new CRFVersionDAO(dataSource); try { if (ServletFileUpload.isMultipartContent(request)) { LOGGER.warn("WARNING: This prototype doesn't support multipart content."); } if (!mayProceedSubmission(studyOID)) builder.status(javax.ws.rs.core.Response.Status.NOT_ACCEPTABLE).build(); PFormCache cache = PFormCache.getInstance(servletContext); HashMap<String, String> userContext = cache.getSubjectContext(context); StudySubjectDAO ssdao = new StudySubjectDAO<String, ArrayList>(dataSource); StudySubjectBean ssBean = getSSBean(userContext); if (!mayProceedSubmission(studyOID, ssBean)) return null; studyEventDefnId = Integer.valueOf(userContext.get("studyEventDefinitionID")); studyEventOrdinal = Integer.valueOf(userContext.get("studyEventOrdinal")); crfVersionOID = userContext.get("crfVersionOID"); StringWriter writer = new StringWriter(); String body = IOUtils.toString(request.getInputStream(), "UTF-8"); CRFVersionBean crfVersion = crfvdao.findByOid(crfVersionOID); if (crfVersion.getXform() != null && !crfVersion.getXform().equals("")) { body = body.substring(body.indexOf("<" + crfVersion.getXformName())); int length = body.indexOf(" "); body = body.replace( body.substring(body.lastIndexOf("<meta>"), body.lastIndexOf("</meta>") + 7), ""); body = body.substring(0, body.lastIndexOf("</" + crfVersion.getXformName()) + length + 2); body = "<instance>" + body + "</instance>"; } else { body = body.substring(body.indexOf("<F_")); int length = body.indexOf(" "); body = body.replace(body.substring(body.indexOf("<meta>"), body.indexOf("</meta>") + 7), ""); body = body.substring(0, body.indexOf("</F_") + length + 2); body = "<instance>" + body + "</instance>"; } Errors errors = getPformSubmissionService() .saveProcess( body, ssBean.getOid(), studyEventDefnId, studyEventOrdinal, crfvdao.findByOid(crfVersionOID)); // Set response headers Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Date currentDate = new Date(); cal.setTime(currentDate); SimpleDateFormat format = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss zz"); format.setCalendar(cal); builder.header("Date", format.format(currentDate)); builder.header("X-OpenRosa-Version", "1.0"); builder.type("text/xml; charset=utf-8"); if (!errors.hasErrors()) { builder.entity( "<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">" + "<message>success</message>" + "</OpenRosaResponse>"); LOGGER.debug("Successful OpenRosa submission"); } else { LOGGER.error("Failed OpenRosa submission"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.flushBuffer(); } } catch (Exception e) { LOGGER.error(e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); return builder.status(javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR).build(); } try { // Notify Participate of successful form submission. String pManageUrl = CoreResources.getField("portalURL") + "/app/rest/oc/submission"; Submission submission = new Submission(); Study pManageStudy = new Study(); pManageStudy.setInstanceUrl( CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOID); pManageStudy.setStudyOid(studyOID); submission.setStudy(pManageStudy); submission.setStudy_event_def_id(studyEventDefnId); submission.setStudy_event_def_ordinal(studyEventOrdinal); submission.setCrf_version_id(crfvdao.findByOid(crfVersionOID).getId()); RestTemplate rest = new RestTemplate(); String result = rest.postForObject(pManageUrl, submission, String.class); LOGGER.debug("Notified Participate of CRF submission with a result of: " + result); } catch (Exception e) { LOGGER.error("Unable to notify Participate of successful CRF submission."); LOGGER.error(e.getMessage()); LOGGER.error(ExceptionUtils.getStackTrace(e)); } return builder.status(javax.ws.rs.core.Response.Status.CREATED).build(); }
public Object objectDone() { String name = curName(); Object o = super.objectDone(); BSONObject b = (BSONObject) o; // override the object if it's a special type if (!_lastArray) { if (b.containsField("$oid")) { o = new ObjectId((String) b.get("$oid")); if (!isStackEmpty()) { gotObjectId(name, (ObjectId) o); } else { setRoot(o); } } else if (b.containsField("$date")) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); GregorianCalendar calendar = new GregorianCalendar(new SimpleTimeZone(0, "GMT")); format.setCalendar(calendar); String txtdate = (String) b.get("$date"); o = format.parse(txtdate, new ParsePosition(0)); if (o == null) { // try older format with no ms format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); format.setCalendar(calendar); o = format.parse(txtdate, new ParsePosition(0)); } if (!isStackEmpty()) { cur().put(name, o); } else { setRoot(o); } } else if (b.containsField("$regex")) { o = Pattern.compile((String) b.get("$regex"), BSON.regexFlags((String) b.get("$options"))); if (!isStackEmpty()) { cur().put(name, o); } else { setRoot(o); } } else if (b.containsField("$ts")) { Long ts = ((Number) b.get("$ts")).longValue(); Long inc = ((Number) b.get("$inc")).longValue(); o = new BSONTimestamp(ts.intValue(), inc.intValue()); if (!isStackEmpty()) { cur().put(name, o); } else { setRoot(o); } } else if (b.containsField("$code")) { if (b.containsField("$scope")) { o = new CodeWScope((String) b.get("$code"), (DBObject) b.get("$scope")); } else { o = new Code((String) b.get("$code")); } if (!isStackEmpty()) { cur().put(name, o); } else { setRoot(o); } } else if (b.containsField("$ref")) { o = new DBRef(null, (String) b.get("$ref"), b.get("$id")); if (!isStackEmpty()) { cur().put(name, o); } else { setRoot(o); } } else if (b.containsField("$minKey")) { o = new MinKey(); if (!isStackEmpty()) { cur().put(name, o); } else { setRoot(o); } } else if (b.containsField("$maxKey")) { o = new MaxKey(); if (!isStackEmpty()) { cur().put(name, o); } else { setRoot(o); } } else if (b.containsField("$uuid")) { o = UUID.fromString((String) b.get("$uuid")); if (!isStackEmpty()) { cur().put(name, o); } else { setRoot(o); } } } return o; }