List of usage examples for javax.xml.bind DatatypeConverter parseDateTime
public static java.util.Calendar parseDateTime(String lexicalXSDDateTime)
Converts the string argument into a Calendar value.
From source file:org.eclipse.lyo.testsuite.oslcv2.CoreResourceXmlTests.java
@Test public void CoreResourceHasAtMostOneModifiedDate() throws XPathExpressionException { String eval = "//" + getNode() + "/" + "dc:modified"; NodeList modifiedDates = (NodeList) OSLCUtils.getXPath().evaluate(eval, doc, XPathConstants.NODESET); assertTrue(getFailureMessage(), modifiedDates.getLength() <= 1); //If there is a modified date, verify the format. if (modifiedDates.getLength() > 0) { try {//from ww w . ja v a2 s. c om final String dateString = modifiedDates.item(0).getTextContent(); DatatypeConverter.parseDateTime(dateString); } catch (Exception e) { fail("Modified date not in valid XSD format"); } } }
From source file:de.gesundkrank.wikipedia.hadoop.parser.Parser.java
private static long matchTimestamp(String line) { Matcher timestampMatcher = TIMESTAMP_PATTERN.matcher(line); if (timestampMatcher.matches()) { String timeString = timestampMatcher.group(1); return DatatypeConverter.parseDateTime(timeString).getTimeInMillis(); }/*from w w w . ja va 2s . c o m*/ return -1; }
From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java
@Test public void changeRequestHasAtMostOneModifiedDate() throws XPathExpressionException { NodeList modifiedDates = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm_v2:ChangeRequest/dc:modified", doc, XPathConstants.NODESET); assertTrue(getFailureMessage(), modifiedDates.getLength() <= 1); //If there is a modified date, verify the format. if (modifiedDates.getLength() > 0) { try {// www .ja v a 2 s .co m final String dateString = modifiedDates.item(0).getTextContent(); DatatypeConverter.parseDateTime(dateString); } catch (Exception e) { fail("Modified date not in valid XSD format"); } } }
From source file:com.marklogic.client.test.BitemporalTest.java
@Test public void c_testOther() throws Exception { String version1 = "<test>" + uniqueTerm + " version1" + "<system-start></system-start>" + "<system-end></system-end>" + "<valid-start>2014-08-19T00:00:00Z</valid-start>" + "<valid-end>2014-08-19T00:00:01Z</valid-end>" + "</test>"; String version2 = "<test>" + uniqueTerm + " version2" + "<system-start></system-start>" + "<system-end></system-end>" + "<valid-start>2014-08-19T00:00:02Z</valid-start>" + "<valid-end>2014-08-19T00:00:03Z</valid-end>" + "</test>"; String version3 = "<test>" + uniqueTerm + " version3" + "<system-start></system-start>" + "<system-end></system-end>" + "<valid-start>2014-08-19T00:00:03Z</valid-start>" + "<valid-end>2014-08-19T00:00:04Z</valid-end>" + "</test>"; String version4 = "<test>" + uniqueTerm + " version4" + "<system-start></system-start>" + "<system-end></system-end>" + "<valid-start>2014-08-19T00:00:05Z</valid-start>" + "<valid-end>2014-08-19T00:00:06Z</valid-end>" + "</test>"; // write four versions of the same document StringHandle handle1 = new StringHandle(version1).withFormat(Format.XML); docMgr.write(docId, null, handle1, null, null, temporalCollection); StringHandle handle2 = new StringHandle(version2).withFormat(Format.XML); docMgr.write(docId, null, handle2, null, null, temporalCollection); StringHandle handle3 = new StringHandle(version3).withFormat(Format.XML); TemporalDescriptor desc = docMgr.write(docId, null, handle3, null, null, temporalCollection); assertNotNull("Missing TemporalDescriptor from write", desc); assertEquals(docId, desc.getUri());//from www . j a va 2s .co m String thirdWriteTimestamp = desc.getTemporalSystemTime(); Calendar thirdWriteTime = DatatypeConverter.parseDateTime(thirdWriteTimestamp); assertNotNull(thirdWriteTime); // add one millisecond since server precision is more precise, so Java truncates // fractions of a second here. Adding one millisecond ensures we're above the // system time for the last write for the document thirdWriteTime.roll(Calendar.MILLISECOND, true); StringHandle handle4 = new StringHandle(version4).withFormat(Format.XML); docMgr.write(docId, null, handle4, null, null, temporalCollection); // make sure non-temporal document read only returns the latest version DocumentPage readResults = docMgr.read(docId); assertEquals("Wrong number of results", 1, readResults.size()); DocumentRecord latestDoc = readResults.next(); assertEquals("Document uri wrong", docId, latestDoc.getUri()); // make sure a simple term query returns all versions of bulk and other docs StructuredQueryBuilder sqb = queryMgr.newStructuredQueryBuilder(); StructuredQueryDefinition termsQuery = sqb.or(sqb.term(uniqueTerm), sqb.term(uniqueBulkTerm)); long start = 1; DocumentPage termQueryResults = docMgr.search(termsQuery, start); assertEquals("Wrong number of results", 12, termQueryResults.size()); // temporal-collection is configured to automatically advance lsqt every 1 second // so we'll sleep for 2 seconds to make sure lsqt has advanced beyond the lsqt // when we inserted our documents Thread.sleep(2000); // query with lsqt of last inserted document // will match the first three versions -- not the last because it's equal to // not greater than the timestamp of this lsqt query StructuredQueryDefinition currentQuery = sqb.temporalLsqtQuery(temporalCollection, thirdWriteTime, 1); StructuredQueryDefinition currentDocQuery = sqb.and(termsQuery, currentQuery); DocumentPage currentDocQueryResults = docMgr.search(currentDocQuery, start); assertEquals("Wrong number of results", 11, currentDocQueryResults.size()); // query with blank lsqt indicating current time // will match all four versions currentQuery = sqb.temporalLsqtQuery(temporalCollection, "", 1); currentDocQuery = sqb.and(termsQuery, currentQuery); currentDocQueryResults = docMgr.search(currentDocQuery, start); assertEquals("Wrong number of results", 12, currentDocQueryResults.size()); StructuredQueryBuilder.Axis validAxis = sqb.axis("valid-axis"); // create a time axis to query the versions against Calendar start1 = DatatypeConverter.parseDateTime("2014-08-19T00:00:00Z"); Calendar end1 = DatatypeConverter.parseDateTime("2014-08-19T00:00:04Z"); StructuredQueryBuilder.Period period1 = sqb.period(start1, end1); // find all documents contained in the time range of our query axis StructuredQueryDefinition periodQuery1 = sqb.and(termsQuery, sqb.temporalPeriodRange(validAxis, TemporalOperator.ALN_CONTAINED_BY, period1)); DocumentPage periodQuery1Results = docMgr.search(periodQuery1, start); assertEquals("Wrong number of results", 3, periodQuery1Results.size()); // create a second time axis to query the versions against Calendar start2 = DatatypeConverter.parseDateTime("2014-08-19T00:00:04Z"); Calendar end2 = DatatypeConverter.parseDateTime("2014-08-19T00:00:07Z"); StructuredQueryBuilder.Period period2 = sqb.period(start2, end2); // find all documents contained in the time range of our second query axis StructuredQueryDefinition periodQuery2 = sqb.and(termsQuery, sqb.temporalPeriodRange(validAxis, TemporalOperator.ALN_CONTAINED_BY, period2)); DocumentPage periodQuery2Results = docMgr.search(periodQuery2, start); assertEquals("Wrong number of results", 3, periodQuery2Results.size()); for (DocumentRecord result : periodQuery2Results) { if (docId.equals(result.getUri())) { continue; } else if (result.getUri().startsWith("test_" + uniqueBulkTerm + "_4")) { continue; } fail("Unexpected uri for ALN_CONTAINED_BY test:" + result.getUri()); } // find all documents where valid time is after system time in the document StructuredQueryBuilder.Axis systemAxis = sqb.axis("system-axis"); StructuredQueryDefinition periodCompareQuery1 = sqb.and(termsQuery, sqb.temporalPeriodCompare(systemAxis, TemporalOperator.ALN_AFTER, validAxis)); DocumentPage periodCompareQuery1Results = docMgr.search(periodCompareQuery1, start); assertEquals("Wrong number of results", 12, periodCompareQuery1Results.size()); // find all documents where valid time is before system time in the document StructuredQueryDefinition periodCompareQuery2 = sqb.and(termsQuery, sqb.temporalPeriodCompare(systemAxis, TemporalOperator.ALN_BEFORE, validAxis)); DocumentPage periodCompareQuery2Results = docMgr.search(periodCompareQuery2, start); assertEquals("Wrong number of results", 0, periodCompareQuery2Results.size()); // check that we get a system time when we delete desc = docMgr.delete(docId, null, temporalCollection); assertNotNull("Missing TemporalDescriptor from delete", desc); assertEquals(docId, desc.getUri()); assertNotNull("Missing temporalSystemTime from delete", desc.getTemporalSystemTime()); }
From source file:iing.uabc.edu.mx.persistencia.util.JSON.java
private static Collection parseArray(JsonParser parser, CollectionManager manager) { Event evt;/*from w w w . j a va 2 s .c o m*/ Class elementClass = manager.getElementClass(); int pos = 0; do { evt = parser.next(); switch (evt) { case START_OBJECT: //The most expected case of all in an array System.out.println( "Nuevo Objeto: " + elementClass.getSimpleName() + " del arreglo en la pos: " + pos); BeanManager objectManager = new BeanManager(elementClass); Object result = parseObject(parser, objectManager); manager.addElement(result); pos++; break; // case START_ARRAY: // //Only possible if array of arrays in json which is unlikely // //Also if in the pojo there is a recursive collection diferent // //from arraylist then there will be some problems. // //// System.out.println("Nueva Colleccion de clase: " + //// elementClass.getSimpleName() + "dentro de otro " //// + "arreglo en la pos: " + pos); //// //// CollectionManager<T> collectionManager = new //// CollectionManager<>(new ArrayList<>(), elementClass); //// //// Collection<T> collection = parseArray(parser, collectionManager); //// manager.addElement(collection); //// pos++; // break; //if it is an array of booleans.... but no. case VALUE_FALSE: System.out.println("Agregando false al arreglo en la pos: " + pos); manager.addElement(false); pos++; break; case VALUE_NULL: System.out.println("Agregando null al arreglo en la pos: " + pos); manager.addElement(null); pos++; break; case VALUE_NUMBER: //double or int if (parser.isIntegralNumber()) { int value = parser.getInt(); System.out.println("Agregando " + value + " al arreglo en la pos: " + pos); manager.addElement(value); pos++; } else { double value = parser.getBigDecimal().doubleValue(); System.out.println("Agregando " + value + " al arreglo en la pos: " + pos); manager.addElement(value); pos++; } break; case VALUE_STRING: String value = parser.getString(); //Validate if the field is of type Date if (manager.getElementClass() == Date.class) { Calendar cal = DatatypeConverter.parseDateTime(value); Date date = cal.getTime(); System.out.println("Agregando " + date + " al arreglo en la pos: " + pos); manager.addElement(date); pos++; } else { System.out.println("Agregando " + value + " al arreglo en la pos: " + pos); manager.addElement(value); pos++; } break; case VALUE_TRUE: System.out.println("Agregando true al arreglo en la pos: " + pos); manager.addElement(true); pos++; break; } } while (evt != Event.END_ARRAY); return manager.getCollection(); }
From source file:org.eclipse.lyo.testsuite.oslcv2.cm.ChangeRequestXmlTests.java
@Test public void changeRequestHasAtMostOneCloseDate() throws XPathExpressionException { NodeList closeDates = (NodeList) OSLCUtils.getXPath() .evaluate("//oslc_cm_v2:ChangeRequest/" + "oslc_cm_v2:closeDate", doc, XPathConstants.NODESET); assertTrue(getFailureMessage(), closeDates.getLength() <= 1); //If there is a close date, verify the format. if (closeDates.getLength() > 0) { try {/*from w ww. j ava2 s .c o m*/ DatatypeConverter.parseDateTime(closeDates.item(0).getTextContent()); } catch (Exception e) { fail("Modified date not in valid XSD format"); } } }
From source file:com.boundary.sdk.event.EventCLI.java
protected Date parseDateTime(String s) throws java.text.ParseException { Date dt = null;/* w w w. j a va 2 s. co m*/ if (s != null) { Calendar c = DatatypeConverter.parseDateTime(s); c.setTimeZone(TimeZone.getTimeZone("GMT")); dt = c.getTime(); } return dt; }
From source file:com.microsoft.windowsazure.management.sql.RecoverableDatabaseOperationsImpl.java
/** * Returns information about a recoverable Azure SQL Database. * * @param serverName Required. The name of the Azure SQL Database Server on * which the database was hosted./*from w w w . ja v a 2s. co m*/ * @param databaseName Required. The name of the recoverable Azure SQL * Database to be obtained. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return Contains the response to the Get Recoverable Database request. */ @Override public RecoverableDatabaseGetResponse get(String serverName, String databaseName) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (serverName == null) { throw new NullPointerException("serverName"); } if (databaseName == null) { throw new NullPointerException("databaseName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("serverName", serverName); tracingParameters.put("databaseName", databaseName); CloudTracing.enter(invocationId, this, "getAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/sqlservers/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/recoverabledatabases/"; url = url + URLEncoder.encode(databaseName, "UTF-8"); String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2012-03-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RecoverableDatabaseGetResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RecoverableDatabaseGetResponse(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element serviceResourceElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "ServiceResource"); if (serviceResourceElement != null) { RecoverableDatabase serviceResourceInstance = new RecoverableDatabase(); result.setDatabase(serviceResourceInstance); Element entityIdElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "EntityId"); if (entityIdElement != null) { String entityIdInstance; entityIdInstance = entityIdElement.getTextContent(); serviceResourceInstance.setEntityId(entityIdInstance); } Element serverNameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "ServerName"); if (serverNameElement != null) { String serverNameInstance; serverNameInstance = serverNameElement.getTextContent(); serviceResourceInstance.setServerName(serverNameInstance); } Element editionElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Edition"); if (editionElement != null) { String editionInstance; editionInstance = editionElement.getTextContent(); serviceResourceInstance.setEdition(editionInstance); } Element lastAvailableBackupDateElement = XmlUtility.getElementByTagNameNS( serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "LastAvailableBackupDate"); if (lastAvailableBackupDateElement != null) { Calendar lastAvailableBackupDateInstance; lastAvailableBackupDateInstance = DatatypeConverter .parseDateTime(lastAvailableBackupDateElement.getTextContent()); serviceResourceInstance.setLastAvailableBackupDate(lastAvailableBackupDateInstance); } Element nameElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Name"); if (nameElement != null) { String nameInstance; nameInstance = nameElement.getTextContent(); serviceResourceInstance.setName(nameInstance); } Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "Type"); if (typeElement != null) { String typeInstance; typeInstance = typeElement.getTextContent(); serviceResourceInstance.setType(typeInstance); } Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement, "http://schemas.microsoft.com/windowsazure", "State"); if (stateElement != null) { String stateInstance; stateInstance = stateElement.getTextContent(); serviceResourceInstance.setState(stateInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:com.microsoft.azure.management.sql.DatabaseBackupOperationsImpl.java
/** * Returns a list of Azure SQL Database restore points. * * @param resourceGroupName Required. The name of the Resource Group to * which the server belongs.//from w w w . j a v a2 s . c o m * @param serverName Required. The name of the Azure SQL Database Server on * which the database is hosted. * @param databaseName Required. The name of the Azure SQL Database from * which to retrieve available restore points. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @return Represents the response to a List Azure Sql Database restore * points request. */ @Override public RestorePointListResponse listRestorePoints(String resourceGroupName, String serverName, String databaseName) throws IOException, ServiceException { // Validate if (resourceGroupName == null) { throw new NullPointerException("resourceGroupName"); } if (serverName == null) { throw new NullPointerException("serverName"); } if (databaseName == null) { throw new NullPointerException("databaseName"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("resourceGroupName", resourceGroupName); tracingParameters.put("serverName", serverName); tracingParameters.put("databaseName", databaseName); CloudTracing.enter(invocationId, this, "listRestorePointsAsync", tracingParameters); } // Construct URL String url = ""; url = url + "/subscriptions/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/resourceGroups/"; url = url + URLEncoder.encode(resourceGroupName, "UTF-8"); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + URLEncoder.encode(serverName, "UTF-8"); url = url + "/databases/"; url = url + URLEncoder.encode(databaseName, "UTF-8"); url = url + "/restorePoints"; ArrayList<String> queryParameters = new ArrayList<String>(); queryParameters.add("api-version=" + "2014-04-01"); if (queryParameters.size() > 0) { url = url + "?" + CollectionStringBuilder.join(queryParameters, "&"); } String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromJson(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result RestorePointListResponse result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new RestorePointListResponse(); ObjectMapper objectMapper = new ObjectMapper(); JsonNode responseDoc = null; String responseDocContent = IOUtils.toString(responseContent); if (responseDocContent == null == false && responseDocContent.length() > 0) { responseDoc = objectMapper.readTree(responseDocContent); } if (responseDoc != null && responseDoc instanceof NullNode == false) { JsonNode valueArray = responseDoc.get("value"); if (valueArray != null && valueArray instanceof NullNode == false) { for (JsonNode valueValue : ((ArrayNode) valueArray)) { RestorePoint restorePointInstance = new RestorePoint(); result.getRestorePoints().add(restorePointInstance); JsonNode propertiesValue = valueValue.get("properties"); if (propertiesValue != null && propertiesValue instanceof NullNode == false) { RestorePointProperties propertiesInstance = new RestorePointProperties(); restorePointInstance.setProperties(propertiesInstance); JsonNode restorePointTypeValue = propertiesValue.get("restorePointType"); if (restorePointTypeValue != null && restorePointTypeValue instanceof NullNode == false) { String restorePointTypeInstance; restorePointTypeInstance = restorePointTypeValue.getTextValue(); propertiesInstance.setRestorePointType(restorePointTypeInstance); } JsonNode restorePointCreationDateValue = propertiesValue .get("restorePointCreationDate"); if (restorePointCreationDateValue != null && restorePointCreationDateValue instanceof NullNode == false) { Calendar restorePointCreationDateInstance; restorePointCreationDateInstance = DatatypeConverter .parseDateTime(restorePointCreationDateValue.getTextValue()); propertiesInstance .setRestorePointCreationDate(restorePointCreationDateInstance); } JsonNode earliestRestoreDateValue = propertiesValue.get("earliestRestoreDate"); if (earliestRestoreDateValue != null && earliestRestoreDateValue instanceof NullNode == false) { Calendar earliestRestoreDateInstance; earliestRestoreDateInstance = DatatypeConverter .parseDateTime(earliestRestoreDateValue.getTextValue()); propertiesInstance.setEarliestRestoreDate(earliestRestoreDateInstance); } } JsonNode idValue = valueValue.get("id"); if (idValue != null && idValue instanceof NullNode == false) { String idInstance; idInstance = idValue.getTextValue(); restorePointInstance.setId(idInstance); } JsonNode nameValue = valueValue.get("name"); if (nameValue != null && nameValue instanceof NullNode == false) { String nameInstance; nameInstance = nameValue.getTextValue(); restorePointInstance.setName(nameInstance); } JsonNode typeValue = valueValue.get("type"); if (typeValue != null && typeValue instanceof NullNode == false) { String typeInstance; typeInstance = typeValue.getTextValue(); restorePointInstance.setType(typeInstance); } JsonNode locationValue = valueValue.get("location"); if (locationValue != null && locationValue instanceof NullNode == false) { String locationInstance; locationInstance = locationValue.getTextValue(); restorePointInstance.setLocation(locationInstance); } JsonNode tagsSequenceElement = ((JsonNode) valueValue.get("tags")); if (tagsSequenceElement != null && tagsSequenceElement instanceof NullNode == false) { Iterator<Map.Entry<String, JsonNode>> itr = tagsSequenceElement.getFields(); while (itr.hasNext()) { Map.Entry<String, JsonNode> property = itr.next(); String tagsKey = property.getKey(); String tagsValue = property.getValue().getTextValue(); restorePointInstance.getTags().put(tagsKey, tagsValue); } } } } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
From source file:eu.riscoss.rdc.RDCGithub.java
/** * For paginated requests/*from ww w. ja v a2 s . co m*/ * @param request * @param maxPages max pages in paginated requests * @param created_at_years maximum timespan for the "created at" field (used e.g. for issues). 0: no timespan * @return */ private JSONAware parsePaged(String request, int maxPages, int created_at_years) { JSONArray jaComplete = new JSONArray(); char divider = '?'; if (request.contains("?")) divider = '&'; Calendar lastyear = Calendar.getInstance();//actual lastyear.set(Calendar.YEAR, lastyear.get(Calendar.YEAR) - created_at_years); try { for (int i = 1; i <= maxPages; i++) { String jsonPage = getData(repository + request + divider + "page=" + i, ""); if (jsonPage.startsWith("WARNING")) { System.err.println(jsonPage); //error message - implement different handling if needed } else try { JSONAware jv = (JSONAware) new JSONParser().parse(jsonPage); if (jv instanceof JSONArray) { JSONArray ja = (JSONArray) jv; if (ja.size() == 0) break; jaComplete.addAll(ja); //do not scan more years if (created_at_years > 0) { Calendar openedDate; String openedAt = (String) ((JSONObject) ja.get(ja.size() - 1)).get("created_at"); if (openedAt != null) { openedDate = DatatypeConverter.parseDateTime(openedAt); //System.out.println("scan: opening date: "+openedDate.get(Calendar.YEAR)+" "+openedDate.get(Calendar.MONTH)); //System.out.println("scan: last date: "+lastyear.get(Calendar.YEAR)+" "+lastyear.get(Calendar.MONTH)); if (openedDate.compareTo(lastyear) < 0) { System.out.println("BREAK"); break; } } } } } catch (ParseException e) { e.printStackTrace();//TODO } } } catch (org.apache.http.ParseException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return jaComplete; }