List of usage examples for java.lang Long toHexString
public static String toHexString(long i)
From source file:core.importmodule.parser.cisco.CiscoCommandSplitter.java
private File getTempFile(String prefix, boolean deleteOnExit) throws IOException { String finalPrefix = prefix == null ? "GM3" : prefix; File f = File.createTempFile(finalPrefix, Long.toHexString(System.nanoTime()), getOuputDirectory()); if (deleteOnExit) { f.deleteOnExit();//from w ww . j a va 2s .co m } return f; }
From source file:org.apache.accumulo.monitor.rest.trace.TracesResource.java
protected Range getRangeForTrace(long minutesSince) { long endTime = System.currentTimeMillis(); long millisSince = minutesSince * 60 * 1000; // Catch the overflow if (millisSince < minutesSince) { millisSince = endTime;/*from w w w . j a va 2s . co m*/ } long startTime = endTime - millisSince; String startHexTime = Long.toHexString(startTime), endHexTime = Long.toHexString(endTime); if (startHexTime.length() < endHexTime.length()) { StringUtils.leftPad(startHexTime, endHexTime.length(), '0'); } return new Range(new Text("start:" + startHexTime), new Text("start:" + endHexTime)); }
From source file:edu.umass.cs.gigapaxos.testing.TESTPaxosApp.java
@Override public synchronized String checkpoint(String paxosID) { if (ABSOLUTE_NOOP) return paxosID + ":" + Long.toHexString(((long) (Math.random() * Long.MAX_VALUE))); PaxosState state = this.allState.get(paxosID); if (state != null) return state.value; return null;//from www. j av a2 s. c o m }
From source file:de.burlov.amazon.s3.dirsync.DirSync.java
/** * Synchronisiert Daten im lokalen Verzeichnis und auf dem Server * //from w w w. j av a 2 s. c o m * @param baseDir * @param folderName * @param up * Synchronisationsrichtung. Wenn 'true' dann werden Daten von lokalen Verzeichnis auf * den Server geschrieben. Wenn 'false' Dann werden Daten von Server auf lokalen * Verzeichnis geschrieben * @param snapShot * Wenn 'true' dann wird Synchronisierung in 'Abbild' Modus duchgefuehrt. D.h. * Zielverzeichnis wird auf den gleichen Stand wie Quelle gebracht: neue Dateien werde * geloescht, geloeschte wiederherstellt und modifiezierte upgedated. Wenn 'false' dann * werden neue Dateien hinzugefuegt und modifizierte upgedated aber auf keinen Fall * irgendetwas geloescht. * @throws DirSyncException */ public void syncFolder(File baseDir, String folderName, boolean up, boolean snapShot) throws DirSyncException { connect(up); deletedFiles = 0; transferredFiles = 0; transferredData = 0; if (!baseDir.isDirectory()) { throw new DirSyncException("Invalid directory: " + baseDir.getAbsolutePath()); } Folder folder = getFolder(folderName); if (folder == null) { if (!up) { log.warn("No such folder " + folderName); //System.out.println("No such folder " + folderName); return; } folder = new Folder(folderName, Long.toHexString(mainIndex.getNextId())); } Collection<LocalFile> files; try { files = generateChangedFileList(baseDir, folder); } catch (Exception e) { throw new DirSyncException(e); } if (up) { syncUp(folder, files, snapShot); } else { syncDown(folder, baseDir, files, snapShot); } log.info("Transferred data: " + FileUtils.byteCountToDisplaySize(transferredData)); log.info("Transferred files: " + transferredFiles); log.info("Deleted/Removed files: " + deletedFiles); }
From source file:org.alfresco.module.vti.web.actions.VtiSoapAction.java
/** * Creates an appropriate SOAP Fault Response, in the appropriate * of the two different formats// ww w . ja v a 2s. c om */ private void createFaultSOAPResponse(VtiSoapRequest request, Element responseElement, Exception e, VtiEndpoint vtiEndpoint) { // Is it something like // <FooResponse><FooResult><Error ID="123"/></FooResult></FooResponse> ? if (e instanceof VtiHandlerException) { VtiHandlerException handlerException = (VtiHandlerException) e; Element endpointResponseE = responseElement.addElement(vtiEndpoint.getName() + "Response", vtiEndpoint.getNamespace()); Element endpointResultE = endpointResponseE.addElement(vtiEndpoint.getName() + "Result"); //String errorMessage = handlerException.getMessage(); String errorCode; if (handlerException.getErrorCode() > -1) { errorCode = Long.toString(handlerException.getErrorCode()); } else { errorCode = "13"; } // Return it as an ID based error, without the message endpointResultE.addElement("Error").addAttribute("ID", errorCode); } else if (e instanceof DwsException) { // <FooResponse><FooResult><Error>[ID]</Error></FooResult></FooResponse> DwsException handlerException = (DwsException) e; Element endpointResponseE = responseElement.addElement(vtiEndpoint.getResponseTagName(), vtiEndpoint.getNamespace()); Element endpointResultE = endpointResponseE.addElement(vtiEndpoint.getResultTagName()); DwsError error = handlerException.getError(); // Error value, numeric ID int errorId = error.toInt(); // Error code, e.g. "ServerFailure" String errorCode = error.toCode(); // Return it as an Coded ID based error, without the message Map<String, Object> errorAttrs = new HashMap<String, Object>(1); errorAttrs.put("ID", errorId); StringBuilder sb = startTag("Error", errorAttrs); sb.append(errorCode); sb.append(endTag("Error")); String elText = sb.toString(); endpointResultE.setText(elText); } else { // We need to return a regular SOAP Fault String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "Unknown error"; } // Manually generate the Soap error response Element fault = responseElement.addElement(QName.get("Fault", "s", VtiSoapResponse.NAMESPACE)); if ("1.2".equals(request.getVersion())) { // SOAP 1.2 is Code + Reason Element faultCode = fault.addElement(QName.get("Code", "s", VtiSoapResponse.NAMESPACE)); Element faultCodeText = faultCode.addElement(QName.get("Value", "s", VtiSoapResponse.NAMESPACE)); faultCodeText.addText("s:Server"); Element faultReason = fault.addElement(QName.get("Reason", "s", VtiSoapResponse.NAMESPACE)); Element faultReasonText = faultReason.addElement(QName.get("Text", "s", VtiSoapResponse.NAMESPACE)); faultReasonText.addText("Exception of type '" + e.getClass().getName() + "' was thrown."); } else { // SOAP 1.1 is Code + String Element faultCode = fault.addElement("faultcode"); faultCode.addText("s:Server"); Element faultString = fault.addElement("faultstring"); faultString.addText(e.getClass().getName()); } // Both versions get the detail Element detail = fault.addElement("detail"); Element errorstring = detail .addElement(QName.get("errorstring", "", "http://schemas.microsoft.com/sharepoint/soap/")); errorstring.addText(errorMessage); // Include the code if known if (e instanceof VtiSoapException) { VtiSoapException soapException = (VtiSoapException) e; if (soapException.getErrorCode() > 0) { Element errorcode = detail.addElement( QName.get("errorcode", "", "http://schemas.microsoft.com/sharepoint/soap/")); // Codes need to be zero padded to 8 characters, eg 0x12345678 String codeHex = Long.toHexString(soapException.getErrorCode()); while (codeHex.length() < 8) { codeHex = "0" + codeHex; } errorcode.addText("0x" + codeHex); } } } }
From source file:com.servioticy.dispatcher.SOProcessor020.java
public SensorUpdate getResultSU(String streamId, Map<String, SensorUpdate> inputSUs, String origin, long timestamp) throws IOException, ScriptException { ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); SensorUpdate su = new SensorUpdate(); su.setLastUpdate(timestamp);//from ww w .ja va 2s .c o m su.setChannels(new LinkedHashMap<String, SUChannel>()); SOStream stream = so.getStreams(this.mapper).get(streamId); for (Map.Entry<String, SOChannel> channelEntry : stream.getChannels().entrySet()) { SOChannel channel = channelEntry.getValue(); SUChannel suChannel = new SUChannel(); String currentValueCode = channel.getCurrentValue(); // TODO Check for invalid calls // TODO Check for an invalid header if (isFunction(currentValueCode)) { // There is no code for one of the channels. Invalid. return null; } else { TypeReference type; Class dataClass; boolean array = false; switch (parseType(channel.getType())) { case TYPE_ARRAY_NUMBER: type = new TypeReference<List<Double>>() { }; array = true; break; case TYPE_NUMBER: type = new TypeReference<Double>() { }; break; case TYPE_ARRAY_BOOLEAN: type = new TypeReference<List<Boolean>>() { }; array = true; break; case TYPE_BOOLEAN: type = new TypeReference<Boolean>() { }; break; case TYPE_ARRAY_STRING: type = new TypeReference<List<String>>() { }; array = true; break; case TYPE_STRING: type = new TypeReference<String>() { }; break; // non-primitive types case TYPE_ARRAY_GEOPOINT: type = new TypeReference<List<GeoPoint>>() { }; array = true; break; case TYPE_GEOPOINT: type = new TypeReference<GeoPoint>() { }; break; default: return null; } String resultVar = "$" + Long.toHexString(UUID.randomUUID().getMostSignificantBits()); engine.eval(initializationCode(inputSUs, origin) + "var " + resultVar + " = JSON.stringify(" + currentValueCode + "(" + functionArgsString(currentValueCode) + ")" + ")"); Object result = this.mapper.readValue((String) engine.get(resultVar), type); if (result == null) { // Filtered output. The type is not the expected one. return null; } suChannel.setCurrentValue(result); } suChannel.setUnit(channel.getUnit()); su.getChannels().put(channelEntry.getKey(), suChannel); } su.setTriggerPath(new ArrayList<ArrayList<String>>()); su.setPathTimestamps(new ArrayList<Long>()); return su; }
From source file:com.oneguy.recognize.engine.GoogleStreamingEngine.java
private String generateRequestPairKey() { Random random = new Random(System.currentTimeMillis()); long value = random.nextLong(); return Long.toHexString(value); }
From source file:de.uzk.hki.da.convert.PublishImageConversionStrategy.java
/** * Adds a Text Watermark to the operation. * * @param commandAsList the command as list * @param audience the audience// w w w.j a va 2 s .c om * @return the watermark * @author Jens Peters */ private ArrayList<String> assembleWatermarkCommand(ArrayList<String> commandAsList, String audience) { if (getPublicationRightForAudience(audience) == null) return commandAsList; if (getPublicationRightForAudience(audience).getImageRestriction() == null) return commandAsList; String text = getPublicationRightForAudience(audience).getImageRestriction().getWatermarkString(); if (text == null || text.equals("")) { logger.debug("Adding Watermark: text not found for audience " + audience); return commandAsList; } String psize = getPublicationRightForAudience(audience).getImageRestriction().getWatermarkPointSize(); if (psize == null) { logger.debug("Adding watermark: point size not found for audience " + audience); throw new UserException(UserExceptionId.WATERMARK_NO_POINTSIZE, "Beim Wasserzeichen muss ein Parameter \"pointsize\" vorhanden sein."); } String position = getPublicationRightForAudience(audience).getImageRestriction().getWatermarkPosition(); if (position == null) { logger.debug("Adding watermark: gravity not found for audience " + audience); throw new UserException(UserExceptionId.WATERMARK_NO_GRAVITY, "Beim Wasserzeichen muss ein Parameter \"gravity\" vorhanden sein."); } String opacity = getPublicationRightForAudience(audience).getImageRestriction().getWatermarkOpacity(); if (opacity == null) { logger.debug("Adding watermark: opacity not found for audience " + audience); throw new UserException(UserExceptionId.WATERMARK_NO_OPACITY, "Beim Wasserzeichen muss eine Parameter \"opacity\" vorhanden sein."); } String opacityHex = Long.toHexString(Math.round(Integer.parseInt(opacity) * 2.55)); if (opacityHex.length() == 1) opacityHex = "0" + opacityHex; commandAsList.add("-pointsize"); commandAsList.add(psize); commandAsList.add("-draw"); commandAsList.add("gravity " + position + " fill #000000" + opacityHex + " text 0,15 '" + text + "' fill #ffffff" + opacityHex + " text 0,14 '" + text + "'"); return commandAsList; }
From source file:org.rhq.enterprise.server.scheduler.jobs.ContentProviderSyncJob.java
/** * Creates a unique name for a new content source sync job. Calling this * method multiple times with the same content source always produces a different name * which is useful if you want to schedule an new job that is separate and distinct * from any other job in the system.// w w w . j av a 2s .c o m * * @param cs the content source * * @return a unique job name that can be used for a new job to sync a given content source */ public static String createUniqueJobName(ContentSource cs) { // the quartz table has a limited column width of 80 - but we need to use the names to make jobs unique // so encode the names' hashcodes to ensure we fix into the quartz job name column. // appendStr is used to make the job unique among others for the same content source. String nameEncoded = Integer.toHexString(cs.getName().hashCode()); String typeNameEncoded = Integer.toHexString(cs.getContentSourceType().getName().hashCode()); String appendStr = Long.toHexString(System.currentTimeMillis()); String jobName = nameEncoded + SEPARATOR + typeNameEncoded + SEPARATOR + appendStr; if (jobName.length() > 80) { throw new IllegalArgumentException( "Job names max size is 80 chars due to DB column size restrictions: " + jobName); } return jobName; }
From source file:com.maass.android.imgur_uploader.ImgurUpload.java
/** * This method uploads an image from the given uri. It does the uploading in * small chunks to make sure it doesn't over run the memory. * //from w w w . j av a 2 s. c o m * @param uri * image location * @return map containing data from interaction */ private String readPictureDataAndUpload(final Uri uri) { Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)"); try { final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r"); final int totalFileLength = (int) assetFileDescriptor.getLength(); assetFileDescriptor.close(); // Create custom progress notification mProgressNotification = new Notification(R.drawable.icon, getString(R.string.upload_in_progress), System.currentTimeMillis()); // set as ongoing mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT; // set custom view to notification mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength); //empty intent for the notification final Intent progressIntent = new Intent(); final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0); mProgressNotification.contentIntent = contentIntent; // add notification to manager mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); final InputStream inputStream = getContentResolver().openInputStream(uri); final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis()) + Long.toHexString((new Random()).nextLong()); final String boundary = "--" + boundaryString; final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json")) .openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\""); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); conn.setChunkedStreamingMode(CHUNK_SIZE); final OutputStream hrout = conn.getOutputStream(); final PrintStream hout = new PrintStream(hrout); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"key\""); hout.println("Content-Type: text/plain"); hout.println(); hout.println(API_KEY); hout.println(boundary); hout.println("Content-Disposition: form-data; name=\"image\""); hout.println("Content-Transfer-Encoding: base64"); hout.println(); hout.flush(); { final Base64OutputStream bhout = new Base64OutputStream(hrout); final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES]; int read = 0; int totalRead = 0; long lastLogTime = 0; while (read >= 0) { read = inputStream.read(pictureData); if (read > 0) { bhout.write(pictureData, 0, read); totalRead += read; if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) { lastLogTime = System.currentTimeMillis(); Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength + " bytes (" + (100 * totalRead) / totalFileLength + "%)"); //make a final version of the total read to make the handler happy final int totalReadFinal = totalRead; mHandler.post(new Runnable() { public void run() { mProgressNotification.contentView = generateProgressNotificationView( totalReadFinal, totalFileLength); mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification); } }); } bhout.flush(); hrout.flush(); } } Log.d(this.getClass().getName(), "Finishing upload..."); // This close is absolutely necessary, this tells the // Base64OutputStream to finish writing the last of the data // (and including the padding). Without this line, it will miss // the last 4 chars in the output, missing up to 3 bytes in the // final output. bhout.close(); Log.d(this.getClass().getName(), "Upload complete..."); mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead, false); } hout.println(boundary); hout.flush(); hrout.close(); inputStream.close(); Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server"); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final StringBuilder rData = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { rData.append(line).append('\n'); } return rData.toString(); } catch (final IOException e) { Log.e(this.getClass().getName(), "Upload failed", e); } return null; }