List of usage examples for java.util GregorianCalendar setTimeInMillis
public void setTimeInMillis(long millis)
From source file:de.ribeiro.android.gso.core.UntisProvider.java
/** * Synchronisiert alle verfgbaren WeekDatas im Stupid * * @param logger/* w ww .ja v a 2s. co m*/ * @param selectedStringDate * @param selectedElement * @param myType * @param htmlResponse * @param stupid * @return * @throws Exception */ public static List<ICalEvent> syncWeekData(GregorianCalendar gc, String selectedElement, Type myType, HtmlResponse htmlResponse, Stupid stupid) throws Exception { List<ICalEvent> result = new ArrayList<ICalEvent>(); int currentDayOfWeek = gc.get(Calendar.DAY_OF_WEEK); // den currentDay auf den folge Montag setzen if (currentDayOfWeek < 2) { // 1000*60*60*24 = 1 Tag! gc.setTimeInMillis(gc.getTimeInMillis() + (1000 * 60 * 60 * 24 * (2 - currentDayOfWeek))); } if (currentDayOfWeek > 6) { // 1000*60*60*24 = 1 Tag! gc.setTimeInMillis(gc.getTimeInMillis() + (1000 * 60 * 60 * 24 * 2)); } String date = ConvertToStupidDateString(gc); String selectedType = myType.type; String selectedClassIndex = getIndexOfSelectorValue(myType.elementList, selectedElement); if (selectedClassIndex == "-1" || selectedType.equalsIgnoreCase("")) { throw new Exception(selectedElement + " kann nicht synchronisiert werden! " + selectedElement + " wurde nicht in der Liste der verfgbaren Elemente gefunden!"); } while (selectedClassIndex.length() < 3) { selectedClassIndex = "0" + selectedClassIndex; } WeekData weekData = new WeekData(stupid); try { // URL setzten URL url = new URL( "https://webuntis.stadt-koeln.de/WebUntis/Ical.do?school=K175055&ajaxCommand=renderTimetable&rpt_sd=" + date + "&type=" + 1 + "&elemId=" + selectedClassIndex + "&elemType=" + selectedType); htmlResponse.dataReceived = false; htmlResponse.xmlContent = XmlOPs.readFromURL(url, Const.CONNECTIONTIMEOUT); if (htmlResponse.xmlContent.length() < 50) { // ende return null; } _logger.Info("Week downloaded!"); List<ICalEvent> events = Ical.Parse(htmlResponse.xmlContent); weekData.syncTime = new GregorianCalendar().getTimeInMillis(); weekData.addParameter("syncTime", String.valueOf(weekData.syncTime)); weekData.date = (Calendar) gc.clone(); weekData.elementId = selectedElement; weekData.addParameter("classId", selectedElement); weekData.events = events; weekData.weekId = String.valueOf(gc.get(Calendar.WEEK_OF_YEAR)); weekData.addParameter("weekId", weekData.weekId); weekData.typeId = myType.type; weekData.addParameter("typeId", weekData.typeId); weekData.weekDataVersion = "2"; weekData.addParameter("weekDataVersion", weekData.weekDataVersion); // stupid.stupidData.add(wd); } catch (Exception e) { throw e; } // prfen, ob bereits die Woche fr die Klasse und den typ vorliegt: WeekData existWeekData = null; // alle bestehden Wochen abrufen: for (int y = 0; y < stupid.stupidData.size(); y++) { existWeekData = stupid.stupidData.get(y); // prfen, ob das bestehende Element, dem neu hinzuzufgenden // entspricht(klasse,KW,Typ) if (existWeekData.elementId.equalsIgnoreCase(weekData.elementId) && existWeekData.weekId.equalsIgnoreCase(weekData.weekId) && existWeekData.typeId.equalsIgnoreCase(weekData.typeId)) { // ja,es ist eine gleiche Woche bereits vorhanden // jedes event der neuen woche prfen, ob dieses schon existiert for (int ev = 0; ev < weekData.events.size(); ev++) { ICalEvent newevent = weekData.events.get(ev); // die schulstunde vom neuen event heraussuchen int schulstunde = GetSchulstundeOfEvent(newevent); // damit die schulstunde vom bestenden stundeplan abrufen ICalEvent existingevent = GetSchulstunde(existWeekData, newevent.DTSTART.get(Calendar.DAY_OF_WEEK), schulstunde); if (existingevent != null) newevent.UID = existingevent.UID; // beide schulstunden vergleichen if (compareEvents(existingevent, newevent)) { // unterschiede gefunden newevent.UID = "diff"; if (existingevent == null) _logger.Info("Es wurden Unterschiede in den Events gefunden: Neues Event " + newevent.DESCRIPTION + " , " + newevent.SUMMARY + " , kein altes Event vorhanden!"); else { _logger.Info("Es wurden Unterschiede in den Events gefunden: Neues Event " + newevent.DESCRIPTION + " , " + newevent.SUMMARY + " , Altes Event " + existingevent.DESCRIPTION + " , " + existingevent.SUMMARY); } // ber unterschiede benachrichtigen result.add(newevent); } // das existierende event aus dem datensatz lschen existWeekData.events.remove(existingevent); } for (ICalEvent event : existWeekData.events) { event.UID = "deleted"; weekData.events.add(event); } // alle verbleibenden events aus dem existierenden datensatz // sind ausgefallene stunden // existiert schon...ersetzen weekData.isDirty = true; stupid.stupidData.set(y, weekData); return SummarizeChanges(result); } } stupid.stupidData.add(weekData); // fgt die geparste Woche den // // Hauptdaten // // hinzu stupid.sort(); return SummarizeChanges(result); }
From source file:com.projity.interval.ValueObjectForIntervalTable.java
/** * Create a new entry one year later/*from ww w . ja v a 2 s.co m*/ */ public Object createUnvalidatedObject(NodeModel nodeModel, Object parent) { long baseDate = DateTime.midnightToday(); ValueObjectForInterval last = (ValueObjectForInterval) valueObjects.get(valueObjects.size() - 1); // get last one baseDate = Math.max(baseDate, last.getStart()); // latest of today or last entry GregorianCalendar cal = DateTime.calendarInstance(); cal.setTimeInMillis(baseDate); cal.roll(GregorianCalendar.YEAR, true); // one year later than last one's start or today long date = cal.getTimeInMillis(); try { return newValueObject(date); } catch (InvalidValueObjectForIntervalException e) { // TODO Auto-generated catch block e.printStackTrace(); // should not ever happen return null; } }
From source file:org.opencms.notification.CmsNotificationCandidates.java
/** * Collects all resources that will expire in short time, or will become valid, or are not modified since a long time.<p> * //from ww w .j a va2 s . c om * @param cms the CmsObject * * @throws CmsException if something goes wrong */ public CmsNotificationCandidates(CmsObject cms) throws CmsException { m_resources = new ArrayList(); m_cms = cms; m_cms.getRequestContext() .setCurrentProject(m_cms.readProject(OpenCms.getSystemInfo().getNotificationProject())); String folder = "/"; GregorianCalendar now = new GregorianCalendar(TimeZone.getDefault(), CmsLocaleManager.getDefaultLocale()); now.setTimeInMillis(System.currentTimeMillis()); GregorianCalendar inOneWeek = (GregorianCalendar) now.clone(); inOneWeek.add(Calendar.WEEK_OF_YEAR, 1); Iterator resources; CmsResource resource; // read all files with the 'notification-interval' property set try { resources = m_cms .readResourcesWithProperty(folder, CmsPropertyDefinition.PROPERTY_NOTIFICATION_INTERVAL) .iterator(); while (resources.hasNext()) { resource = (CmsResource) resources.next(); int notification_interval = Integer.parseInt(m_cms .readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_NOTIFICATION_INTERVAL, true) .getValue()); GregorianCalendar intervalBefore = new GregorianCalendar(TimeZone.getDefault(), CmsLocaleManager.getDefaultLocale()); intervalBefore.setTimeInMillis(resource.getDateLastModified()); intervalBefore.add(Calendar.DAY_OF_YEAR, notification_interval); GregorianCalendar intervalAfter = (GregorianCalendar) intervalBefore.clone(); intervalAfter.add(Calendar.WEEK_OF_YEAR, -1); for (int i = 0; (i < 100) && intervalAfter.getTime().before(now.getTime()); i++) { if (intervalBefore.getTime().after(now.getTime())) { m_resources.add(new CmsExtendedNotificationCause(resource, CmsExtendedNotificationCause.RESOURCE_UPDATE_REQUIRED, intervalBefore.getTime())); } intervalBefore.add(Calendar.DAY_OF_YEAR, notification_interval); intervalAfter.add(Calendar.DAY_OF_YEAR, notification_interval); } } } catch (CmsDbEntryNotFoundException e) { // no resources with property 'notification-interval', ignore } // read all files that were not modified longer than the max notification-time GregorianCalendar oneYearAgo = (GregorianCalendar) now.clone(); oneYearAgo.add(Calendar.DAY_OF_YEAR, -OpenCms.getSystemInfo().getNotificationTime()); // create a resource filter to get the resources with CmsResourceFilter filter = CmsResourceFilter.IGNORE_EXPIRATION .addRequireLastModifiedBefore(oneYearAgo.getTimeInMillis()); resources = m_cms.readResources(folder, filter).iterator(); while (resources.hasNext()) { resource = (CmsResource) resources.next(); m_resources.add(new CmsExtendedNotificationCause(resource, CmsExtendedNotificationCause.RESOURCE_OUTDATED, new Date(resource.getDateLastModified()))); } // get all resources that will expire within the next week CmsResourceFilter resourceFilter = CmsResourceFilter.IGNORE_EXPIRATION .addRequireExpireBefore(inOneWeek.getTimeInMillis()); resourceFilter = resourceFilter.addRequireExpireAfter(now.getTimeInMillis()); resources = m_cms.readResources(folder, resourceFilter).iterator(); while (resources.hasNext()) { resource = (CmsResource) resources.next(); m_resources.add(new CmsExtendedNotificationCause(resource, CmsExtendedNotificationCause.RESOURCE_EXPIRES, new Date(resource.getDateExpired()))); } // get all resources that will release within the next week resourceFilter = CmsResourceFilter.IGNORE_EXPIRATION.addRequireReleaseBefore(inOneWeek.getTimeInMillis()); resourceFilter = resourceFilter.addRequireReleaseAfter(now.getTimeInMillis()); resources = m_cms.readResources(folder, resourceFilter).iterator(); while (resources.hasNext()) { resource = (CmsResource) resources.next(); m_resources.add(new CmsExtendedNotificationCause(resource, CmsExtendedNotificationCause.RESOURCE_RELEASE, new Date(resource.getDateReleased()))); } }
From source file:net.acesinc.nifi.processors.json.BetterAttributesToJSON.java
/** * Builds the Map of attributes that should be included in the JSON that is * emitted from this process./*from w w w. j av a2 s . com*/ * * @param ff * @param atrListForStringValues * @param atrListForIntValues * @param atrListForDoubleValues * @param atrListForLongEpochToGoToDateValues * @return Map of values that are feed to a Jackson ObjectMapper * @throws java.io.IOException */ protected Map<String, Object> buildAttributesMapAndBringInFlowAttrs(FlowFile ff, String atrListForStringValues, String atrListForIntValues, String atrListForDoubleValues, String atrListForLongEpochToGoToDateValues) throws IOException { Map<String, Object> atsToWrite = new HashMap<>(); //handle all the string values //If list of attributes specified get only those attributes. Otherwise write them all if (StringUtils.isNotBlank(atrListForStringValues)) { String[] ats = StringUtils.split(atrListForStringValues, AT_LIST_SEPARATOR); if (ats != null) { for (String str : ats) { String cleanStr = str.trim(); String val = ff.getAttribute(cleanStr); if (val != null) { atsToWrite.put(cleanStr, val); } else { atsToWrite.put(cleanStr, ""); } } } } else { atsToWrite.putAll(ff.getAttributes()); } //handle all int values if (StringUtils.isNotBlank(atrListForIntValues)) { String[] ats = StringUtils.split(atrListForIntValues, AT_LIST_SEPARATOR); if (ats != null) { for (String str : ats) { String cleanStr = str.trim(); String val = ff.getAttribute(cleanStr); if (val != null) { atsToWrite.put(cleanStr, Integer.parseInt(val)); } else { atsToWrite.put(cleanStr, null); } } } } //handle all double values if (StringUtils.isNotBlank(atrListForDoubleValues)) { String[] ats = StringUtils.split(atrListForDoubleValues, AT_LIST_SEPARATOR); if (ats != null) { for (String str : ats) { String cleanStr = str.trim(); String val = ff.getAttribute(cleanStr); if (val != null) { atsToWrite.put(cleanStr, Double.parseDouble(val)); } else { atsToWrite.put(cleanStr, null); } } } } //handle all date values if (StringUtils.isNotBlank(atrListForLongEpochToGoToDateValues)) { String[] ats = StringUtils.split(atrListForLongEpochToGoToDateValues, AT_LIST_SEPARATOR); if (ats != null) { for (String str : ats) { String cleanStr = str.trim(); String val = ff.getAttribute(cleanStr); if (val != null) { long epochTime = Long.parseLong(val); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeZone(TimeZone.getTimeZone(MONGO_TIME_ZONE)); gcal.setTimeInMillis(epochTime); SimpleDateFormat sdf = new SimpleDateFormat(MONGO_DATE_TEMPLATE); String mongoDate = sdf.format(gcal.getTime()); //to Date Map<String, String> isoDate = new HashMap<>(); isoDate.put("$date", mongoDate); atsToWrite.put(cleanStr, isoDate); } else { atsToWrite.put(cleanStr, null); } } } } return atsToWrite; }
From source file:gov.nih.nci.integration.caaers.CaAERSParticipantServiceClientIntegrationTest.java
/** * Testcase for marshlling participant type * //from w ww. j a v a 2 s .com * @throws JAXBException - JAXBException * @throws DatatypeConfigurationException - DatatypeConfigurationException */ @Test public void marshalParticipantType() throws JAXBException, DatatypeConfigurationException { final ParticipantType pt = new ParticipantType(); pt.setFirstName("fn"); pt.setLastName("ln"); pt.setEthnicity(EthnicityType.NOT_HISPANIC_OR_LATINO); pt.setGender(GenderType.MALE); final DatatypeFactory df = DatatypeFactory.newInstance(); final GregorianCalendar gc = new GregorianCalendar(); gc.setTimeInMillis(new Date().getTime()); pt.setBirthDate(df.newXMLGregorianCalendar(gc)); pt.setRace(RaceType.WHITE); final OrganizationAssignedIdentifierType orgId = new OrganizationAssignedIdentifierType(); orgId.setType(ParticipantIdentifierType.MRN); orgId.setValue("123456"); orgId.setPrimaryIndicator(true); final OrganizationType ot = new OrganizationType(); ot.setName("UCSF)"); ot.setNciInstituteCode("UCSF"); orgId.setOrganization(ot); final ParticipantType.Identifiers ids = new ParticipantType.Identifiers(); ids.getOrganizationAssignedIdentifier().add(orgId); pt.setIdentifiers(ids); final AssignmentType at = new AssignmentType(); at.setStudySubjectIdentifier("456"); final StudySiteType sst = new StudySiteType(); final OrganizationType ot2 = new OrganizationType(); ot2.setName("UCSF)"); ot2.setNciInstituteCode("UCSF"); sst.setOrganization(ot2); final StudyType st = new StudyType(); final ReducedIdentifierType rit = new ReducedIdentifierType(); rit.setType(StudyIdentifierType.SITE_IDENTIFIER); rit.setValue("1.2.3.4.5"); final StudyType.Identifiers sids = new StudyType.Identifiers(); sids.setIdentifier(rit); st.setIdentifiers(sids); sst.setStudy(st); at.setStudySite(sst); final Assignments ass = new Assignments(); ass.getAssignment().add(at); pt.setAssignments(ass); final QName qname = new QName("http://webservice.caaers.cabig.nci.nih.gov/participant", "participant"); final JAXBElement<ParticipantType> ptJaxbEle = new JAXBElement<ParticipantType>(qname, ParticipantType.class, pt); final StringWriter sw = new StringWriter(); getMarshaller().marshal(ptJaxbEle, sw); Assert.assertNotNull(sw.toString()); JAXBElement<ParticipantType> jaxbEle = (JAXBElement<ParticipantType>) getUnMarshaller() .unmarshal(new StreamSource(new StringReader(sw.toString())), ParticipantType.class); Assert.assertNotNull(jaxbEle); Assert.assertNotNull(jaxbEle.getValue()); jaxbEle = (JAXBElement<ParticipantType>) getUnMarshaller() .unmarshal(new StreamSource(new StringReader(getPStr())), ParticipantType.class); Assert.assertNotNull(jaxbEle); final ParticipantType ptn = jaxbEle.getValue(); Assert.assertNotNull(ptn); }
From source file:org.enotron.EnergySimulatorEndpoint.java
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "getDataRequest") @ResponsePayload//w w w. jav a 2 s .com public GetDataResponse getData(@RequestPayload GetDataRequest getDataPayload) throws GetDataFault { if (getDataPayload.getValuesMode() == null) { GetDataFault df = new GetDataFault(); df.setFaultText("Invalid value for 'ValuesMode' use one of enumerated values"); throw df; } GetDataResponse resp = new GetDataResponse(); Date startTime = null, endTime = null; if (getDataPayload.getStartTime() != null) { startTime = new Date(getDataPayload.getStartTime().getMillisecond()); } if (getDataPayload.getEndTime() != null) { endTime = new Date(getDataPayload.getEndTime().getMillisecond()); } try { for (MeasurementImpl measurement : simdata.getMeaurementList(getDataPayload.getSimulatorid(), getDataPayload.getParameterList().toArray(new String[getDataPayload.getParameterList().size()]), org.enotron.simulator.api.ValuesMode.valueOf(getDataPayload.getValuesMode().name()), startTime, endTime, GroupByTime.valueOf(getDataPayload.getGroupBy().name()))) { Measurement measSoap = new Measurement(); measSoap.setDurationSecs(measurement.getDurationSecs()); measSoap.setName(measurement.getName()); GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(measurement.getTimestamp().getTime()); measSoap.setTimestamp(factory.newXMLGregorianCalendar(cal)); measSoap.setUnit(measurement.getUnit()); measSoap.setValueCode(ValuesMode.valueOf(measurement.getValueCode().name())); for (Float measValue : measurement.getValues()) { measSoap.getValues().add(measValue); } resp.getMeasurement().add(measSoap); } return resp; } catch (SimulatorException e) { e.printStackTrace(); GetDataFault gdf = new GetDataFault(); gdf.setFaultText(e.getMessage()); throw gdf; } catch (Exception e) { e.printStackTrace(); GetDataFault gdf = new GetDataFault(); gdf.setFaultText("Exception from getData " + e.getMessage()); throw gdf; } }
From source file:org.sufficientlysecure.keychain.keyimport.HkpKeyServer.java
@Override public ArrayList<ImportKeysListEntry> search(String query) throws QueryException, TooManyResponses, InsufficientQuery { ArrayList<ImportKeysListEntry> results = new ArrayList<ImportKeysListEntry>(); if (query.length() < 3) { throw new InsufficientQuery(); }/* w w w . j a va2 s . c om*/ String encodedQuery; try { encodedQuery = URLEncoder.encode(query, "utf8"); } catch (UnsupportedEncodingException e) { return null; } String request = "/pks/lookup?op=index&options=mr&search=" + encodedQuery; String data; try { data = query(request); } catch (HttpError e) { if (e.getCode() == 404) { return results; } else { if (e.getData().toLowerCase(Locale.US).contains("no keys found")) { return results; } else if (e.getData().toLowerCase(Locale.US).contains("too many")) { throw new TooManyResponses(); } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) { throw new InsufficientQuery(); } } throw new QueryException("querying server(s) for '" + mHost + "' failed"); } final Matcher matcher = PUB_KEY_LINE.matcher(data); while (matcher.find()) { final ImportKeysListEntry entry = new ImportKeysListEntry(); entry.setBitStrength(Integer.parseInt(matcher.group(3))); final int algorithmId = Integer.decode(matcher.group(2)); entry.setAlgorithm(PgpKeyHelper.getAlgorithmInfo(algorithmId)); // group 1 contains the full fingerprint (v4) or the long key id if available // see http://bit.ly/1d4bxbk and http://bit.ly/1gD1wwr String fingerprintOrKeyId = matcher.group(1); if (fingerprintOrKeyId.length() > 16) { entry.setFingerprintHex(fingerprintOrKeyId.toLowerCase(Locale.US)); entry.setKeyIdHex("0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() - 16, fingerprintOrKeyId.length())); } else { // set key id only entry.setKeyIdHex("0x" + fingerprintOrKeyId); } final long creationDate = Long.parseLong(matcher.group(4)); final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC")); tmpGreg.setTimeInMillis(creationDate * 1000); entry.setDate(tmpGreg.getTime()); entry.setRevoked(matcher.group(6).contains("r")); ArrayList<String> userIds = new ArrayList<String>(); final String uidLines = matcher.group(7); final Matcher uidMatcher = UID_LINE.matcher(uidLines); while (uidMatcher.find()) { String tmp = uidMatcher.group(1).trim(); if (tmp.contains("%")) { try { // converts Strings like "Universit%C3%A4t" to a proper encoding form "Universitt". tmp = (URLDecoder.decode(tmp, "UTF8")); } catch (UnsupportedEncodingException ignored) { // will never happen, because "UTF8" is supported } } userIds.add(tmp); } entry.setUserIds(userIds); entry.setPrimaryUserId(userIds.get(0)); results.add(entry); } return results; }
From source file:com.cloudbees.hudson.plugins.folder.computed.FolderComputation.java
@WithBridgeMethods(TaskListener.class) @Nonnull/* w w w . j ava 2 s . c o m*/ public synchronized StreamTaskListener createEventsListener() { File eventsFile = getEventsFile(); if (!eventsFile.getParentFile().isDirectory() && !eventsFile.getParentFile().mkdirs()) { LOGGER.log(Level.WARNING, "Could not create directory {0} for {1}", new Object[] { eventsFile.getParentFile(), folder.getFullName() }); // TODO return a StreamTaskListener sending output to a log, for now this will just try and fail to write } if (eventStreams == null) { eventStreams = new EventOutputStreams(new EventOutputStreams.OutputFile() { @NonNull @Override public File get() { return getEventsFile(); } @Override public boolean canWriteNow() { // TODO rework once JENKINS-42248 is solved GregorianCalendar timestamp = new GregorianCalendar(); timestamp.setTimeInMillis(System.currentTimeMillis() - 10000L); Queue.Item probe = new Queue.WaitingItem(timestamp, folder, Collections.<Action>emptyList()); for (QueueTaskDispatcher d : QueueTaskDispatcher.all()) { if (d.canRun(probe) != null) { return false; } } return true; } }, 250, TimeUnit.MILLISECONDS, 1024, true, EVENT_LOG_MAX_SIZE * 1024, BACKUP_LOG_COUNT == null ? 0 : Math.max(0, BACKUP_LOG_COUNT)); } return new StreamTaskListener(eventStreams.get(), Charsets.UTF_8); }
From source file:org.thialfihar.android.apg.keyimport.HkpKeyserver.java
@Override public ArrayList<ImportKeysListEntry> search(String query) throws QueryFailedException, QueryNeedsRepairException { ArrayList<ImportKeysListEntry> results = new ArrayList<ImportKeysListEntry>(); if (query.length() < 3) { throw new QueryTooShortException(); }//from www . java 2s .co m String encodedQuery; try { encodedQuery = URLEncoder.encode(query, "utf8"); } catch (UnsupportedEncodingException e) { return null; } String request = "/pks/lookup?op=index&options=mr&search=" + encodedQuery; String data; try { data = query(request); } catch (HttpError e) { if (e.getCode() == 404) { return results; } else { if (e.getData().toLowerCase(Locale.US).contains("no keys found")) { return results; } else if (e.getData().toLowerCase(Locale.US).contains("too many")) { throw new TooManyResponsesException(); } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) { throw new QueryTooShortException(); } } throw new QueryFailedException("querying server(s) for '" + mHost + "' failed"); } final Matcher matcher = PUB_KEY_LINE.matcher(data); while (matcher.find()) { final ImportKeysListEntry entry = new ImportKeysListEntry(); entry.setQuery(query); entry.setBitStrength(Integer.parseInt(matcher.group(3))); final int algorithmId = Integer.decode(matcher.group(2)); entry.setAlgorithm(PgpKeyHelper.getAlgorithmInfo(algorithmId)); // group 1 contains the full fingerprint (v4) or the long key id if available // see http://bit.ly/1d4bxbk and http://bit.ly/1gD1wwr String fingerprintOrKeyId = matcher.group(1); if (fingerprintOrKeyId.length() > 16) { entry.setFingerprintHex(fingerprintOrKeyId.toLowerCase(Locale.US)); entry.setKeyIdHex("0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() - 16, fingerprintOrKeyId.length())); } else { // set key id only entry.setKeyIdHex("0x" + fingerprintOrKeyId); } final long creationDate = Long.parseLong(matcher.group(4)); final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC")); tmpGreg.setTimeInMillis(creationDate * 1000); entry.setDate(tmpGreg.getTime()); entry.setRevoked(matcher.group(6).contains("r")); ArrayList<String> userIds = new ArrayList<String>(); final String uidLines = matcher.group(7); final Matcher uidMatcher = UID_LINE.matcher(uidLines); while (uidMatcher.find()) { String tmp = uidMatcher.group(1).trim(); if (tmp.contains("%")) { try { // converts Strings like "Universit%C3%A4t" to a proper encoding form "Universitt". tmp = (URLDecoder.decode(tmp, "UTF8")); } catch (UnsupportedEncodingException ignored) { // will never happen, because "UTF8" is supported } } userIds.add(tmp); } entry.setUserIds(userIds); entry.setPrimaryUserId(userIds.get(0)); results.add(entry); } return results; }
From source file:org.thialfihar.android.apg.pgp.HkpKeyServer.java
@Override public ArrayList<ImportKeysListEntry> search(String query) throws QueryException, TooManyResponses, InsufficientQuery { ArrayList<ImportKeysListEntry> results = new ArrayList<ImportKeysListEntry>(); if (query.length() < 3) { throw new InsufficientQuery(); }/*from w w w . j a v a2s .c om*/ String encodedQuery; try { encodedQuery = URLEncoder.encode(query, "utf8"); } catch (UnsupportedEncodingException e) { return null; } String request = "/pks/lookup?op=index&options=mr&search=" + encodedQuery; String data; try { data = query(request); } catch (HttpError e) { if (e.getCode() == 404) { return results; } else { if (e.getData().toLowerCase(Locale.US).contains("no keys found")) { return results; } else if (e.getData().toLowerCase(Locale.US).contains("too many")) { throw new TooManyResponses(); } else if (e.getData().toLowerCase(Locale.US).contains("insufficient")) { throw new InsufficientQuery(); } } throw new QueryException("querying server(s) for '" + mHost + "' failed"); } final Matcher matcher = PUB_KEY_LINE.matcher(data); while (matcher.find()) { final ImportKeysListEntry entry = new ImportKeysListEntry(); entry.setBitStrength(Integer.parseInt(matcher.group(3))); final int algorithmId = Integer.decode(matcher.group(2)); entry.setAlgorithm(ImportKeysListEntry.getAlgorithmFromId(algorithmId)); // group 1 contains the full fingerprint (v4) or the long key id if available // see http://bit.ly/1d4bxbk and http://bit.ly/1gD1wwr String fingerprintOrKeyId = matcher.group(1); if (fingerprintOrKeyId.length() > 16) { entry.setFingerPrintHex(fingerprintOrKeyId.toLowerCase(Locale.US)); entry.setKeyIdHex("0x" + fingerprintOrKeyId.substring(fingerprintOrKeyId.length() - 16, fingerprintOrKeyId.length())); } else { // set key id only entry.setKeyIdHex("0x" + fingerprintOrKeyId); } final long creationDate = Long.parseLong(matcher.group(4)); final GregorianCalendar tmpGreg = new GregorianCalendar(TimeZone.getTimeZone("UTC")); tmpGreg.setTimeInMillis(creationDate * 1000); entry.setDate(tmpGreg.getTime()); entry.setRevoked(matcher.group(6).contains("r")); ArrayList<String> userIds = new ArrayList<String>(); final String uidLines = matcher.group(7); final Matcher uidMatcher = UID_LINE.matcher(uidLines); while (uidMatcher.find()) { String tmp = uidMatcher.group(1).trim(); if (tmp.contains("%")) { try { // converts Strings like "Universit%C3%A4t" to a proper encoding form "Universitt". tmp = (URLDecoder.decode(tmp, "UTF8")); } catch (UnsupportedEncodingException ignored) { // will never happen, because "UTF8" is supported } } userIds.add(tmp); } entry.setUserIds(userIds); results.add(entry); } return results; }