List of usage examples for java.text ParseException toString
public String toString()
From source file:org.ow2.aspirerfid.queryandcapture.ui.MasterDataQueryAndCaptureGui.java
/** * /*from w w w . ja v a 2s . c o m*/ */ private void querySubmitButtonPressed() { // SetUp the EPCIS Repository Query URL queryClient = new MasterDataQueryClient(queryServiceUrlText.getText()); /** * Contains the data for the result table. */ Object[][] data = {}; try { checkQueryUrl(captureServiceUrlText.getText(), queryClient); queryClient.clearParameters(); QueryParam queryParam = new QueryParam(); queryParam.setName("eventType"); queryParam.setValue("SimpleMasterDataQuery"); queryClient.addParameter(queryParam); QueryParam param2 = new QueryParam(); param2.setName("includeAttributes"); param2.setValue(includeAttributesButton.getSelection()); queryClient.addParameter(param2); QueryParam param3 = new QueryParam(); param3.setName("includeChildren"); param3.setValue(includeChildrenButton.getSelection()); queryClient.addParameter(param3); ArrayOfString vocabularyNames = new ArrayOfString(); vocabularyNames.getString().add(eq_nameText.getText()); QueryParam param4 = new QueryParam(); param4.setName("EQ_name"); param4.setValue(vocabularyNames); queryClient.addParameter(param4); ArrayOfString vocabularyType = new ArrayOfString(); vocabularyType.getString().add(vocabularyTypeCombo.getText()); QueryParam param5 = new QueryParam(); param5.setName("vocabularyName"); param5.setValue(vocabularyType); queryClient.addParameter(param5); data = queryClient.runMasterDataQuery(); if (!data.equals(null)) { System.out.println("Data retrieved from the query:"); for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { if (data[i][j] != null) { System.out.println(data[i][j]); } } } } } catch (ParseException e) { String msg = "Unable to parse a Time value."; System.out.print("\n" + msg + "\n"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); System.out.print(sw.toString()); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, msg + "\n" + e.getMessage(), "Service invocation error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { String msg = "Unexpected error while invoking EPCIS Query Interface."; System.out.print("\n" + msg + "\n"); System.out.print(e.toString()); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); System.out.print(sw.toString()); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, msg + "\n" + e.toString(), "Service invocation error", JOptionPane.ERROR_MESSAGE); } }
From source file:edu.arizona.rice.kew.docsearch.dao.impl.DocumentSearchDAOJdbcImpl.java
private DateTime[] getFromToDatesFromBewteenOperatorString(String input) { DateTime[] retval = null;/*w w w . j a v a 2 s .c o m*/ if (StringUtils.isNotBlank(input) && input.contains(DocumentSearchConstants.DATE_BETWEEN_OPERATOR)) { int pos1 = input.indexOf("."); try { retval = new DateTime[] { new DateTime(DocumentSearchConstants.INPUT_DATE_FORMAT.parse(input.substring(0, pos1))), new DateTime(DocumentSearchConstants.INPUT_DATE_FORMAT.parse(input.substring(pos1 + 2))) }; } catch (ParseException ex) { LOG.error(ex.toString(), ex); } } return retval; }
From source file:org.ow2.aspirerfid.beg.simmulator.BegSimmCore.java
/** * @param repositoryQueryURL//from w ww.java 2 s . co m * @return List of VocabularyElementType */ public List<VocabularyElementType> getEventList(String repositoryQueryURL) { // SetUp the EPCIS Repository Query URL MasterDataQueryClient queryClient = new MasterDataQueryClient(repositoryQueryURL); List<VocabularyElementType> vocabularyElementList = null; // Contains the data for the result table. List<VocabularyType> vocabularyList = null; try { queryClient.clearParameters(); QueryParam queryParam = new QueryParam(); queryParam.setName("eventType"); queryParam.setValue("SimpleMasterDataQuery"); queryClient.addParameter(queryParam); QueryParam param2 = new QueryParam(); param2.setName("includeAttributes"); param2.setValue(true); queryClient.addParameter(param2); QueryParam param3 = new QueryParam(); param3.setName("includeChildren"); param3.setValue(false); queryClient.addParameter(param3); ArrayOfString vocabularyType = new ArrayOfString(); vocabularyType.getString().add("urn:epcglobal:epcis:vtype:BusinessTransaction"); QueryParam param5 = new QueryParam(); param5.setName("vocabularyName"); param5.setValue(vocabularyType); queryClient.addParameter(param5); vocabularyList = queryClient.runMasterDataQuery(); } catch (ParseException e) { String msg = "Unable to parse a Time value."; System.out.print("\n" + msg + "\n"); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); System.out.print(sw.toString()); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, msg + "\n" + e.getMessage(), "Service invocation error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { String msg = "Unexpected error while invoking EPCIS Query Interface."; System.out.print("\n" + msg + "\n"); System.out.print(e.toString()); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); System.out.print(sw.toString()); JFrame frame = new JFrame(); JOptionPane.showMessageDialog(frame, msg + "\n" + e.toString(), "Service invocation error", JOptionPane.ERROR_MESSAGE); } for (Object o : vocabularyList) { if (o instanceof JAXBElement<?>) { o = ((JAXBElement<?>) o).getValue(); } VocabularyType vocabulary = (VocabularyType) o; vocabularyElementList = vocabulary.getVocabularyElementList().getVocabularyElement(); } return cleanVocabularyElementsParents(vocabularyElementList); }
From source file:contestWebsite.MainPage.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets, html/templates"); ve.init();//w w w . ja v a2 s . c o m VelocityContext context = new VelocityContext(); Pair<Entity, UserCookie> infoAndCookie = init(context, req); UserCookie userCookie = infoAndCookie.y; Entity user = userCookie != null ? userCookie.authenticateUser() : null; boolean loggedIn = (boolean) context.get("loggedIn"); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); if (loggedIn && !userCookie.isAdmin()) { Entity contestInfo = infoAndCookie.x; String endDateStr = (String) contestInfo.getProperty("editEndDate"); String startDateStr = (String) contestInfo.getProperty("editStartDate"); Date endDate = new Date(); Date startDate = new Date(); try { endDate = new SimpleDateFormat("MM/dd/yyyy").parse(endDateStr); startDate = new SimpleDateFormat("MM/dd/yyyy").parse(startDateStr); } catch (ParseException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Incorrect date format"); } if (new Date().after(endDate) || new Date().before(startDate)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Registration editing deadline passed."); } else { Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, user.getProperty("user-id"))); Entity registration = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0); String studentData = req.getParameter("studentData"); JSONArray regData = null; try { regData = new JSONArray(studentData); } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } long price = (Long) infoAndCookie.x.getProperty("price"); int cost = (int) (0 * price); for (int i = 0; i < regData.length(); i++) { try { JSONObject studentRegData = regData.getJSONObject(i); for (Subject subject : Subject.values()) { cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0); } } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } registration.setProperty("cost", cost); registration.setProperty("studentData", new Text(studentData)); Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { datastore.put(registration); txn.commit(); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } resp.sendRedirect("/?updated=1"); } } else if (loggedIn && userCookie.isAdmin()) { String username = req.getParameter("email").toLowerCase(); Query query = new Query("user") .setFilter(new FilterPredicate("user-id", FilterOperator.EQUAL, username)); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); if (users.size() >= 1) { Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { query = new Query("authToken").setKeysOnly(); Filter tokenFilter = new FilterPredicate("token", FilterOperator.EQUAL, URLDecoder.decode(userCookie.getValue(), "UTF-8")); Filter expiredFilter = new FilterPredicate("expires", FilterOperator.LESS_THAN, new Date()); query.setFilter(CompositeFilterOperator.or(tokenFilter, expiredFilter)); datastore.delete( datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()).get(0).getKey()); userCookie.setMaxAge(0); userCookie.setValue(""); resp.addCookie(userCookie); SecureRandom random = new SecureRandom(); String authToken = new BigInteger(130, random).toString(32); Entity token = new Entity("authToken"); token.setProperty("user-id", username); token.setProperty("token", authToken); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 60); token.setProperty("expires", new Date(calendar.getTimeInMillis())); Cookie cookie = new Cookie("authToken", authToken); cookie.setValue(authToken); resp.addCookie(cookie); datastore.put(token); datastore.put(user); resp.sendRedirect("/"); txn.commit(); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } } else { resp.sendRedirect("/?error=1"); } } else { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User account required for that operation"); } }
From source file:gov.usda.DataCatalogClient.Dataset.java
/** * For each CKAN extra loads into this dataset object. * @param extraList//w w w.j av a2 s . co m * @throws DatasetException */ private void loadExtraListFromCKAN(JSONArray extraList) throws DatasetException { for (int i = 0; i < extraList.size(); i++) { JSONObject extraObject = (JSONObject) extraList.get(i); String key = (String) extraObject.get("key"); String value = (String) extraObject.get("value"); try { loadExtraFromCKAN(key, value); } catch (ParseException e) { dsEx.addError(e.toString()); } } }
From source file:gov.usda.DataCatalogClient.Dataset.java
public void setBureauCodeList(Object bureauCodeList) { if (bureauCodeList == null) { throw new NullPointerException("bureauCodeList cannot be null"); }/*ww w . ja v a 2s . c o m*/ if (bureauCodeList instanceof ArrayList) { setBureauCodeList((ArrayList<String>) bureauCodeList); } else if (bureauCodeList instanceof JSONArray) { final JSONArray bureauArray = (JSONArray) bureauCodeList; for (int i = 0; i < bureauArray.size(); i++) { try { setBureauCodeList((String) bureauArray.get(i)); } catch (ParseException e) { dsEx.addError(e.toString()); } } } }
From source file:gov.usda.DataCatalogClient.Dataset.java
public void setProgramCodeList(Object programCodeList) { if (programCodeList == null) { throw new NullPointerException("programCodeList cannot be null"); }//from w w w.j a va 2 s . c om if (programCodeList instanceof ArrayList) { setProgramCodeList((ArrayList<String>) programCodeList); } else if (programCodeList instanceof JSONArray) { final JSONArray programArray = (JSONArray) programCodeList; for (int i = 0; i < programArray.size(); i++) { try { setProgramCodeList((String) programArray.get(i)); } catch (ParseException e) { dsEx.addError(e.toString()); } } } }
From source file:gov.usda.DataCatalogClient.Dataset.java
/** * This method takes a valid data.json file that conforms to Dataset in Project open data * and loads it into Dataset object./*from w ww .j a v a 2 s .co m*/ * @param podFileName String The name of the file to import. * @throws DatasetException This is thrown when the data.json file is not valid Project Open Data 1.1 json format. * This can include business validation rules. * @throws IOException This is thrown if there is issue reading the file, most likely file does not exist */ public void loadDatasetFromFile(String podFileName) throws DatasetException, IOException { JSONObject datasetObject; try { datasetObject = Utils.loadJsonObjectFile(podFileName); } catch (org.json.simple.parser.ParseException e) { throw new IOException("Invalid JSON file:" + podFileName + " " + e.toString()); } loadFromProjectOpenDataJSON(datasetObject); }
From source file:org.apache.ode.bpel.engine.ProcessAndInstanceManagementImpl.java
/** * Query processes based on a {@link ProcessFilter} criteria. This is * implemented in memory rather than via database calls since the processes * are managed by the {@link ProcessStore} object and we don't want to make * this needlessly complicated./*from w w w . j a v a 2 s . com*/ * * @param filter * @return */ @SuppressWarnings("unchecked") Collection<ProcessConf> processQuery(ProcessFilter filter) { List<QName> pids = _store.getProcesses(); // Name filter can be implemented using only the PIDs. if (filter != null && filter.getNameFilter() != null) { final Pattern pattern = Pattern.compile(filter.getNameFilter().replace("*", ".*") + "(-\\d*)?"); CollectionsX.remove_if(pids, new MemberOfFunction<QName>() { @Override public boolean isMember(QName o) { return !pattern.matcher(o.getLocalPart()).matches(); } }); } if (filter != null && filter.getNamespaceFilter() != null) { final Pattern pattern = Pattern.compile(filter.getNamespaceFilter().replace("*", ".*")); CollectionsX.remove_if(pids, new MemberOfFunction<QName>() { @Override public boolean isMember(QName o) { String ns = o.getNamespaceURI() == null ? "" : o.getNamespaceURI(); return !pattern.matcher(ns).matches(); } }); } // Now we need the process conf objects, we need to be // careful since someone could have deleted them by now List<ProcessConf> confs = new LinkedList<ProcessConf>(); for (QName pid : pids) { ProcessConf pconf = _store.getProcessConfiguration(pid); confs.add(pconf); } if (filter != null) { // TODO Implement process status filtering when status will exist // Specific filter for deployment date. if (filter.getDeployedDateFilter() != null) { for (final String ddf : filter.getDeployedDateFilter()) { final Date dd; try { dd = ISO8601DateParser.parse(Filter.getDateWithoutOp(ddf)); } catch (ParseException e) { // Should never happen. __log.error("Exception while parsing date", e); throw new RuntimeException(e.toString()); } CollectionsX.remove_if(confs, new MemberOfFunction<ProcessConf>() { @Override public boolean isMember(ProcessConf o) { if (ddf.startsWith("=")) return !o.getDeployDate().equals(dd); if (ddf.startsWith("<=")) return o.getDeployDate().getTime() > dd.getTime(); if (ddf.startsWith(">=")) return o.getDeployDate().getTime() < dd.getTime(); if (ddf.startsWith("<")) return o.getDeployDate().getTime() >= dd.getTime(); if (ddf.startsWith(">")) return o.getDeployDate().getTime() <= dd.getTime(); return false; } }); } } // Ordering if (filter.getOrders() != null) { ComparatorChain cchain = new ComparatorChain(); for (String key : filter.getOrders()) { boolean ascending = true; String orderKey = key; if (key.startsWith("+") || key.startsWith("-")) { orderKey = key.substring(1, key.length()); if (key.startsWith("-")) ascending = false; } Comparator c; if ("name".equals(orderKey)) c = new Comparator<ProcessConf>() { public int compare(ProcessConf o1, ProcessConf o2) { return o1.getProcessId().getLocalPart().compareTo(o2.getProcessId().getLocalPart()); } }; else if ("namespace".equals(orderKey)) c = new Comparator<ProcessConf>() { public int compare(ProcessConf o1, ProcessConf o2) { String ns1 = o1.getProcessId().getNamespaceURI() == null ? "" : o1.getProcessId().getNamespaceURI(); String ns2 = o2.getProcessId().getNamespaceURI() == null ? "" : o2.getProcessId().getNamespaceURI(); return ns1.compareTo(ns2); } }; else if ("version".equals(orderKey)) c = new Comparator<ProcessConf>() { public int compare(ProcessConf o1, ProcessConf o2) { // TODO: implement version comparisons. return 0; } }; else if ("deployed".equals(orderKey)) c = new Comparator<ProcessConf>() { public int compare(ProcessConf o1, ProcessConf o2) { return o1.getDeployDate().compareTo(o2.getDeployDate()); } }; else { // unrecognized __log.debug("unrecognized order key" + orderKey); continue; } cchain.addComparator(c, !ascending); } Collections.sort(confs, cchain); } } return confs; }
From source file:com.opentransport.rdfmapper.nmbs.NetworkDisturbanceFetcher.java
private void scrapeNetworkDisturbanceWebsite(String language, String _url) { Document doc;// ww w . ja va2 s .com int i = 0; //English Version try { URL url = new URL(_url); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); // Convert to a JSON object to print data JsonParser jp = new JsonParser(); //from gson JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element JsonArray disturbances = root.getAsJsonObject().getAsJsonArray("him"); for (JsonElement el : disturbances) { JsonObject obj = (JsonObject) el; String header = obj.get("header").getAsString(); String description = obj.get("text").getAsString(); String urls = ""; // todo check JsonNull String begin = obj.get("begin").getAsString(); // dd.MM.yyyy HH:mm String end = obj.get("end").getAsString(); // dd.MM.yyyy HH:mm SimpleDateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm"); df.setTimeZone(TimeZone.getTimeZone("Europe/Brussels")); Date date; long startEpoch, endEpoch; try { date = df.parse(begin); startEpoch = date.getTime() / 1000; date = df.parse(end); endEpoch = date.getTime() / 1000; } catch (ParseException ex) { // When time range is missing, take 12 hours before and after startEpoch = new Date().getTime() - 43200; endEpoch = new Date().getTime() + 43200; Logger.getLogger(NetworkDisturbanceFetcher.class.getName()).log(Level.SEVERE, null, ex); } int startStationId, endStationId, impactStationId; if (obj.has("startstation_extId")) { startStationId = obj.get("startstation_extId").getAsInt(); } else { startStationId = -1; } if (obj.has("endstation_extId")) { endStationId = obj.get("endstation_extId").getAsInt(); } else { endStationId = -1; } if (obj.has("impactstation_extId")) { impactStationId = obj.get("impactstation_extId").getAsInt(); } else { impactStationId = -1; } String id = obj.get("id").getAsString(); NetworkDisturbance disturbance = new NetworkDisturbance(header, description, urls, language, startEpoch, endEpoch, startStationId, endStationId, impactStationId, id); networkDisturbances.add(disturbance); } } catch (IOException ex) { Logger.getLogger(NetworkDisturbanceFetcher.class.getName()).log(Level.SEVERE, null, ex); errorWriter.writeError(ex.toString()); } }