List of usage examples for java.lang String hashCode
public int hashCode()
From source file:com.yahoo.elide.core.PersistentResource.java
@Override public int hashCode() { final int prime = 31; int result = 1; String id = dictionary.getId(getObject()); result = prime * result + (uuid.isPresent() ? uuid.hashCode() : 0); result = prime * result + (id == null ? 0 : id.hashCode()); result = prime * result + (type == null ? 0 : type.hashCode()); return result; }
From source file:com.ikanow.infinit.e.harvest.extraction.document.file.FileHarvester.java
private void traverse(InfiniteFile f, SourcePojo source, int depth) throws Exception { if (depth == 0) { return;/*from www . j a v a 2 s . co m*/ } try { InfiniteFile[] l; if (_customJob) { l = f.listFiles(_customLastRecordWritten, this.maxDocsPerCycle); } else { if (_bNeedsExtraSyncLock) { synchronized (FileHarvester.class) { l = f.listFiles(); } } else { // normal case, no synchronization needed l = f.listFiles(); } } for (int i = 0; l != null && i < l.length; i++) { if (null == l[i]) break; // (reached the end of the list) // Check what the deal with memory usage is: // (Allow 25% of current heap) if ((_totalMemUsage.get() * 4) > Runtime.getRuntime().maxMemory()) { source.setReachedMaxDocs(); break; } //TESTED // Check to see if the item is a directory or a file that needs to parsed // if it is a file then parse the sucker using tika // if it is a directory then use recursion to dive into the directory if (files.size() >= this.maxDocsPerCycle) { source.setReachedMaxDocs(); break; } if (l[i].isDirectory()) { // Directories: included unless explicity exclude: String path = l[i].getUrlPath(); boolean bProcess = true; if (_customJob && !_unshardedCustomJob && (depth == Integer.MAX_VALUE)) { // custom jobs split by directory aka shard, and only at the top... if ((null != source.getDistributionTokens()) && (null != source.getDistributionFactor())) { int split = Math.abs(path.hashCode()) % source.getDistributionFactor(); if (!source.getDistributionTokens().contains(split)) { bProcess = false; } } //TESTED (custom) } if (bProcess && (null != excludeRegex)) { if (excludeRegex.matcher(path).matches()) { bProcess = false; } } //TESTED if (bProcess) { traverse(l[i], source, depth - 1); if (source.reachedMaxDocs()) { // (express elevator back to recursion root) return; } } } else { if (_customJob && (depth == Integer.MAX_VALUE)) { // file at level 1 => custom job is unsharded _unshardedCustomJob = true; } boolean bProcess = true; // Files: check both include and exclude and distribution logic String path = l[i].getUrlPath(); // Intra-source distribution logic: if (!_customJob || _unshardedCustomJob) { // custom jobs split by directory aka shard if ((null != source.getDistributionTokens()) && (null != source.getDistributionFactor())) { int split = Math.abs(path.hashCode()) % source.getDistributionFactor(); if (!source.getDistributionTokens().contains(split)) { bProcess = false; } } //TESTED (custom and non-custom) } if (bProcess && (null != includeRegex)) { if (!includeRegex.matcher(path).matches()) { bProcess = false; } } if (bProcess && (null != excludeRegex)) { if (excludeRegex.matcher(path).matches()) { bProcess = false; } } //TESTED if (bProcess) { parse(l[i], source); // (Adds to this.files) // If we've got here, check what we should do with the file if (!_context.isStandalone()) { if ((null != source.getFileConfig()) && (null != source.getFileConfig().renameAfterParse)) { try { if (source.getFileConfig().renameAfterParse.isEmpty() || source.getFileConfig().renameAfterParse.equals(".")) { // delete it l[i].delete(); } //TESTED else { l[i].rename(createNewName(l[i], source.getFileConfig().renameAfterParse)); } //TESTED } catch (IOException e) { // doesn't seem worth bombing out but should error _context.getHarvestStatus().logMessage( HarvestExceptionUtils.createExceptionMessage(e).toString(), true); } } //TESTED } } //(not excluded) } //(file not directory) l[i] = null; // (ie should now be able to free the memory } //(end loop over directory files) } catch (Exception e) { if (maxDepth == depth) { // Top level error, abandon ship errors++; throw e; } else { // Already had some luck with this URL keep going errors++; _context.getHarvestStatus().logMessage(HarvestExceptionUtils.createExceptionMessage(e).toString(), true); } } }
From source file:org.callimachusproject.auth.CookieAuthenticationManager.java
public CookieAuthenticationManager(String identifier, String redirect_uri, String fullname_prefix, String path, List<String> domains, RealmManager realms, ParameterAuthReader reader) throws OpenRDFException, IOException { assert domains != null; assert domains.size() > 0; this.domains = domains; Set<Integer> ports = new HashSet<Integer>(); for (String domain : domains) { int port = java.net.URI.create(domain).getPort(); ports.add(port);// w w w . jav a 2 s. com StringBuilder suffix = new StringBuilder(); if (port > 0) { suffix.append(port); } if (domain.startsWith("https")) { suffix.append('s'); } suffix.append('='); userCookies.add("username" + suffix); } assert reader != null; assert identifier != null; this.reader = reader; this.identifier = identifier; this.redirect_prefix = redirect_uri + "&return_to="; this.fullname_prefix = fullname_prefix; assert redirect_uri.contains("?"); boolean secureOnly = identifier.startsWith("https"); this.protectedPath = path; this.secureCookie = secureOnly ? ";Secure" : ""; String hex = Integer.toHexString(Math.abs(identifier.hashCode())); this.sid = "sid" + hex + "="; String string = realms.getRealm(identifier).getOriginSecret(); if (Base64.isBase64(string)) { this.secret = Base64.decodeBase64(string); } else { this.secret = string.getBytes(Charset.forName("UTF-8")); } }
From source file:com.developer4droid.contactslister.backend.image_load.EnhancedImageDownloader.java
private Bitmap downloadBitmap(String url) { // AndroidHttpClient is not allowed to be used from the main thread final HttpClient client = (mode == Mode.NO_ASYNC_TASK) ? new DefaultHttpClient() : AndroidHttpClient.newInstance("Android"); url = url.replace(" ", "%20"); final HttpGet getRequest = new HttpGet(url); try {/*from w ww .j ava 2s . c om*/ HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.e("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); // return BitmapFactory.decodeStream(inputStream); // Bug on slow connections, fixed in future release. // create descriptor String filename = String.valueOf(url.hashCode()); File f = new File(cacheDir, filename); InputStream is = new URL(url).openStream(); // copy stream to file OutputStream os = new FileOutputStream(f); // save stream to // SD copyStream(is, os); os.close(); // decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // Find the correct scale value. It should be the power of 2. int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_IMAGE_SIZE || height_tmp / 2 < REQUIRED_IMAGE_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FlushedInputStream(inputStream), null, o2); // return BitmapFactory.decodeStream(inputStream); } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (OutOfMemoryError error) { error.printStackTrace(); } catch (IOException e) { getRequest.abort(); Log.e(LOG_TAG, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.e(LOG_TAG, "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.e(LOG_TAG, "Error while retrieving bitmap from " + url, e); } finally { if ((client instanceof AndroidHttpClient)) { ((AndroidHttpClient) client).close(); } } return null; }
From source file:com.lvlstudios.gtmessage.server.RegisterServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("doPost " + req.getRequestURI()); resp.setContentType("text/plain"); RequestInfo reqInfo = RequestInfo.processRequest(req, resp, getServletContext()); if (reqInfo == null) { return;//from w ww .j av a 2 s. c om } if (reqInfo.deviceRegistrationID == null) { resp.setStatus(400); resp.getWriter().println(ERROR_STATUS + "(Must specify devregid)"); log.severe("Missing registration id "); return; } String deviceName = reqInfo.getParameter("deviceName"); if (deviceName == null) { deviceName = "Phone"; } // TODO: generate the device name by adding a number suffix for multiple // devices of same type. Change android app to send model/type. String deviceType = reqInfo.getParameter("deviceType"); if (deviceType == null) { deviceType = "ac2dm"; } // Because the deviceRegistrationId isn't static, we use a static // identifier for the device. (Can be null in older clients) String deviceId = reqInfo.getParameter("deviceId"); // Context-shared PMF. PersistenceManager pm = C2DMessaging.getPMF(getServletContext()).getPersistenceManager(); try { List<DeviceInfo> registrations = reqInfo.devices; if (registrations.size() > MAX_DEVICES) { // we could return an error - but user can't handle it yet. // we can't let it grow out of bounds. // TODO: we should also define a 'ping' message and expire/remove // unused registrations DeviceInfo oldest = registrations.get(0); if (oldest.getRegistrationTimestamp() == null) { reqInfo.deleteRegistration(oldest.getDeviceRegistrationID()); } else { long oldestTime = oldest.getRegistrationTimestamp().getTime(); for (int i = 1; i < registrations.size(); i++) { if (registrations.get(i).getRegistrationTimestamp().getTime() < oldestTime) { oldest = registrations.get(i); oldestTime = oldest.getRegistrationTimestamp().getTime(); } } reqInfo.deleteRegistration(oldest.getDeviceRegistrationID()); } } // Get device if it already exists, else create String suffix = (deviceId != null ? "#" + Long.toHexString(Math.abs(deviceId.hashCode())) : ""); Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), reqInfo.userName + suffix); DeviceInfo device = null; try { device = pm.getObjectById(DeviceInfo.class, key); } catch (JDOObjectNotFoundException e) { } if (device == null) { device = new DeviceInfo(key, reqInfo.deviceRegistrationID); device.setType(deviceType); } else { // update registration id device.setDeviceRegistrationID(reqInfo.deviceRegistrationID); device.setRegistrationTimestamp(new Date()); } device.setName(deviceName); // update display name // TODO: only need to write if something changed, for chrome nothing // changes, we just create a new channel pm.makePersistent(device); log.log(Level.INFO, "Registered device " + reqInfo.userName + " " + deviceType); if (device.getType().equals(DeviceInfo.TYPE_CHROME)) { String channelId = ChannelServiceFactory.getChannelService() .createChannel(reqInfo.deviceRegistrationID); resp.getWriter().println(OK_STATUS + " " + channelId); } else { resp.getWriter().println(OK_STATUS); } } catch (Exception e) { resp.setStatus(500); resp.getWriter().println(ERROR_STATUS + " (Error registering device)"); log.log(Level.WARNING, "Error registering device.", e); } finally { pm.close(); } }
From source file:fuse.okuyamafs.OkuyamaFilesystem.java
public int write(String path, Object fh, boolean isWritepage, ByteBuffer buf, long offset) throws FuseException { log.info("write path:" + path + " offset:" + offset + " isWritepage:" + isWritepage + " buf.limit:" + buf.limit());/* w ww. j a v a 2 s . c o m*/ //long startAA = System.nanoTime(); try { if (startTimeAAA == 0L) startTimeAAA = System.nanoTime(); // ?????????????? if (OkuyamaFilesystem.storageType == 1) return realWrite(path, fh, isWritepage, buf, offset); if (fh == null) return Errno.EBADE; synchronized (this.parallelDataAccessSync[((path.hashCode() << 1) >>> 1) % 100]) { if (appendWriteDataBuf.containsKey(fh)) { Map appendData = (Map) appendWriteDataBuf.get(fh); ByteArrayOutputStream bBuf = (ByteArrayOutputStream) appendData.get("buf"); long bOffset = ((Long) appendData.get("offset")).longValue(); if ((bOffset + bBuf.size()) == offset) { byte[] tmpBuf = new byte[buf.limit()]; buf.get(tmpBuf); bBuf.write(tmpBuf); // ?????????????????? if (bBuf.size() >= writeBufferSize) { // ??????? appendWriteDataBuf.remove(fh); String bPath = (String) appendData.get("path"); Object bFh = (Object) appendData.get("fh"); boolean bIsWritepage = ((Boolean) appendData.get("isWritepage")).booleanValue(); int ret = this.realWrite(bPath, bFh, bIsWritepage, bBuf, bOffset); return ret; } else { return 0; } } else { // offset????????????? appendWriteDataBuf.remove(fh); String bPath = (String) appendData.get("path"); Object bFh = (Object) appendData.get("fh"); boolean bIsWritepage = ((Boolean) appendData.get("isWritepage")).booleanValue(); int realWriteRet = this.realWrite(bPath, bFh, bIsWritepage, bBuf, bOffset); if (realWriteRet == 0) { int retI = this.realWrite(path, fh, isWritepage, buf, offset); return retI; } else { return realWriteRet; } } } else { Map appendData = new HashMap(); appendData.put("path", path); appendData.put("fh", fh); appendData.put("isWritepage", isWritepage); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024 * 1024 * 10 + 8192); byte[] tmpByte = new byte[buf.limit()]; buf.get(tmpByte); baos.write(tmpByte); appendData.put("buf", baos); appendData.put("offset", offset); this.appendWriteDataBuf.put(fh, appendData); this.writeBufFpMap.addGroupingData(path, fh); return 0; } } } catch (Exception e) { throw new FuseException(e); } finally { } }
From source file:com.google.android.chrometophone.server.RegisterServlet.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/plain"); RequestInfo reqInfo = RequestInfo.processRequest(req, resp, getServletContext()); if (reqInfo == null) { return;//from www. j ava 2s. c o m } if (reqInfo.deviceRegistrationID == null) { resp.setStatus(400); resp.getWriter().println(ERROR_STATUS + "(Must specify devregid)"); log.severe("Missing registration id "); return; } String deviceName = reqInfo.getParameter("deviceName"); if (deviceName == null) { deviceName = "Phone"; } // TODO: generate the device name by adding a number suffix for multiple // devices of same type. Change android app to send model/type. String deviceType = reqInfo.getParameter("deviceType"); if (deviceType == null) { deviceType = "ac2dm"; } String gcm = reqInfo.getParameter("gcm"); boolean isGcm = gcm != null && gcm.equalsIgnoreCase("true"); // Because the deviceRegistrationId isn't static, we use a static // identifier for the device. (Can be null in older clients) String deviceId = reqInfo.getParameter("deviceId"); // Context-shared PMF. PersistenceManager pm = C2DMessaging.getPMF(getServletContext()).getPersistenceManager(); try { List<DeviceInfo> registrations = reqInfo.devices; if (registrations.size() > MAX_DEVICES) { // we could return an error - but user can't handle it yet. // we can't let it grow out of bounds. // TODO: we should also define a 'ping' message and expire/remove // unused registrations DeviceInfo oldest = registrations.get(0); if (oldest.getRegistrationTimestamp() == null) { reqInfo.deleteRegistration(oldest.getDeviceRegistrationID(), deviceType); } else { long oldestTime = oldest.getRegistrationTimestamp().getTime(); for (int i = 1; i < registrations.size(); i++) { if (registrations.get(i).getRegistrationTimestamp().getTime() < oldestTime) { oldest = registrations.get(i); oldestTime = oldest.getRegistrationTimestamp().getTime(); } } reqInfo.deleteRegistration(oldest.getDeviceRegistrationID(), deviceType); } } // Get device if it already exists, else create String suffix = (deviceId != null ? "#" + Long.toHexString(Math.abs(deviceId.hashCode())) : ""); Key key = KeyFactory.createKey(DeviceInfo.class.getSimpleName(), reqInfo.userName + suffix); DeviceInfo device = null; try { device = pm.getObjectById(DeviceInfo.class, key); } catch (JDOObjectNotFoundException e) { } if (device == null) { device = new DeviceInfo(key, reqInfo.deviceRegistrationID); device.setType(deviceType); } else { // update registration id device.setDeviceRegistrationID(reqInfo.deviceRegistrationID); // must update type, as this could be a C2DM to GCM migration device.setType(deviceType); device.setRegistrationTimestamp(new Date()); } device.setName(deviceName); // update display name device.setGcm(isGcm); // TODO: only need to write if something changed, for chrome nothing // changes, we just create a new channel pm.makePersistent(device); log.log(Level.INFO, "Registered device " + reqInfo.userName + " " + deviceType + "(gcm: " + isGcm + ")"); if (device.getType().equals(DeviceInfo.TYPE_CHROME)) { String channelId = ChannelServiceFactory.getChannelService() .createChannel(reqInfo.deviceRegistrationID); resp.getWriter().println(OK_STATUS + " " + channelId); } else { resp.getWriter().println(OK_STATUS); } } catch (Exception e) { resp.setStatus(500); resp.getWriter().println(ERROR_STATUS + " (Error registering device)"); log.log(Level.WARNING, "Error registering device.", e); } finally { pm.close(); } }
From source file:io.pravega.service.server.containers.StreamSegmentMapperTests.java
/** * Tests the ability of the StreamSegmentMapper to generate/return the Id of an existing StreamSegment, as well as * retrieving existing attributes./* www .j a v a 2s . c om*/ */ @Test public void testGetOrAssignStreamSegmentId() { final int segmentCount = 10; final int transactionsPerSegment = 5; @Cleanup TestContext context = new TestContext(); HashSet<String> storageSegments = new HashSet<>(); for (int i = 0; i < segmentCount; i++) { String segmentName = getName(i); storageSegments.add(segmentName); setAttributes(segmentName, storageSegments.size() % ATTRIBUTE_COUNT, context); for (int j = 0; j < transactionsPerSegment; j++) { // There is a small chance of a name conflict here, but we don't care. As long as we get at least one // Transaction per segment, we should be fine. String transactionName = StreamSegmentNameUtils.getTransactionNameFromId(segmentName, UUID.randomUUID()); storageSegments.add(transactionName); setAttributes(transactionName, storageSegments.size() % ATTRIBUTE_COUNT, context); } } // We setup all necessary handlers, except the one for create. We do not need to create new Segments here. setupOperationLog(context); Predicate<String> isSealed = segmentName -> segmentName.hashCode() % 2 == 0; Function<String, Long> getInitialLength = segmentName -> (long) Math.abs(segmentName.hashCode()); setupStorageGetHandler(context, storageSegments, segmentName -> new StreamSegmentInformation(segmentName, getInitialLength.apply(segmentName), isSealed.test(segmentName), false, new ImmutableDate())); // First, map all the parents (stand-alone segments). for (String name : storageSegments) { if (StreamSegmentNameUtils.getParentStreamSegmentName(name) == null) { long id = context.mapper.getOrAssignStreamSegmentId(name, TIMEOUT).join(); Assert.assertNotEquals("No id was assigned for StreamSegment " + name, ContainerMetadata.NO_STREAM_SEGMENT_ID, id); SegmentMetadata sm = context.metadata.getStreamSegmentMetadata(id); Assert.assertNotNull("No metadata was created for StreamSegment " + name, sm); long expectedLength = getInitialLength.apply(name); boolean expectedSeal = isSealed.test(name); Assert.assertEquals("Metadata does not have the expected length for StreamSegment " + name, expectedLength, sm.getDurableLogLength()); Assert.assertEquals( "Metadata does not have the expected value for isSealed for StreamSegment " + name, expectedSeal, sm.isSealed()); val segmentState = context.stateStore.get(name, TIMEOUT).join(); Map<UUID, Long> expectedAttributes = segmentState == null ? null : segmentState.getAttributes(); SegmentMetadataComparer.assertSameAttributes( "Unexpected attributes in metadata for StreamSegment " + name, expectedAttributes, sm); } } // Now, map all the Transactions. for (String name : storageSegments) { String parentName = StreamSegmentNameUtils.getParentStreamSegmentName(name); if (parentName != null) { long id = context.mapper.getOrAssignStreamSegmentId(name, TIMEOUT).join(); Assert.assertNotEquals("No id was assigned for Transaction " + name, ContainerMetadata.NO_STREAM_SEGMENT_ID, id); SegmentMetadata sm = context.metadata.getStreamSegmentMetadata(id); Assert.assertNotNull("No metadata was created for Transaction " + name, sm); long expectedLength = getInitialLength.apply(name); boolean expectedSeal = isSealed.test(name); Assert.assertEquals("Metadata does not have the expected length for Transaction " + name, expectedLength, sm.getDurableLogLength()); Assert.assertEquals( "Metadata does not have the expected value for isSealed for Transaction " + name, expectedSeal, sm.isSealed()); val segmentState = context.stateStore.get(name, TIMEOUT).join(); Map<UUID, Long> expectedAttributes = segmentState == null ? null : segmentState.getAttributes(); SegmentMetadataComparer.assertSameAttributes( "Unexpected attributes in metadata for Transaction " + name, expectedAttributes, sm); // Check parenthood. Assert.assertNotEquals("No parent defined in metadata for Transaction " + name, ContainerMetadata.NO_STREAM_SEGMENT_ID, sm.getParentId()); long parentId = context.metadata.getStreamSegmentId(parentName, false); Assert.assertEquals("Unexpected parent defined in metadata for Transaction " + name, parentId, sm.getParentId()); } } }
From source file:de.ingrid.iplug.sns.SNSController.java
/** * @param topic// www. jav a 2s . c o m * @param plugId * @param associationType * @param lang * @return A ingrid topic from a Topic. */ private synchronized de.ingrid.iplug.sns.utils.Topic buildTopicFromTopic(Topic topic, String plugId, String associationType, String lang) { BaseName[] baseNames = topic.getBaseName(); // Set a default if for the selected language nothing exists. String title = baseNames[0].getBaseNameString().get_value(); String topicLang = "en"; for (int i = 0; i < baseNames.length; i++) { final Scope scope = baseNames[i].getScope(); if (scope != null) { final String href = scope.getTopicRef()[0].getHref(); if (href.endsWith('#' + lang)) { title = baseNames[i].getBaseNameString().get_value(); topicLang = lang; break; } } } String summary = title + ' ' + topic.getInstanceOf()[0].getTopicRef().getHref(); String topicId = topic.getId(); de.ingrid.iplug.sns.utils.Topic result = new de.ingrid.iplug.sns.utils.Topic(plugId, topicId.hashCode(), topicId, title, summary, associationType, null); pushOccurensie(de.ingrid.iplug.sns.utils.Topic.NATIVEKEY_OCC, topic, result, lang); pushOccurensie(DetailedTopic.GEMET_OCC, topic, result, lang); String topicNativeKey = result.getTopicNativeKey(); if (null != topicNativeKey) { String ags = SNSUtil.transformSpacialReference(this.fNativeKeyPrefix, topicNativeKey); if (ags.startsWith("lawa:")) { ags = SNSUtil.transformSpacialReference("lawa:", topicNativeKey); } result.setTopicNativeKey(ags); } else { result.setTopicNativeKey(topicId); } result.setLanguage(topicLang); return result; }