label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
public static String ReadURLString(String str) throws IOException { try { URL url = new URL(str); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); String inputLine; String line = ""; int i = 0; while ((inputLine = in.readLine()) != null) { line += inputLine + "\n"; } is.close(); isr.close(); in.close(); return line; } catch (Exception e) { e.printStackTrace(); } return ""; }
Code Sample 2:
public static Collection<Class<? extends Page>> loadPages() throws IOException { ClassLoader ldr = Thread.currentThread().getContextClassLoader(); Collection<Class<? extends Page>> pages = new ArrayList<Class<? extends Page>>(); Enumeration<URL> e = ldr.getResources("META-INF/services/" + Page.class.getName()); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); ; try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) break; int comment = line.indexOf('#'); if (comment >= 0) line = line.substring(0, comment); String name = line.trim(); if (name.length() == 0) continue; Class<?> clz = Class.forName(name, true, ldr); Class<? extends Page> impl = clz.asSubclass(Page.class); pages.add(impl); } } catch (Exception ex) { System.out.println(ex); } finally { try { is.close(); } catch (Exception ex) { } } } return pages; }
|
11
|
Code Sample 1:
public static String hash(String in, String algorithm) { if (StringUtils.isBlank(algorithm)) algorithm = DEFAULT_ALGORITHM; try { md = MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException nsae) { logger.error("No such algorithm exception", nsae); } md.reset(); md.update(in.getBytes()); String out = null; try { out = Base64Encoder.encode(md.digest()); } catch (IOException e) { logger.error("Error converting to Base64 ", e); } if (out.endsWith("\n")) out = out.substring(0, out.length() - 1); return out; }
Code Sample 2:
public void insertQuotation(final String sText, final Source aSource) throws ConfigHandlerError, com.sun.star.uno.Exception { final XTextDocument xTextDocument = (XTextDocument) this.docController.getXInterface(XTextDocument.class, this.docController.getXFrame().getController().getModel()); final XMultiServiceFactory xMultiServiceFactory = (XMultiServiceFactory) this.docController.getXInterface(XMultiServiceFactory.class, xTextDocument); final XText xText = xTextDocument.getText(); final XTextViewCursor xTextViewCursor = ((XTextViewCursorSupplier) this.docController.getXInterface(XTextViewCursorSupplier.class, this.docController.getXFrame().getController())).getViewCursor(); final XTextRange xTextRange = xTextViewCursor.getStart(); if (aSource.getSourceType() == SourceType.QUOTE || aSource.getSourceType() == SourceType.WEBQUOTE || aSource.getSourceType() == SourceType.WEBQUOTE) { final XPropertySet xQuoteProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xTextViewCursor); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String("Quotations")); } xQuoteProps.setPropertyValue("CharStyleName", new String("Citation")); final Object aBookmark = xMultiServiceFactory.createInstance("com.sun.star.text.Bookmark"); this.sourceUtils.setNameToObject(aBookmark, this.docController.getLanguageController().__("Quote: ") + aSource.getShortinfo()); final XTextContent xTextContent = (XTextContent) this.docController.getXInterface(XTextContent.class, aBookmark); xText.insertTextContent(xTextRange, xTextContent, false); this.sourceUtils.insertBibliographyEntry(xMultiServiceFactory, xTextRange, aSource, sText); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String(this.docController.getLanguageController().__("Default"))); } xQuoteProps.setPropertyValue("CharStyleName", new String(this.docController.getLanguageController().__("Default"))); } else if (aSource.getSourceType() == SourceType.IMAGE || aSource.getSourceType() == SourceType.TABLE) { xText.insertControlCharacter(xTextRange, ControlCharacter.PARAGRAPH_BREAK, false); final XTextFrame xFrame = this.sourceUtils.getTextFrame(aSource.getShortinfo(), xMultiServiceFactory); xText.insertTextContent(xTextRange, xFrame, false); final XText xFrameText = xFrame.getText(); final XTextCursor xFrameCursor = xFrameText.createTextCursor(); final Size aNewSize = new Size(); XPropertySet xBaseFrameProps = null; final Size aPageTextAreaSize = this.sourceUtils.getPageTextAreaSize(xTextDocument, xTextViewCursor); if (aSource.getSourceType() == SourceType.IMAGE) { try { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption illustration: ") + aSource.getShortinfo()); final XNameContainer xBitmapContainer = (XNameContainer) this.docController.getXInterface(XNameContainer.class, xMultiServiceFactory.createInstance("com.sun.star.drawing.BitmapTable")); final XTextContent xImage = (XTextContent) this.docController.getXInterface(XTextContent.class, xMultiServiceFactory.createInstance("com.sun.star.text.TextGraphicObject")); this.sourceUtils.setNameToObject(xImage, this.docController.getLanguageController().__("Illustration: ") + aSource.getShortinfo()); final String graphicURL = this.docController.getPathUtils().getFileURLFromSystemPath(((Image) aSource).getFile().getPath(), ((Image) aSource).getFile().getPath()); xBaseFrameProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xImage); xBaseFrameProps.setPropertyValue("AnchorType", com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH); xBaseFrameProps.setPropertyValue("GraphicURL", graphicURL); final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(graphicURL.getBytes(), 0, graphicURL.length()); final String internalName = new BigInteger(1, md.digest()).toString(16); xBitmapContainer.insertByName(internalName, graphicURL); final String internalURL = (String) (xBitmapContainer.getByName(internalName)); xBaseFrameProps.setPropertyValue("GraphicURL", internalURL); float imageRatio = (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height / (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width; final Size aUsedAreaSize = new Size(this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width * 26, this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height * 26); if (aUsedAreaSize.Width >= aPageTextAreaSize.Width) { aNewSize.Width = aPageTextAreaSize.Width; aNewSize.Height = (int) (aPageTextAreaSize.Width * imageRatio); } else { aNewSize.Width = aUsedAreaSize.Width; aNewSize.Height = aUsedAreaSize.Height; } xFrameText.insertTextContent(xFrameCursor, xImage, false); xBitmapContainer.removeByName(internalName); } catch (final NoSuchAlgorithmException e) { new ASTError(e).severe(); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Illustration"), xMultiServiceFactory); } else if (aSource.getSourceType() == SourceType.TABLE) { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption table: ") + aSource.getShortinfo()); xBaseFrameProps = this.sourceUtils.createTextEmbeddedObjectCalc(xMultiServiceFactory); this.sourceUtils.setNameToObject(xBaseFrameProps, this.docController.getLanguageController().__("Table: ") + aSource.getShortinfo()); xFrameText.insertTextContent(xFrameCursor, (XTextContent) this.docController.getXInterface(XTextContent.class, xBaseFrameProps), false); final XEmbeddedObjectSupplier2 xEmbeddedObjectSupplier = (XEmbeddedObjectSupplier2) this.docController.getXInterface(XEmbeddedObjectSupplier2.class, xBaseFrameProps); final XEmbeddedObject xEmbeddedObject = xEmbeddedObjectSupplier.getExtendedControlOverEmbeddedObject(); long nAspect = xEmbeddedObjectSupplier.getAspect(); final Size aVisualAreaSize = xEmbeddedObject.getVisualAreaSize(nAspect); final XComponent xComponent = xEmbeddedObjectSupplier.getEmbeddedObject(); XSpreadsheets xSpreadsheets = ((XSpreadsheetDocument) this.docController.getXInterface(XSpreadsheetDocument.class, xComponent)).getSheets(); final XIndexAccess xIndexAccess = (XIndexAccess) this.docController.getXInterface(XIndexAccess.class, xSpreadsheets); final XSpreadsheet xSpreadsheet = (XSpreadsheet) this.docController.getXInterface(XSpreadsheet.class, xIndexAccess.getByIndex(0)); final XSheetLinkable xSheetLinkable = (XSheetLinkable) this.docController.getXInterface(XSheetLinkable.class, xSpreadsheet); xSheetLinkable.link(this.docController.getPathUtils().getFileURLFromSystemPath(((Table) aSource).getFile().getPath(), ((Table) aSource).getFile().getPath()), "", "", "", com.sun.star.sheet.SheetLinkMode.NORMAL); final CellRangeAddress aUsedArea = this.sourceUtils.getUsedArea(xSpreadsheet); final Size aUsedAreaSize = this.sourceUtils.calcCellRangeSize(xSpreadsheets, aUsedArea); if ((aUsedAreaSize.Width != aVisualAreaSize.Width) || (aUsedAreaSize.Height != aVisualAreaSize.Height)) { aNewSize.Height = (aUsedAreaSize.Height > aPageTextAreaSize.Height) ? aPageTextAreaSize.Height : aUsedAreaSize.Height; aNewSize.Width = (aUsedAreaSize.Width > aPageTextAreaSize.Width) ? aPageTextAreaSize.Width : aUsedAreaSize.Width; xEmbeddedObject.setVisualAreaSize(nAspect, aNewSize); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Table"), xMultiServiceFactory); } xBaseFrameProps.setPropertyValue("Width", aNewSize.Width); xBaseFrameProps.setPropertyValue("Height", aNewSize.Height); final XShape xShape = (XShape) this.docController.getXInterface(XShape.class, xFrame); xShape.setSize(aNewSize); } final XTextFieldsSupplier xTextFieldsSupplier = (XTextFieldsSupplier) this.docController.getXInterface(XTextFieldsSupplier.class, xMultiServiceFactory); final XRefreshable xRefreshable = (XRefreshable) this.docController.getXInterface(XRefreshable.class, xTextFieldsSupplier.getTextFields()); xRefreshable.refresh(); }
|
11
|
Code Sample 1:
public void testWriteThreadsNoCompression() throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.loadProfiles(CommandLineProcessorFactory.PROFILE.DB, CommandLineProcessorFactory.PROFILE.REST_CLIENT, CommandLineProcessorFactory.PROFILE.COLLECTOR); final LocalLogFileWriter writer = (LocalLogFileWriter) bootstrap.getBean(LogFileWriter.class); writer.init(); writer.setCompressionCodec(null); File fileInput = new File(baseDir, "testWriteOneFile/input"); fileInput.mkdirs(); File fileOutput = new File(baseDir, "testWriteOneFile/output"); fileOutput.mkdirs(); writer.setBaseDir(fileOutput); int fileCount = 100; int lineCount = 100; File[] inputFiles = createInput(fileInput, fileCount, lineCount); ExecutorService exec = Executors.newFixedThreadPool(fileCount); final CountDownLatch latch = new CountDownLatch(fileCount); for (int i = 0; i < fileCount; i++) { final File file = inputFiles[i]; final int count = i; exec.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { FileStatus.FileTrackingStatus status = FileStatus.FileTrackingStatus.newBuilder().setFileDate(System.currentTimeMillis()).setDate(System.currentTimeMillis()).setAgentName("agent1").setFileName(file.getName()).setFileSize(file.length()).setLogType("type1").build(); BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = reader.readLine()) != null) { writer.write(status, new ByteArrayInputStream((line + "\n").getBytes())); } } finally { IOUtils.closeQuietly(reader); } LOG.info("Thread[" + count + "] completed "); latch.countDown(); return true; } }); } latch.await(); exec.shutdown(); LOG.info("Shutdown thread service"); writer.close(); File[] outputFiles = fileOutput.listFiles(); assertNotNull(outputFiles); File testCombinedInput = new File(baseDir, "combinedInfile.txt"); testCombinedInput.createNewFile(); FileOutputStream testCombinedInputOutStream = new FileOutputStream(testCombinedInput); try { for (File file : inputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedInputOutStream); } } finally { testCombinedInputOutStream.close(); } File testCombinedOutput = new File(baseDir, "combinedOutfile.txt"); testCombinedOutput.createNewFile(); FileOutputStream testCombinedOutOutStream = new FileOutputStream(testCombinedOutput); try { System.out.println("----------------- " + testCombinedOutput.getAbsolutePath()); for (File file : outputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedOutOutStream); } } finally { testCombinedOutOutStream.close(); } FileUtils.contentEquals(testCombinedInput, testCombinedOutput); }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { FileChannel inChannel = new FileInputStream(src).getChannel(); FileChannel outChannel = new FileOutputStream(dst).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
Code Sample 2:
public StringBuffer render(RenderEngine c) { String logTime = null; if (c.getWorkerContext() != null) { logTime = c.getWorkerContext().getWorkerStart(); } if (c.isBreakState() || !c.canRender("u")) { return new StringBuffer(); } StringBuffer buffer = new StringBuffer(); varname = TagInspector.processElement(varname, c); action = TagInspector.processElement(action, c); filemode = TagInspector.processElement(filemode, c); xmlparse = TagInspector.processElement(xmlparse, c); encoding = TagInspector.processElement(encoding, c); decoding = TagInspector.processElement(decoding, c); filter = TagInspector.processElement(filter, c); sort = TagInspector.processElement(sort, c); useDocroot = TagInspector.processElement(useDocroot, c); useFilename = TagInspector.processElement(useFilename, c); useDest = TagInspector.processElement(useDest, c); xmlOutput = TagInspector.processElement(xmlOutput, c); renderOutput = TagInspector.processElement(renderOutput, c); callProc = TagInspector.processElement(callProc, c); vartype = TagInspector.processElement(vartype, c); if (sort == null || sort.equals("")) { sort = "asc"; } if (useFilename.equals("") && !action.equalsIgnoreCase("listing")) { return new StringBuffer(); } boolean isRooted = true; if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; } } if (isRooted && (useFilename.indexOf("/") == -1 || useFilename.startsWith("./"))) { if (c.getWorkerContext() != null && useFilename.startsWith("./")) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename.substring(2); Debug.inform("CWD path specified in filename, rewritten to '" + useFilename + "'"); } else if (c.getWorkerContext() != null && useFilename.indexOf("/") == -1) { useFilename = c.getWorkerContext().getClientContext().getPostVariable("current_path") + useFilename; Debug.inform("No path specified in filename, rewritten to '" + useFilename + "'"); } else { Debug.inform("No path specified in filename, no worker context, not rewriting filename."); } } StringBuffer filenameData = null; StringBuffer contentsData = null; StringBuffer fileDestData = null; contentsData = TagInspector.processBody(this, c); filenameData = new StringBuffer(useFilename); fileDestData = new StringBuffer(useDest); String currentDocroot = null; if (c.getWorkerContext() == null) { if (c.getRenderContext().getCurrentDocroot() == null) { currentDocroot = "."; } else { currentDocroot = c.getRenderContext().getCurrentDocroot(); } } else { currentDocroot = c.getWorkerContext().getDocRoot(); } if (!isRooted) { currentDocroot = ""; } if (useDocroot.equalsIgnoreCase("true")) { if (c.getVendContext().getVend().getIgnorableDocroot(c.getClientContext().getMatchedHost())) { isRooted = false; currentDocroot = ""; } } if (!currentDocroot.endsWith("/")) { if (!currentDocroot.equals("") && currentDocroot.length() > 0) { currentDocroot += "/"; } } if (filenameData != null) { filenameData = new StringBuffer(filenameData.toString().replaceAll("\\.\\.", "")); } if (fileDestData != null) { fileDestData = new StringBuffer(fileDestData.toString().replaceAll("\\.\\.", "")); } if (action.equalsIgnoreCase("read")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileInputStream is = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte data[] = null; boolean vfsLoaded = false; try { data = c.getVendContext().getFileAccess().getFile(c.getWorkerContext(), filenameData.toString().replaceAll("\\.\\.", ""), c.getClientContext().getMatchedHost(), c.getVendContext().getVend().getRenderExtension(c.getClientContext().getMatchedHost()), null); bos.write(data, 0, data.length); vfsLoaded = true; } catch (Exception e) { Debug.user(logTime, "Included file attempt with VFS of file '" + filenameData + "' failed: " + e); } if (data == null) { try { is = new FileInputStream(file); } catch (Exception e) { Debug.user(logTime, "Unable to render: Filename '" + currentDocroot + filenameData + "' does not exist."); return new StringBuffer(); } } if (xmlparse == null || xmlparse.equals("")) { if (data == null) { Debug.user(logTime, "Opening filename '" + currentDocroot + filenameData + "' for reading into buffer '" + varname + "'"); data = new byte[32768]; int totalBytesRead = 0; while (true) { int bytesRead; try { bytesRead = is.read(data); bos.write(data, 0, bytesRead); } catch (Exception e) { break; } if (bytesRead <= 0) { break; } totalBytesRead += bytesRead; } } byte docOutput[] = bos.toByteArray(); if (renderOutput != null && renderOutput.equalsIgnoreCase("ssp")) { String outputData = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n" + new String(FileAccess.getDefault().processServerPageData(c.getWorkerContext(), docOutput)); docOutput = outputData.getBytes(); } Debug.user(logTime, "File read complete: " + docOutput.length + " byte(s)"); if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (encoding != null && encoding.equalsIgnoreCase("url")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.URLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.URLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("xml")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.XMLEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.XMLEncode(new String(docOutput))); } } else if (encoding != null && encoding.equalsIgnoreCase("base64")) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Base64.encode(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Base64.encode(docOutput)); } } else if (encoding != null && (encoding.equalsIgnoreCase("javascript") || encoding.equalsIgnoreCase("js"))) { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, Encoder.JavascriptEncode(new String(docOutput))); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(Encoder.JavascriptEncode(new String(docOutput))); } } else { if (!varname.equals("")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, new String(docOutput)); } else { if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(new String(docOutput)); } } } else { RenderEngine engine = new RenderEngine(null); DocumentEngine docEngine = null; try { if (vfsLoaded) { ByteArrayInputStream bais = new ByteArrayInputStream(data); docEngine = new DocumentEngine(bais); } else { docEngine = new DocumentEngine(is); } } catch (Exception e) { c.setExceptionState(true, "XML parse of data read from file failed: " + e.getMessage()); } engine.setDocumentEngine(docEngine); c.addNodeSet(varname, docEngine.rootTag.thisNode); } if (is != null) { try { is.close(); } catch (Exception e) { } } is = null; if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); } else if (action.equalsIgnoreCase("write")) { try { String rootDir = filenameData.toString(); if (rootDir.lastIndexOf("/") != -1 && rootDir.lastIndexOf("/") != 0) { rootDir = rootDir.substring(0, rootDir.lastIndexOf("/")); java.io.File mkdirFile = new java.io.File(currentDocroot + rootDir); if (!mkdirFile.mkdirs()) { Debug.inform("Unable to create directory '" + currentDocroot + rootDir + "'"); } else { Debug.inform("Created directory '" + currentDocroot + rootDir + "'"); } } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); FileOutputStream fos = null; if (file == null) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Cannot write to location specified"); return new StringBuffer(); } else if (file.isDirectory()) { c.setExceptionState(true, "Unable to write to file '" + filenameData + "': Is a directory."); return new StringBuffer(); } if (filemode.equalsIgnoreCase("append")) { fos = new FileOutputStream(file, true); } else { fos = new FileOutputStream(file, false); } if (decoding != null && !decoding.equals("")) { if (decoding.equalsIgnoreCase("base64")) { try { byte contentsDecoded[] = Base64.decode(contentsData.toString().getBytes()); fos.write(contentsDecoded); } catch (Exception e) { c.setExceptionState(true, "Encoded data in <content> element does not contain valid Base64-" + "encoded data."); } } else { fos.write(contentsData.toString().getBytes()); } } else { fos.write(contentsData.toString().getBytes()); } try { fos.flush(); } catch (IOException e) { Debug.inform("Unable to flush output data: " + e.getMessage()); } fos.close(); Debug.user(logTime, "Wrote contents to filename '" + currentDocroot + filenameData + "' (length=" + contentsData.length() + ")"); } catch (IOException e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } catch (Exception e) { c.setExceptionState(true, "Unable to write to filename '" + filenameData + "': " + e.getMessage()); } } else if (action.equalsIgnoreCase("listing")) { String filenameDataString = filenameData.toString(); if (filenameDataString.equals("")) { filenameDataString = c.getClientContext().getPostVariable("current_path"); } if (filenameDataString == null) { c.setExceptionState(true, "Filename cannot be blank when listing."); return new StringBuffer(); } while (filenameDataString.endsWith("/")) { filenameDataString = filenameDataString.substring(0, filenameDataString.length() - 1); } Vector fileList = new Vector(); java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String curDirname = filenameData.toString(); String parentDirectory = null; String[] dirEntries = curDirname.split("/"); int numSlashes = 0; for (int i = 0; i < curDirname.length(); i++) { if (curDirname.toString().charAt(i) == '/') { numSlashes++; } } parentDirectory = "/"; if (numSlashes > 1) { for (int i = 0; i < (dirEntries.length - 1); i++) { if (dirEntries[i] != null && !dirEntries[i].equals("")) { parentDirectory += dirEntries[i] + "/"; } } } if (parentDirectory.length() > 1 && parentDirectory.endsWith("/")) { parentDirectory = parentDirectory.substring(0, parentDirectory.length() - 1); } if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_JAR) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); int depth = 0; for (int i = 0; i < filenameData.toString().length(); i++) { if (filenameData.toString().charAt(i) == '/') { depth++; } } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(list, new ZipSorterAscending()); } else { Arrays.sort(list, new ZipSorterDescending()); } for (int i = 0; i < list.length; i++) { ZipEntry zEntry = (ZipEntry) list[i]; String zipFile = filenameData.toString() + "/" + zEntry.getName(); String displayFilename = zipFile.replaceFirst(filenameData.toString(), ""); int curDepth = 0; if (zipFile.equalsIgnoreCase(".acl") || zipFile.equalsIgnoreCase("access.list") || zipFile.equalsIgnoreCase("application.inc") || zipFile.equalsIgnoreCase("global.inc") || zipFile.indexOf("/.proc") != -1 || zipFile.indexOf("/procedures") != -1) { continue; } for (int x = 0; x < displayFilename.length(); x++) { if (displayFilename.charAt(x) == '/') { curDepth++; } } if (zipFile.startsWith(filenameData.toString())) { String fileLength = "" + zEntry.getSize(); String fileType = "file"; if (curDepth == depth) { if (zEntry.isDirectory()) { fileType = "directory"; } else { fileType = "file"; } String fileMode = "read-only"; String fileTime = Long.toString(zEntry.getTime()); buffer.append(" <file name=\""); buffer.append(displayFilename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + displayFilename + ")(time)", false, fileTime); } } else { if (curDepth == depth) { fileList.add(zipFile); } } } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else if (c.getVendContext() != null && c.getVendContext().getFileAccess() != null && c.getVendContext().getFileAccess().getVFSType(filenameData.toString(), c.getClientContext().getMatchedHost()) == FileAccess.TYPE_FS) { Vector listFiles = c.getVendContext().getFileAccess().listFiles(filenameData.toString(), c.getClientContext().getMatchedHost()); Object[] list = listFiles.toArray(); java.io.File[] filesorted = new java.io.File[list.length]; for (int i = 0; i < list.length; i++) { filesorted[i] = (java.io.File) list[i]; } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(filesorted, new FileSorterAscending()); } else { Arrays.sort(filesorted, new FileSorterDescending()); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < filesorted.length; i++) { java.io.File zEntry = filesorted[i]; String filename = filenameData.toString() + "/" + zEntry.getName(); if (filename.equalsIgnoreCase(".acl") || filename.equalsIgnoreCase("access.list") || filename.equalsIgnoreCase("application.inc") || filename.equalsIgnoreCase("global.inc") || filename.indexOf("/.proc") != -1 || filename.indexOf("/procedures") != -1) { continue; } String displayFilename = filename.replaceFirst(filenameData.toString(), ""); String fileLength = "" + zEntry.length(); String fileType = "file"; if (zEntry.isDirectory()) { fileType = "directory"; } else if (zEntry.isFile()) { fileType = "file"; } else if (zEntry.isHidden()) { fileType = "hidden"; } else if (zEntry.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (zEntry.canRead() && !zEntry.canWrite()) { fileMode = "read-only"; } else if (!zEntry.canRead() && zEntry.canWrite()) { fileMode = "write-only"; } else if (zEntry.canRead() && zEntry.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(zEntry.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(filename); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(zEntry); } c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + filename + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } else { String[] fileStringList = null; if (!filter.equals("")) { fileStringList = file.list(new ListFilter(filter)); } else { fileStringList = file.list(); } if (sort.equalsIgnoreCase("asc")) { Arrays.sort(fileStringList, new StringSorterAscending()); } else { Arrays.sort(fileStringList, new StringSorterDescending()); } if (fileStringList == null) { buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\"/>\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); } else { c.getVariableContainer().setVector(varname, fileList); } return new StringBuffer(); } else { Debug.user(logTime, "Directory '" + currentDocroot + filenameData + "' returns " + fileStringList.length + " entry(ies)"); } buffer = new StringBuffer(); buffer.append("<listing filter=\""); buffer.append(filter); buffer.append("\" path=\""); buffer.append(filenameData); if (parentDirectory != null) { buffer.append("\" parent=\""); buffer.append(parentDirectory); } buffer.append("\">\n"); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(filter)", false, filter); c.getVariableContainer().setVariable(c, varname + "(fileinfo)(path)", false, filenameData); if (parentDirectory != null) { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, parentDirectory); } else { c.getVariableContainer().setVariable(c, varname + "(fileinfo)(parent)", false, "/"); } for (int i = 0; i < fileStringList.length; i++) { file = new java.io.File(currentDocroot + filenameData.toString() + "/" + fileStringList[i]); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } else if (file.isAbsolute()) { fileType = "absolute"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (xmlOutput.equalsIgnoreCase("true")) { buffer.append(" <file name=\""); buffer.append(fileStringList[i]); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); } else { fileList.add(fileStringList[i]); } c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(length)", false, "" + fileLength); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(type)", false, fileType); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(mode)", false, fileMode); c.getVariableContainer().setVariable(c, varname + "(" + fileStringList[i] + ")(time)", false, fileTime); } buffer.append("</listing>"); if (xmlOutput.equalsIgnoreCase("true")) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, buffer.toString()); return new StringBuffer(); } c.getVariableContainer().setVector(varname, fileList); } } else if (action.equalsIgnoreCase("delete")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.isDirectory()) { boolean success = deleteDir(new java.io.File(currentDocroot + filenameData.toString())); if (!success) { c.setExceptionState(true, "Unable to delete '" + currentDocroot + filenameData + "'"); } } else { String filenamePattern = null; if (filenameData.toString().indexOf("/") != -1) { filenamePattern = filenameData.toString().substring(filenameData.toString().lastIndexOf("/") + 1); } String filenameDirectory = currentDocroot; if (filenameData.toString().indexOf("/") != -1) { filenameDirectory += filenameData.substring(0, filenameData.toString().lastIndexOf("/")); } String[] fileStringList = null; file = new java.io.File(filenameDirectory); fileStringList = file.list(new ListFilter(filenamePattern)); for (int i = 0; i < fileStringList.length; i++) { (new java.io.File(filenameDirectory + "/" + fileStringList[i])).delete(); } } } else if (action.equalsIgnoreCase("rename") || action.equalsIgnoreCase("move")) { if (fileDestData.equals("")) { c.getVariableContainer().setVariable(varname + "-result", filenameData + ": File operation failed: No destination filename given."); return new StringBuffer(); } java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); boolean success = file.renameTo(new java.io.File(currentDocroot + fileDestData.toString(), file.getName())); if (!success) { c.setExceptionState(true, "Unable to rename '" + currentDocroot + filenameData + "' to '" + currentDocroot + fileDestData + "'"); } } else if (action.equalsIgnoreCase("copy")) { if (fileDestData.equals("")) { c.setExceptionState(true, "File copy operation failed for file '" + filenameData + "': No destination file specified."); return new StringBuffer(); } FileChannel srcChannel; FileChannel destChannel; String filename = null; filename = currentDocroot + filenameData.toString(); if (vartype != null && vartype.equalsIgnoreCase("file")) { if (useFilename.indexOf("/") != -1) { useFilename = useFilename.substring(useFilename.lastIndexOf("/") + 1); } filename = c.getVariableContainer().getFileVariable(useFilename); } try { Debug.debug("Copying from file '" + filename + "' to '" + fileDestData.toString() + "'"); srcChannel = new FileInputStream(filename).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' failed to read: " + e.getMessage()); return new StringBuffer(); } try { destChannel = new FileOutputStream(currentDocroot + fileDestData.toString()).getChannel(); } catch (IOException e) { c.setExceptionState(true, "Filecopy to '" + fileDestData + "' failed to write: " + e.getMessage()); return new StringBuffer(); } try { destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", filenameData + " copy to " + fileDestData + ": File copy succeeded."); } else { return new StringBuffer("true"); } } catch (IOException e) { c.setExceptionState(true, "Filecopy from '" + filenameData + "' to '" + fileDestData + "' failed: " + e.getMessage()); } } else if (action.equalsIgnoreCase("exists")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.exists()) { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "true"); } else { return new StringBuffer("true"); } } else { if (varname != null) { if (c.isProtectedVariable(varname)) { c.setExceptionState(true, "Attempted to modify a read-only variable '" + varname + "'"); return new StringBuffer(); } c.getVariableContainer().setVariable(varname, "false"); } else { return new StringBuffer("false"); } } } else if (action.equalsIgnoreCase("mkdir")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); if (file.mkdirs()) { if (varname != null) { c.getVariableContainer().setVariable(varname + "-result", "created"); } else { return new StringBuffer("true"); } } else { c.setExceptionState(true, "Unable to create directory '" + filenameData + "'"); } } else if (action.equalsIgnoreCase("info")) { java.io.File file = new java.io.File(currentDocroot + filenameData.toString()); String fileLength = Long.toString(file.length()); String fileType = "file"; if (file.isAbsolute()) { fileType = "absolute"; } else if (file.isDirectory()) { fileType = "directory"; } else if (file.isFile()) { fileType = "file"; } else if (file.isHidden()) { fileType = "hidden"; } String fileMode = "read-only"; if (file.canRead() && !file.canWrite()) { fileMode = "read-only"; } else if (!file.canRead() && file.canWrite()) { fileMode = "write-only"; } else if (file.canRead() && file.canWrite()) { fileMode = "read/write"; } String fileTime = Long.toString(file.lastModified()); if (varname != null && !varname.equals("")) { c.getVariableContainer().setVariable(varname + ".length", fileLength); c.getVariableContainer().setVariable(varname + ".type", fileType); c.getVariableContainer().setVariable(varname + ".mode", fileMode); c.getVariableContainer().setVariable(varname + ".modtime", fileTime); } else { buffer = new StringBuffer(); buffer.append("<file name=\""); buffer.append(filenameData); buffer.append("\" length=\""); buffer.append(fileLength); buffer.append("\" type=\""); buffer.append(fileType); buffer.append("\" mode=\""); buffer.append(fileMode); buffer.append("\" modtime=\""); buffer.append(fileTime); buffer.append("\"/>\n"); return buffer; } } if (callProc != null && !callProc.equals("")) { Call call = new Call(); call.callProcedure(c, null, null, callProc, null); } return new StringBuffer(); }
|
00
|
Code Sample 1:
public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null; InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; String transferEncoding = null; parts.add(new PartBase(c.getName(), c.getContentType(), charSet, transferEncoding) { @Override protected long lengthOfData() throws IOException { return c.getSize(); } @Override protected void sendData(OutputStream out) throws IOException { Reader reader = c.getReader(); try { IOUtils.copy(reader, out); } finally { reader.close(); } } }); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity(new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method.releaseConnection(); method = null; if (is != null) { is.close(); } if ((tries < 1)) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } try { int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } }
Code Sample 2:
public void create(String oid, Serializable obj) throws PersisterException { String key = getLock(oid); if (key != null) { throw new PersisterException("Object already exists: OID = " + oid); } Connection conn = null; PreparedStatement ps = null; try { byte[] data = serialize(obj); conn = _ds.getConnection(); conn.setAutoCommit(true); ps = conn.prepareStatement("insert into " + _table_name + "(" + _oid_col + "," + _data_col + "," + _ts_col + ") values (?,?,?)"); ps.setString(1, oid); ps.setBinaryStream(2, new ByteArrayInputStream(data), data.length); ps.setLong(3, System.currentTimeMillis()); ps.executeUpdate(); } catch (Throwable th) { if (conn != null) { try { conn.rollback(); } catch (Throwable th2) { } } throw new PersisterException("Failed to create object: OID = " + oid, th); } finally { if (ps != null) { try { ps.close(); } catch (Throwable th) { } } if (conn != null) { try { conn.close(); } catch (Throwable th) { } } } }
|
00
|
Code Sample 1:
public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = "Schema created by object [" + objectControlller + "] with boui [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (\"SCHEMA\",OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } }
Code Sample 2:
private void scanURL(String packagePath, Collection<String> componentClassNames, URL url) throws IOException { URLConnection connection = url.openConnection(); JarFile jarFile; if (connection instanceof JarURLConnection) { jarFile = ((JarURLConnection) connection).getJarFile(); } else { jarFile = getAlternativeJarFile(url); } if (jarFile != null) { scanJarFile(packagePath, componentClassNames, jarFile); } else if (supportsDirStream(url)) { Stack<Queued> queue = new Stack<Queued>(); queue.push(new Queued(url, packagePath)); while (!queue.isEmpty()) { Queued queued = queue.pop(); scanDirStream(queued.packagePath, queued.packageURL, componentClassNames, queue); } } else { String packageName = packagePath.replace("/", "."); if (packageName.endsWith(".")) { packageName = packageName.substring(0, packageName.length() - 1); } scanDir(packageName, new File(url.getFile()), componentClassNames); } }
|
00
|
Code Sample 1:
private static void replaceEntityMappings(File signserverearpath, File entityMappingXML) throws ZipException, IOException { ZipInputStream earFile = new ZipInputStream(new FileInputStream(signserverearpath)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream tempZip = new ZipOutputStream(baos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("signserver-ejb.jar")) { content = replaceEntityMappings(content, entityMappingXML); next = new ZipEntry("signserver-ejb.jar"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); FileOutputStream fos = new FileOutputStream(signserverearpath); fos.write(baos.toByteArray()); fos.close(); }
Code Sample 2:
public String move(Integer param) { LOG.debug("move " + param); StringBuffer ret = new StringBuffer(); try { URL url = new URL("http://" + host + "/decoder_control.cgi?command=" + param + "&user=" + user + "&pwd=" + password); URLConnection con = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { ret.append(inputLine); } in.close(); } catch (Exception e) { logException(e); connect(host, user, password); } return ret.toString(); }
|
00
|
Code Sample 1:
private void packageDestZip(File tmpFile) throws FileNotFoundException, IOException { log("Creating launch profile package " + destfile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destfile))); ZipEntry e = new ZipEntry(RESOURCE_JAR_FILENAME); e.setMethod(ZipEntry.STORED); e.setSize(tmpFile.length()); e.setCompressedSize(tmpFile.length()); e.setCrc(calcChecksum(tmpFile, new CRC32())); out.putNextEntry(e); InputStream in = new BufferedInputStream(new FileInputStream(tmpFile)); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.closeEntry(); out.finish(); out.close(); }
Code Sample 2:
@Override public String getHash(String text) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); }
|
11
|
Code Sample 1:
public static boolean installMetricsCfg(Db db, String xmlFileName) throws Exception { String xmlText = FileHelper.asString(xmlFileName); Bundle bundle = new Bundle(); loadMetricsCfg(bundle, xmlFileName, xmlText); try { db.begin(); PreparedStatement psExists = db.prepareStatement("SELECT e_bundle_id, xml_decl_path, xml_text FROM sdw.e_bundle WHERE xml_decl_path = ?;"); psExists.setString(1, xmlFileName); ResultSet rsExists = db.executeQuery(psExists); if (rsExists.next()) { db.rollback(); return false; } PreparedStatement psId = db.prepareStatement("SELECT currval('sdw.e_bundle_serial');"); PreparedStatement psAdd = db.prepareStatement("INSERT INTO sdw.e_bundle (xml_decl_path, xml_text, sdw_major_version, sdw_minor_version, file_major_version, file_minor_version) VALUES (?, ?, ?, ?, ?, ?);"); psAdd.setString(1, xmlFileName); psAdd.setString(2, xmlText); FileInformation fi = bundle.getSingleFileInformation(); if (!xmlFileName.equals(fi.filename)) throw new IllegalStateException("FileInformation bad for " + xmlFileName); psAdd.setInt(3, Globals.SDW_MAJOR_VER); psAdd.setInt(4, Globals.SDW_MINOR_VER); psAdd.setInt(5, fi.majorVer); psAdd.setInt(6, fi.minorVer); if (1 != db.executeUpdate(psAdd)) { throw new IllegalStateException("Could not add " + xmlFileName); } int bundleId = DbHelper.getIntKey(psId); PreparedStatement psGroupId = db.prepareStatement("SELECT currval('sdw.e_metric_group_serial');"); PreparedStatement psAddGroup = db.prepareStatement("INSERT INTO sdw.e_metric_group (bundle_id, metric_group_name) VALUES (?, ?);"); psAddGroup.setInt(1, bundleId); PreparedStatement psMetricId = db.prepareStatement("SELECT currval('sdw.e_metric_name_serial');"); PreparedStatement psAddMetric = db.prepareStatement("INSERT INTO sdw.e_metric_name (bundle_id, metric_name) VALUES (?, ?);"); psAddMetric.setInt(1, bundleId); PreparedStatement psAddGroup2Metric = db.prepareStatement("INSERT INTO sdw.e_metric_groups (metric_name_id, metric_group_id) VALUES (?, ?);"); Iterator<MetricGroup> i = bundle.getAllMetricGroups(); while (i.hasNext()) { MetricGroup grp = i.next(); psAddGroup.setString(2, grp.groupName); if (1 != db.executeUpdate(psAddGroup)) throw new IllegalStateException("Could not add group " + grp.groupName + " from " + xmlFileName); int groupId = DbHelper.getIntKey(psGroupId); psAddGroup2Metric.setInt(2, groupId); Iterator<String> j = grp.getAllMetricNames(); while (j.hasNext()) { String metricName = j.next(); psAddMetric.setString(2, metricName); if (1 != db.executeUpdate(psAddMetric)) throw new IllegalStateException("Could not add " + metricName + " from " + xmlFileName); int metricId = DbHelper.getIntKey(psMetricId); psAddGroup2Metric.setInt(1, metricId); if (1 != db.executeUpdate(psAddGroup2Metric)) throw new IllegalStateException("Could not add group " + grp.groupName + " -> " + metricName + " from " + xmlFileName); } } return true; } catch (Exception e) { db.rollback(); throw e; } finally { db.commitUnless(); } }
Code Sample 2:
public static boolean insert(final Cargo cargo) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into cargo (nome) values (?)"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
|
00
|
Code Sample 1:
public static void copyFile(File source, File destination) throws IOException { if (!source.isFile()) { throw new IOException(source + " is not a file."); } if (destination.exists()) { throw new IOException("Destination file " + destination + " is already exist."); } FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(destination).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { inChannel.close(); outChannel.close(); } }
Code Sample 2:
@Override public void parse() throws IOException { URL url = new URL(getDataUrl()); URLConnection con = url.openConnection(); BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream())); String s = bStream.readLine(); String[] tokens = s.split("</html>"); tokens = tokens[1].split("<br>"); for (String sToken : tokens) { String[] sTokens = sToken.split(";"); CurrencyUnit unit = new CurrencyUnit(sTokens[4], Float.valueOf(sTokens[9]), Integer.valueOf(sTokens[5])); this.set.add(unit); } }
|
11
|
Code Sample 1:
@Test public void testCopy_inputStreamToWriter_Encoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, "UTF8"); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF8").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); }
Code Sample 2:
public static DownloadedContent downloadContent(final InputStream is) throws IOException { if (is == null) { return new DownloadedContent.InMemory(new byte[] {}); } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int nbRead; try { while ((nbRead = is.read(buffer)) != -1) { bos.write(buffer, 0, nbRead); if (bos.size() > MAX_IN_MEMORY) { final File file = File.createTempFile("htmlunit", ".tmp"); file.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(file); bos.writeTo(fos); IOUtils.copyLarge(is, fos); fos.close(); return new DownloadedContent.OnFile(file); } } } finally { IOUtils.closeQuietly(is); } return new DownloadedContent.InMemory(bos.toByteArray()); }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws EnhancedException { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (Exception e) { throw new EnhancedException("Could not copy file " + in.getAbsolutePath() + " to " + out.getAbsolutePath() + ".", e); } }
Code Sample 2:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath, String myImagesBehaviour) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(directoryPath + "images.xml"); SAXBuilder builder = new SAXBuilder(false); try { Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); int i = 0; TIGDataBase.activateTransactions(); while (j.hasNext() && !stop && !cancel) { current = i; i++; Element image = (Element) j.next(); String name = image.getAttributeValue("name"); List categories = image.getChildren("category"); Iterator k = categories.iterator(); if (exists(list, name)) { String pathSrc = directoryPath.concat(name); String pathDst = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase() + File.separator; String folder = System.getProperty("user.dir") + File.separator + "images" + File.separator + name.substring(0, 1).toUpperCase(); if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.REPLACE_IMAGES"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); TIGDataBase.deleteAsociatedOfImage(idImage); } pathDst = pathDst.concat(name); } if (myImagesBehaviour.equals(TLanguage.getString("TIGImportDBDialog.ADD_IMAGES"))) { Vector aux = new Vector(); aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.'))); int fileCount = 0; if (aux.size() != 0) { while (aux.size() != 0) { fileCount++; aux = TIGDataBase.imageSearchByName(name.substring(0, name.lastIndexOf('.')) + "_" + fileCount); } pathDst = pathDst + name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); name = name.substring(0, name.lastIndexOf('.')) + '_' + fileCount + name.substring(name.lastIndexOf('.'), name.length()); } else { pathDst = pathDst.concat(name); } } String pathThumbnail = (pathDst.substring(0, pathDst.lastIndexOf("."))).concat("_th.jpg"); File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertImageDB(name.substring(0, name.lastIndexOf('.')), name); int idImage = TIGDataBase.imageKeySearchName(name.substring(0, name.lastIndexOf('.'))); while (k.hasNext()) { Element category = (Element) k.next(); int idCategory = TIGDataBase.insertConceptDB(category.getValue()); TIGDataBase.insertAsociatedDB(idCategory, idImage); } } else { errorImages = errorImages + System.getProperty("line.separator") + name; } } TIGDataBase.executeQueries(); current = lengthOfTask; } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } }
Code Sample 2:
public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } }
|
00
|
Code Sample 1:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; }
Code Sample 2:
@Override public void copyTo(ManagedFile other) throws ManagedIOException { try { if (other.getType() == ManagedFileType.FILE) { IOUtils.copy(this.getContent().getInputStream(), other.getContent().getOutputStream()); } else { ManagedFile newFile = other.retrive(this.getPath()); newFile.createFile(); IOUtils.copy(this.getContent().getInputStream(), newFile.getContent().getOutputStream()); } } catch (IOException ioe) { throw ManagedIOException.manage(ioe); } }
|
00
|
Code Sample 1:
private static boolean initLOG4JProperties(String homeDir) { String Log4jURL = homeDir + LOG4J_URL; try { URL log4jurl = getURL(Log4jURL); InputStream inStreamLog4j = log4jurl.openStream(); Properties propertiesLog4j = new Properties(); try { propertiesLog4j.load(inStreamLog4j); PropertyConfigurator.configure(propertiesLog4j); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { logger.info("Failed to initialize LOG4J with properties file."); return false; } return true; }
Code Sample 2:
public static String validateAuthTicketAndGetSessionId(ServletRequest request, String servicekey) { String loginapp = SSOFilter.getLoginapp(); String authticket = request.getParameter("authticket"); String u = SSOUtil.addParameter(loginapp + "/api/validateauthticket", "authticket", authticket); u = SSOUtil.addParameter(u, "servicekey", servicekey); String sessionid = null; try { URL url = new URL(u); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { sessionid = line.trim(); } reader.close(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } if ("error".equals(sessionid)) { return null; } return sessionid; }
|
00
|
Code Sample 1:
public void update() { try { String passwordMD5 = new String(); if (this.password != null && this.password.length() > 0) { MessageDigest md = MessageDigest.getInstance("md5"); md.update(this.password.getBytes()); byte[] digest = md.digest(); for (int i = 0; i < digest.length; i++) { passwordMD5 += Integer.toHexString((digest[i] >> 4) & 0xf); passwordMD5 += Integer.toHexString((digest[i] & 0xf)); } } this.authCode = new String(Base64Encoder.encode(new String(this.username + ";" + passwordMD5).getBytes())); } catch (Throwable throwable) { throwable.printStackTrace(); } }
Code Sample 2:
public static Image getImage(URL url) throws IOException { InputStream is = null; try { is = url.openStream(); Image img = getImage(is); img.setUrl(url); return img; } finally { if (is != null) { is.close(); } } }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { logger.error(Logger.SECURITY_FAILURE, "Problem encoding file to file", exc); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static boolean encodeFileToFile(final String infile, final String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); final byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (final java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (final Exception exc) { } try { out.close(); } catch (final Exception exc) { } } return success; }
|
00
|
Code Sample 1:
private void readCard() { try { final String urlString = createURLStringExistRESTGetXQuery("//scheda[cata = \"" + cata + "\"]"); InputStream inputStream = new URL(urlString).openStream(); uiSchedaXml.read(inputStream); inputStream.close(); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } }
Code Sample 2:
private void preprocessImages(GeoImage[] detailedImages) throws IOException { for (int i = 0; i < detailedImages.length; i++) { BufferedImage img = loadImage(detailedImages[i].getPath()); detailedImages[i].setLatDim(img.getHeight()); detailedImages[i].setLonDim(img.getWidth()); freeImage(img); String fileName = detailedImages[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("filename " + tmp); File worldFile = new File(tmp); if (!worldFile.exists()) { System.out.println("Rez: Could not find file: " + tmp); debug("Rez: Could not find directory: " + tmp); throw new IOException("File not Found"); } BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLonSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLonExtent(detailedImages[i].getLonSpacing() * ((double) detailedImages[i].getLonDim() - 1d)); System.out.println("setLonExtent " + detailedImages[i].getLonExtent()); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("skip line: " + line); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLatSpacing(Double.valueOf(tokenizer.nextToken()).doubleValue()); detailedImages[i].setLatExtent(detailedImages[i].getLatSpacing() * ((double) detailedImages[i].getLatDim() - 1d)); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); detailedImages[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); detailedImages[i].setPath(tmp); DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } else { System.out.println("Rez: ERROR: World file for image is null"); } } }
|
11
|
Code Sample 1:
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); String forw = null; try { int maxUploadSize = 50000000; MultipartRequest multi = new MultipartRequest(request, ".", maxUploadSize); String descrizione = multi.getParameter("text"); File myFile = multi.getFile("uploadfile"); String filePath = multi.getOriginalFileName("uploadfile"); String path = "C:\\files\\"; try { FileInputStream inStream = new FileInputStream(myFile); FileOutputStream outStream = new FileOutputStream(path + myFile.getName()); while (inStream.available() > 0) { outStream.write(inStream.read()); } inStream.close(); outStream.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } forw = "../sendDoc.jsp"; request.setAttribute("contentType", context.getMimeType(path + myFile.getName())); request.setAttribute("text", descrizione); request.setAttribute("path", path + myFile.getName()); request.setAttribute("size", Long.toString(myFile.length()) + " Bytes"); RequestDispatcher rd = request.getRequestDispatcher(forw); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public boolean chequearMarca(int a, int m, int d) { boolean existe = false; try { cantidadArchivos = obtenerCantidad() + 1; String filenametxt = ""; String filenamezip = ""; int dia = 0; int mes = 0; int ano = 0; for (int i = 1; i < cantidadArchivos; i++) { filenamezip = "recordatorio" + i + ".zip"; filenametxt = "recordatorio" + i + ".txt"; BufferedOutputStream dest = null; BufferedInputStream is = null; ZipEntry entry; ZipFile zipfile = new ZipFile(filenamezip); Enumeration e = zipfile.entries(); while (e.hasMoreElements()) { entry = (ZipEntry) e.nextElement(); is = new BufferedInputStream(zipfile.getInputStream(entry)); int count; byte data[] = new byte[buffer]; FileOutputStream fos = new FileOutputStream(entry.getName()); dest = new BufferedOutputStream(fos, buffer); while ((count = is.read(data, 0, buffer)) != -1) dest.write(data, 0, count); dest.flush(); dest.close(); is.close(); } DataInputStream input = new DataInputStream(new FileInputStream(filenametxt)); dia = Integer.parseInt(input.readLine()); mes = Integer.parseInt(input.readLine()); ano = Integer.parseInt(input.readLine()); if (ano == a && mes == m && dia == d) existe = true; input.close(); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Error en: " + e.toString(), "Error", JOptionPane.ERROR_MESSAGE); } return (existe); }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public void copyTo(Bean bean, OutputStream out, int offset, int length) throws Exception { BeanInfo beanInfo = getBeanInfo(bean.getClass()); validate(bean, beanInfo, "copyTo"); if (blobCache != null && length < MAX_BLOB_CACHE_LENGHT) { byte[] bytes = null; synchronized (this) { String key = makeUniqueKey(bean, beanInfo, offset, length); if (blobCache.contains(key)) bytes = (byte[]) blobCache.get(key); else blobCache.put(key, bytes = toByteArray(bean, offset, length, beanInfo)); } InputStream in = new ByteArrayInputStream(bytes); IOUtils.copy(in, out); in.close(); } else { jdbcManager.queryScript(beanInfo.getBlobInfo(jdbcManager.getDb()).getReadScript(), bean, new JdbcOutputStreamRowMapper(out, offset, length)); } }
|
00
|
Code Sample 1:
private static String fetchUrl(String url, boolean keepLineEnds) throws IOException, MalformedURLException { URLConnection destConnection = (new URL(url)).openConnection(); BufferedReader br; String inputLine; StringBuffer doc = new StringBuffer(); String contentEncoding; destConnection.setRequestProperty("Accept-Encoding", "gzip"); if (proxyAuth != null) destConnection.setRequestProperty("Proxy-Authorization", proxyAuth); destConnection.connect(); contentEncoding = destConnection.getContentEncoding(); if ((contentEncoding != null) && contentEncoding.equals("gzip")) { br = new BufferedReader(new InputStreamReader(new GZIPInputStream(destConnection.getInputStream()))); } else { br = new BufferedReader(new InputStreamReader(destConnection.getInputStream())); } while ((inputLine = br.readLine()) != null) { if (keepLineEnds) doc.append(inputLine + "\n"); else doc.append(inputLine); } br.close(); return doc.toString(); }
Code Sample 2:
public static synchronized String getMD5_Base64(String input) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(input.getBytes("UTF-8")); } catch (java.io.UnsupportedEncodingException ex) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] rawData = msgDigest.digest(); byte[] encoded = Base64.encodeBase64(rawData); String retValue = new String(encoded); return retValue; }
|
11
|
Code Sample 1:
@Override public String execute() throws Exception { SystemContext sc = getSystemContext(); if (sc.getExpireTime() == -1) { return LOGIN; } else if (upload != null) { try { Enterprise e = LicenceUtils.get(upload); sc.setEnterpriseName(e.getEnterpriseName()); sc.setExpireTime(e.getExpireTime()); String webPath = ServletActionContext.getServletContext().getRealPath("/"); File desFile = new File(webPath, LicenceUtils.LICENCE_FILE_NAME); FileChannel sourceChannel = new FileInputStream(upload).getChannel(); FileChannel destinationChannel = new FileOutputStream(desFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); return LOGIN; } catch (Exception e) { } } return "license"; }
Code Sample 2:
public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static String getMD5HashFromString(String message) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(message.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
Code Sample 2:
private static FileEntry writeEntry(Zip64File zip64File, FileEntry targetPath, File toWrite, boolean compress) { InputStream in = null; EntryOutputStream out = null; processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath.getName(), toWrite), compress); try { if (!compress) { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_STORED, getFileDate(toWrite)); } else { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_DEFLATED, getFileDate(toWrite)); } if (!targetPath.isDirectory()) { in = new FileInputStream(toWrite); IOUtils.copyLarge(in, out); in.close(); } out.flush(); out.close(); if (targetPath.isDirectory()) { log.info("[createZip] Written folder entry to zip: " + targetPath.getName()); } else { log.info("[createZip] Written file entry to zip: " + targetPath.getName()); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ZipException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return targetPath; }
|
00
|
Code Sample 1:
public String getImageURL(String text) { String imgURL = ""; try { URL url = new URL("http://images.search.yahoo.com/search/images?p=" + URLEncoder.encode(text)); URLConnection connection = url.openConnection(); DataInputStream in = new DataInputStream(connection.getInputStream()); String line; Pattern imgPattern = Pattern.compile("isrc=\"([^\"]*)\""); while ((line = in.readLine()) != null) { Matcher match = imgPattern.matcher(line); if (match.find()) { imgURL = match.group(1); break; } } in.close(); } catch (Exception e) { } return imgURL; }
Code Sample 2:
private void impurlActionPerformed(java.awt.event.ActionEvent evt) { try { String prevurl = Prefs.getPref(PrefName.LASTIMPURL); String urlst = JOptionPane.showInputDialog(Resource.getResourceString("enturl"), prevurl); if (urlst == null || urlst.equals("")) return; Prefs.putPref(PrefName.LASTIMPURL, urlst); URL url = new URL(urlst); impURLCommon(urlst, url.openStream()); } catch (Exception e) { Errmsg.errmsg(e); } }
|
11
|
Code Sample 1:
public static void copyFile(String source, String dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(new File(source)).getChannel(); out = new FileOutputStream(new File(dest)).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
Code Sample 2:
private List<Document> storeDocuments(List<Document> documents) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); List<Document> newDocuments = new ArrayList<Document>(); try { session.beginTransaction(); Preference preference = new PreferenceModel(); preference = (Preference) preference.doList(preference).get(0); Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); if (documents != null && !documents.isEmpty()) { for (Iterator<Document> iter = documents.iterator(); iter.hasNext(); ) { Document document = iter.next(); if (AppConstants.STATUS_ACTIVE.equals(document.getStatus())) { try { document = (Document) preAdd(document, getParams()); File fileIn = new File(preference.getScanLocation() + File.separator + document.getName()); File fileOut = new File(preference.getStoreLocation() + File.separator + document.getName()); FileInputStream in = new FileInputStream(fileIn); FileOutputStream out = new FileOutputStream(fileOut); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); document.doAdd(document); boolean isDeleted = fileIn.delete(); System.out.println("Deleted scan folder file: " + document.getName() + ":" + isDeleted); if (isDeleted) { document.setStatus(AppConstants.STATUS_PROCESSING); int uploadCount = 0; if (document.getUploadCount() != null) { uploadCount = document.getUploadCount(); } uploadCount++; document.setUploadCount(uploadCount); newDocuments.add(document); } } catch (Exception add_ex) { add_ex.printStackTrace(); } } else if (AppConstants.STATUS_PROCESSING.equals(document.getStatus())) { int uploadCount = document.getUploadCount(); if (uploadCount < 5) { uploadCount++; document.setUploadCount(uploadCount); System.out.println("increase upload count: " + document.getName() + ":" + uploadCount); newDocuments.add(document); } else { System.out.println("delete from documents list: " + document.getName()); } } else if (AppConstants.STATUS_INACTIVE.equals(document.getStatus())) { document.setFixFlag(AppConstants.FLAG_NO); newDocuments.add(document); } } } } catch (Exception ex) { ex.printStackTrace(); } return newDocuments; }
|
11
|
Code Sample 1:
public void createZipCopy(IUIContext ui, final String zipFileName, final File[] filesToZip, final FilenameFilter fileFilter, Timestamp timestamp) { TestCase.assertNotNull(ui); TestCase.assertNotNull(zipFileName); TestCase.assertFalse(zipFileName.trim().length() == 0); TestCase.assertNotNull(filesToZip); TestCase.assertNotNull(timestamp); String nameCopy = zipFileName; if (nameCopy.endsWith(".zip")) { nameCopy = nameCopy.substring(0, zipFileName.length() - 4); } nameCopy = nameCopy + "_" + timestamp.toString() + ".zip"; final String finalZip = nameCopy; IWorkspaceRunnable noResourceChangedEventsRunner = new IWorkspaceRunnable() { public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } }; try { IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.run(noResourceChangedEventsRunner, workspace.getRoot(), IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException ce) { PlatformActivator.logException(ce); } }
Code Sample 2:
protected static void writeFileToStream(FileWrapper file, String filename, ZipOutputStream zipStream) throws CausedIOException, IOException { InputStream in; try { in = file.getInputStream(); } catch (Exception e) { throw new CausedIOException("Could not obtain InputStream for " + filename, e); } try { IOUtils.copy(in, zipStream); } finally { IOUtils.closeQuietly(in); } }
|
00
|
Code Sample 1:
private static void ensure(File pFile) throws IOException { if (!pFile.exists()) { FileOutputStream fos = new FileOutputStream(pFile); String resourceName = "/" + pFile.getName(); InputStream is = BaseTest.class.getResourceAsStream(resourceName); Assert.assertNotNull(String.format("Could not find resource [%s].", resourceName), is); IOUtils.copy(is, fos); fos.close(); } }
Code Sample 2:
private static InputSource getInputSourceFromURI(String uri, String username, String password) throws IOException, ProtocolException, UnsupportedEncodingException { URL wsdlurl = null; try { wsdlurl = new URL(uri); } catch (MalformedURLException e) { return new InputSource(uri); } if (username == null && wsdlurl.getUserInfo() == null) { return new InputSource(uri); } if (!wsdlurl.getProtocol().startsWith("http")) { return new InputSource(uri); } URLConnection connection = wsdlurl.openConnection(); if (!(connection instanceof HttpURLConnection)) { return new InputSource(uri); } HttpURLConnection uconn = (HttpURLConnection) connection; String userinfo = wsdlurl.getUserInfo(); uconn.setRequestMethod("GET"); uconn.setAllowUserInteraction(false); uconn.setDefaultUseCaches(false); uconn.setDoInput(true); uconn.setDoOutput(false); uconn.setInstanceFollowRedirects(true); uconn.setUseCaches(false); String auth = null; if (userinfo != null) { auth = userinfo; } else if (username != null) { auth = (password == null) ? username : username + ":" + password; } if (auth != null) { uconn.setRequestProperty("Authorization", "Basic " + base64encode(auth.getBytes(httpAuthCharEncoding))); } uconn.connect(); return new InputSource(uconn.getInputStream()); }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
@Override public void loadData() { try { String url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=11&f=2099&g=d&ignore=.csv"; URLConnection conn = (new URL(url)).openConnection(); conn.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); String str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double open = Double.parseDouble(split[1]); final double high = Double.parseDouble(split[2]); final double low = Double.parseDouble(split[3]); final double close = Double.parseDouble(split[4]); final int volume = Integer.parseInt(split[5]); final double adjClose = Double.parseDouble(split[6]); final HistoricalPrice price = new HistoricalPrice(date, open, high, low, close, volume, adjClose); historicalPrices.add(price); } in.close(); url = "http://ichart.finance.yahoo.com/table.csv?s=" + symbol + "&a=00&b=2&c=1962&d=11&e=17&f=2008&g=v&ignore=.csv"; conn = (new URL(url)).openConnection(); conn.connect(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); in.readLine(); str = ""; while ((str = in.readLine()) != null) { final String[] split = str.split(","); final String date = split[0]; final double amount = Double.parseDouble(split[1]); final Dividend dividend = new Dividend(date, amount); dividends.add(dividend); } in.close(); } catch (final IOException ioe) { logger.error("Error parsing historical prices for " + getSymbol(), ioe); } }
|
11
|
Code Sample 1:
private static Long getNextPkValueForEntityIncreaseBy(String ename, int count, int increaseBy) { if (increaseBy < 1) increaseBy = 1; String where = "where eoentity_name = '" + ename + "'"; ERXJDBCConnectionBroker broker = ERXJDBCConnectionBroker.connectionBrokerForEntityNamed(ename); Connection con = broker.getConnection(); try { try { con.setAutoCommit(false); con.setReadOnly(false); } catch (SQLException e) { log.error(e, e); } for (int tries = 0; tries < count; tries++) { try { ResultSet resultSet = con.createStatement().executeQuery("select pk_value from pk_table " + where); con.commit(); boolean hasNext = resultSet.next(); long pk = 1; if (hasNext) { pk = resultSet.getLong("pk_value"); con.createStatement().executeUpdate("update pk_table set pk_value = " + (pk + increaseBy) + " " + where); } else { pk = maxIdFromTable(ename); con.createStatement().executeUpdate("insert into pk_table (eoentity_name, pk_value) values ('" + ename + "', " + (pk + increaseBy) + ")"); } con.commit(); return new Long(pk); } catch (SQLException ex) { String s = ex.getMessage().toLowerCase(); boolean creationError = (s.indexOf("error code 116") != -1); creationError |= (s.indexOf("pk_table") != -1 && s.indexOf("does not exist") != -1); creationError |= s.indexOf("ora-00942") != -1; if (creationError) { try { con.rollback(); log.info("creating pk table"); con.createStatement().executeUpdate("create table pk_table (eoentity_name varchar(100) not null, pk_value integer)"); con.createStatement().executeUpdate("alter table pk_table add primary key (eoentity_name)"); con.commit(); } catch (SQLException ee) { throw new NSForwardException(ee, "could not create pk table"); } } else { throw new NSForwardException(ex, "Error fetching PK"); } } } } finally { broker.freeConnection(con); } throw new IllegalStateException("Couldn't get PK"); }
Code Sample 2:
protected int insertRecord(PutMetadataRequest request, PutMetadataInfo info) throws ImsServiceException, SQLException { Connection con = null; boolean autoCommit = true; PreparedStatement st = null; ResultSet rs = null; int nRows = 0; String sXml = info.getXml(); String sUuid = info.getUuid(); String sName = info.getName(); String sThumbnailBinary = info.getThumbnailBinary(); String sTable = this.getResourceTableName(); String sDataTable = this.getResourceDataTableName(); long id = doesRecordExist(sTable, sUuid); try { ManagedConnection mc = returnConnection(); con = mc.getJdbcConnection(); autoCommit = con.getAutoCommit(); con.setAutoCommit(false); if (id < 0) { StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO ").append(sTable); sql.append(" ("); sql.append("DOCUUID,"); sql.append("TITLE,"); sql.append("OWNER"); sql.append(")"); sql.append(" VALUES(?,?,?)"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); int n = 1; st.setString(n++, sUuid); st.setString(n++, sName); st.setInt(n++, this.publisher.getLocalID()); nRows = st.executeUpdate(); closeStatement(st); if (nRows > 0) { if (getIsDbCaseSensitive(this.getRequestContext())) { st = con.prepareStatement("SELECT id FROM " + sTable + " WHERE UPPER(docuuid)=?"); } else { st = con.prepareStatement("SELECT id FROM " + sTable + " WHERE docuuid=?"); } st.setString(1, sUuid.toUpperCase()); rs = st.executeQuery(); rs.next(); id = rs.getLong(1); closeStatement(st); request.setActionStatus(ImsRequest.ACTION_STATUS_OK); sql = new StringBuffer(); sql.append("INSERT INTO ").append(sDataTable); sql.append(" (DOCUUID,ID,XML)"); sql.append(" VALUES(?,?,?)"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); st.setString(1, sUuid); st.setLong(2, id); st.setString(3, sXml); st.executeUpdate(); } } else { this.authorize(request, sUuid); StringBuffer sql = new StringBuffer(); sql.append("UPDATE ").append(sTable); sql.append(" SET "); if (!request.getLockTitle()) { sql.append("TITLE=?, "); } sql.append("OWNER=?, "); sql.append("UPDATEDATE=?"); sql.append(" WHERE DOCUUID=?"); logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); int n = 1; if (!request.getLockTitle()) { st.setString(n++, sName); } st.setInt(n++, this.publisher.getLocalID()); st.setTimestamp(n++, new Timestamp(System.currentTimeMillis())); st.setString(n++, sUuid); nRows = st.executeUpdate(); if (nRows > 0) { request.setActionStatus(ImsRequest.ACTION_STATUS_REPLACED); } closeStatement(st); sql = new StringBuffer(); if (doesRecordExist(sDataTable, sUuid) >= 0) { sql.append("UPDATE ").append(sDataTable); sql.append(" SET DOCUUID=?, XML=?, THUMBNAIL=?"); sql.append(" WHERE ID=?"); } else { sql.append("INSERT INTO ").append(sDataTable); sql.append(" (DOCUUID, XML,THUMBNAIL,ID)"); sql.append(" VALUES(?,?,?,?)"); } logExpression(sql.toString()); st = con.prepareStatement(sql.toString()); st.setString(1, sUuid); st.setString(2, sXml); st.setBytes(3, null); st.setLong(4, id); st.executeUpdate(); } con.commit(); } catch (ImsServiceException ex) { if (con != null) { con.rollback(); } throw ex; } catch (SQLException ex) { if (con != null) { con.rollback(); } throw ex; } finally { closeResultSet(rs); closeStatement(st); if (con != null) { con.setAutoCommit(autoCommit); } } if ((sThumbnailBinary != null) && (sThumbnailBinary.length() > 0)) { this.updateThumbnail(sThumbnailBinary, sUuid); } return nRows; }
|
11
|
Code Sample 1:
public static String calculateHA2(String uri) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(getBytes("GET", ISO_8859_1)); md.update((byte) ':'); md.update(getBytes(uri, ISO_8859_1)); return toHexString(md.digest()); } catch (NoSuchAlgorithmException err) { throw new RuntimeException(err); } }
Code Sample 2:
public static String encryptPassword(String password) { if (password == null) return null; MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.error("Algorithm not found", e); return null; } digest.reset(); digest.update(password.getBytes()); return hexValue(digest.digest()); }
|
00
|
Code Sample 1:
public void compressImage(InputStream input, OutputStream output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile = null; try { inputFile = File.createTempFile("tmp", ".tif"); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e1) { logger.error("Unexpected file format; expecting uncompressed TIFF", e1); throw new DjatokaException("Unexpected file format; expecting uncompressed TIFF"); } String out = STDOUT; File winOut = null; if (isWindows) { try { winOut = File.createTempFile("pipe_", ".jp2"); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } out = winOut.getAbsolutePath(); } String command = getKduCompressCommand(inputFile.getAbsolutePath(), out, params); logger.debug("compressCommand: " + command); Runtime rt = Runtime.getRuntime(); try { final Process process = rt.exec(command, envParams, new File(env)); if (out.equals(STDOUT)) { IOUtils.copyStream(process.getInputStream(), output); } else if (isWindows) { FileInputStream fis = new FileInputStream(out); IOUtils.copyStream(fis, output); fis.close(); } process.waitFor(); if (process != null) { String errorCheck = null; try { errorCheck = new String(IOUtils.getByteArray(process.getErrorStream())); } catch (Exception e1) { logger.error(e1, e1); } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); if (errorCheck != null) throw new DjatokaException(errorCheck); } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } catch (InterruptedException e) { logger.error(e, e); throw new DjatokaException(e); } if (inputFile != null) inputFile.delete(); if (winOut != null) winOut.delete(); }
Code Sample 2:
public static String move_files(String sessionid, String keys, String absolutePathForTheDestinationTag) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "move_files"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "move_file")); nameValuePairs.add(new BasicNameValuePair("absolute_new_parent_tag", absolutePathForTheDestinationTag)); nameValuePairs.add(new BasicNameValuePair("keys", keys)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); Log.d("jsonStringReturned:", resultJsonString); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; }
|
11
|
Code Sample 1:
public static byte[] getHashedPassword(String password, byte[] randomBytes) { byte[] hashedPassword = null; try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(randomBytes); messageDigest.update(password.getBytes("UTF-8")); hashedPassword = messageDigest.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return hashedPassword; }
Code Sample 2:
public synchronized String encrypt(String plaintext) throws SystemUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new SystemUnavailableException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new SystemUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
|
11
|
Code Sample 1:
public void setContentAsStream(final InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { output.close(); } this.content = output.toByteArray(); }
Code Sample 2:
public static FileChannel newFileChannel(File file, String rw, boolean enableException) throws IOException { if (file == null) return null; if (rw == null || rw.length() == 0) { return null; } rw = rw.toLowerCase(); if (rw.equals(MODE_READ)) { if (FileUtil.exists(file, enableException)) { FileInputStream fis = new FileInputStream(file); FileChannel ch = fis.getChannel(); setObjectMap(ch.hashCode(), fis, FIS); return ch; } } else if (rw.equals(MODE_WRITE)) { FileOutputStream fos = new FileOutputStream(file); FileChannel ch = fos.getChannel(); setObjectMap(ch.hashCode(), fos, FOS_W); return ch; } else if (rw.equals(MODE_APPEND)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel ch = raf.getChannel(); ch.position(ch.size()); setObjectMap(ch.hashCode(), raf, FOS_A); return ch; } } else if (rw.equals(MODE_READ_WRITE)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, rw); FileChannel ch = raf.getChannel(); setObjectMap(ch.hashCode(), raf, RAF); return ch; } } else { throw new IllegalArgumentException("Illegal read/write type : [" + rw + "]\n" + "You can use following types for: \n" + " (1) Read Only = \"r\"\n" + " (2) Write Only = \"w\"\n" + " (3) Read/Write = \"rw\"\n" + " (4) Append = \"a\""); } return null; }
|
00
|
Code Sample 1:
public void onClick(View v) { try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("m", "login")); nameValuePairs.add(new BasicNameValuePair("c", "User")); nameValuePairs.add(new BasicNameValuePair("password", "cloudisgreat")); nameValuePairs.add(new BasicNameValuePair("alias", "cs588")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); String result = ""; try { HttpResponse response = httpclient.execute(httppost); result = EntityUtils.toString(response.getEntity()); } catch (Exception e) { result = e.getMessage(); } LayoutInflater inflater = (LayoutInflater) WebTest.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final View layout = inflater.inflate(R.layout.window1, null); final PopupWindow popup = new PopupWindowTest(layout, 100, 100); Button b = (Button) layout.findViewById(R.id.test_button); b.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { Log.d("Debug", "Button activate"); popup.dismiss(); return false; } }); popup.showAtLocation(layout, Gravity.CENTER, 0, 0); View layout2 = inflater.inflate(R.layout.window1, null); final PopupWindow popup2 = new PopupWindowTest(layout2, 100, 100); TextView tview = (TextView) layout2.findViewById(R.id.pagetext); tview.setText(result); popup2.showAtLocation(layout, Gravity.CENTER, 50, -90); } catch (Exception e) { Log.d("Debug", e.toString()); } }
Code Sample 2:
public static void copy(String file1, String file2) throws IOException { File inputFile = new File(file1); File outputFile = new File(file2); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); System.out.println("Copy file from: " + file1 + " to: " + file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
00
|
Code Sample 1:
public static boolean insert(final Cargo cargo) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into cargo (nome) values (?)"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public void addScanURL(final URL url) { if (url == null) throw new NullArgumentException(); try { url.openConnection().connect(); } catch (IOException e) { e.printStackTrace(); } urlList.add(url); }
Code Sample 2:
public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
protected void doRequest(HttpServletRequest request, HttpServletResponse response, boolean inGet) throws ServletException, IOException { response.setHeader("Server", WebConsoleServlet.SERVER_STRING); try { String requestedFilename = request.getRequestURI().substring(1); URL url = new URL(getJarFileName() + "/"); JarURLConnection jarConnection = (JarURLConnection) (url.openConnection()); JarFile jarFile = jarConnection.getJarFile(); String negotiatedFilename = null; ZipEntry zipEntry = null; zipEntry = negotiateImageFile(jarFile, requestedFilename, isIE6OrEarlier(request.getHeader("User-Agent"))); if (zipEntry == null) { zipEntry = jarFile.getEntry(requestedFilename); } else { negotiatedFilename = zipEntry.getName(); } if (zipEntry == null || zipEntry.isDirectory()) { handleFileNotFound(inGet, request, response); return; } int fileSize = (int) zipEntry.getSize(); response.setContentLength(fileSize); if (negotiatedFilename != null) { response.setContentType(getContentType(negotiatedFilename)); } else { response.setContentType(getContentType(request.getRequestURI())); } InputStream in = jarFile.getInputStream(zipEntry); BufferedInputStream bufferedInputStream = new BufferedInputStream(in); byte[] file = new byte[fileSize]; int bytesRead = bufferedInputStream.read(file); bufferedInputStream.close(); if (bytesRead == fileSize && cachingEnabled) { SimpleDateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z"); java.util.Date today = new java.util.Date(); String date = formatter.format(GenericUtils.addOrSubstractDaysFromDate(today, 365)); response.setHeader("Expires", date); } OutputStream outputStream = response.getOutputStream(); outputStream.write(file); } catch (FileNotFoundException e) { handleFileNotFound(inGet, request, response); } catch (IOException e) { } catch (Throwable t) { Application.getApplication().logExceptionEvent(EventLogMessage.EventType.WEB_ERROR, t); } }
|
00
|
Code Sample 1:
public String digest(String algorithm, String text) { MessageDigest digester = null; try { digester = MessageDigest.getInstance(algorithm); digester.update(text.getBytes(Digester.ENCODING)); } catch (NoSuchAlgorithmException nsae) { _log.error(nsae, nsae); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } byte[] bytes = digester.digest(); if (_BASE_64) { return Base64.encode(bytes); } else { return new String(Hex.encodeHex(bytes)); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
|
00
|
Code Sample 1:
public void doFilter(final ServletRequest arg0, final ServletResponse arg1, final FilterChain arg2) throws IOException, ServletException { if (!this.init) { final HttpServletResponse response = Dynamic._.Cast(arg1); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Mainfilter not initialized."); return; } if (this.mainFilter != null) { try { URL url = this.context.getResource("/WEB-INF/classes/log4j.properties"); URLConnection uc = url.openConnection(); if (uc.getLastModified() != lastLoadLog4j) { lastLoadLog4j = uc.getLastModified(); try { uc.getInputStream().close(); } catch (Exception ignore) { } PropertyConfigurator.configure(url); } else { try { uc.getInputStream().close(); } catch (Exception ignore) { } } } catch (final Exception e) { } this.mainFilter.doFilter(arg0, arg1); } else { final HttpServletResponse response = Dynamic._.Cast(arg1); response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "Mainfilter bad setup."); } }
Code Sample 2:
public String getHtmlCodeUnCharset(String urlString) { StringBuffer result = new StringBuffer(); BufferedReader in = null; try { URL url = new URL((urlString)); URLConnection con = url.openConnection(); in = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = null; while ((line = in.readLine()) != null) { result.append(line + "\r\n"); } in.close(); } catch (MalformedURLException e) { System.out.println("Unable to connect to URL: " + urlString); } catch (IOException e) { System.out.println("IOException when connecting to URL: " + urlString); } finally { if (in != null) { try { in.close(); } catch (Exception ex) { System.out.println("Exception throws at finally close reader when connecting to URL: " + urlString); } } } return result.toString(); }
|
00
|
Code Sample 1:
public static IBiopaxModel read(URL url) throws ReactionException, IOException { IBiopaxModel model = null; InputStream in = null; try { in = url.openStream(); model = read(in); } catch (IOException e) { LOGGER.error("Unable to read from URL " + url, e); } finally { if (in != null) in.close(); } return model; }
Code Sample 2:
private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; }
|
11
|
Code Sample 1:
private static String getVisitorId(String guid, String account, String userAgent, Cookie cookie) throws NoSuchAlgorithmException, UnsupportedEncodingException { if (cookie != null && cookie.getValue() != null) { return cookie.getValue(); } String message; if (!isEmpty(guid)) { message = guid + account; } else { message = userAgent + getRandomNumber() + UUID.randomUUID().toString(); } MessageDigest m = MessageDigest.getInstance("MD5"); m.update(message.getBytes("UTF-8"), 0, message.length()); byte[] sum = m.digest(); BigInteger messageAsNumber = new BigInteger(1, sum); String md5String = messageAsNumber.toString(16); while (md5String.length() < 32) { md5String = "0" + md5String; } return "0x" + md5String.substring(0, 16); }
Code Sample 2:
public static String getMd5Digest(String pInput) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(pInput.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032x", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } }
|
11
|
Code Sample 1:
private String hashSong(Song s) { if (s == null) return null; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(s.getTitle().getBytes()); digest.update(s.getAllLyrics().getBytes()); String hash = Base64.encodeBytes(digest.digest()); return hash; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
Code Sample 2:
public static String getHash(String password, String salt) { try { MessageDigest messageDigest = null; messageDigest = MessageDigest.getInstance(SHA_512); messageDigest.reset(); messageDigest.update(salt.getBytes("UTF-8")); messageDigest.update(password.getBytes("UTF-8")); byte[] input = messageDigest.digest(); for (int i = 0; i < 1000; i++) { messageDigest.reset(); input = messageDigest.digest(input); } Formatter formatter = new Formatter(); for (byte i : input) { formatter.format("%02x", i); } return formatter.toString(); } catch (NoSuchAlgorithmException e) { return ""; } catch (UnsupportedEncodingException e) { return ""; } }
|
00
|
Code Sample 1:
public static void main(String[] args) { String u = "http://portal.acm.org/results.cfm?query=%28Author%3A%22" + "Boehm%2C+Barry" + "%22%29&srt=score%20dsc&short=0&source_disp=&since_month=&since_year=&before_month=&before_year=&coll=ACM&dl=ACM&termshow=matchboolean&range_query=&CFID=22704101&CFTOKEN=37827144&start=1"; URL url = null; AcmSearchresultPageParser_2010May cb = new AcmSearchresultPageParser_2010May(); try { url = new URL(u); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setUseCaches(false); InputStream is = uc.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); ParserDelegator pd = new ParserDelegator(); pd.parse(br, cb, true); br.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("all doc num= " + cb.getAllDocNum()); for (int i = 0; i < cb.getEachResultStartPositions().size(); i++) { HashMap<String, Integer> m = cb.getEachResultStartPositions().get(i); System.out.println(i + "pos= " + m); } }
Code Sample 2:
public void buildCache() { XMLCacheBuilder cacheBuilder = CompositePageUtil.getCacheBuilder(); String postFix = ""; if (cacheBuilder.getPostFix() != null && !cacheBuilder.getPostFix().equals("")) { postFix = "." + cacheBuilder.getPostFix(); } String basePath = cacheBuilder.getBasePath(); List actions = CompositePageUtil.getXMLActions(); for (int i = 0; i < actions.size(); i++) { try { XMLAction action = (XMLAction) actions.get(i); if (action.getEscapeCacheBuilder() != null && action.getEscapeCacheBuilder().equals("true")) continue; String actionUrl = basePath + action.getName() + postFix; URL url = new URL(actionUrl); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setDoInput(true); huc.setDoOutput(true); huc.setUseCaches(false); huc.setRequestProperty("Content-Type", "text/html"); DataOutputStream dos = new DataOutputStream(huc.getOutputStream()); dos.flush(); dos.close(); huc.disconnect(); } catch (MalformedURLException e) { logger.error(e); e.printStackTrace(); } catch (IOException e) { logger.equals(e); e.printStackTrace(); } } }
|
11
|
Code Sample 1:
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; }
Code Sample 2:
private void removeSessionId(InputStream inputStream, Output output) throws IOException { String jsessionid = RewriteUtils.getSessionId(target); boolean textContentType = ResourceUtils.isTextContentType(httpClientResponse.getHeader(HttpHeaders.CONTENT_TYPE), target.getDriver().getConfiguration().getParsableContentTypes()); if (jsessionid == null || !textContentType) { IOUtils.copy(inputStream, output.getOutputStream()); } else { String charset = httpClientResponse.getContentCharset(); if (charset == null) { charset = "ISO-8859-1"; } String content = IOUtils.toString(inputStream, charset); content = removeSessionId(jsessionid, content); if (output.getHeader(HttpHeaders.CONTENT_LENGTH) != null) { output.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(content.length())); } OutputStream outputStream = output.getOutputStream(); IOUtils.write(content, outputStream, charset); } inputStream.close(); }
|
00
|
Code Sample 1:
public int[] do_it(final int[] x) { int temp = 0; int j = x.length; while (j > 0) { for (int i = 0; i < j - 1; i++) { if (x[i] > x[i + 1]) { temp = x[i]; x[i] = x[i + 1]; x[i + 1] = temp; } ; } ; j--; } ; return x; }
Code Sample 2:
private File Gzip(File f) throws IOException { if (f == null || !f.exists()) return null; File dest_dir = f.getParentFile(); String dest_filename = f.getName() + ".gz"; File zipfile = new File(dest_dir, dest_filename); GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(zipfile)); FileInputStream in = new FileInputStream(f); byte buf[] = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.finish(); try { in.close(); } catch (Exception e) { } try { out.close(); } catch (Exception e) { } try { f.delete(); } catch (Exception e) { } return zipfile; }
|
11
|
Code Sample 1:
public void copyToCurrentDir(File _copyFile, String _fileName) throws IOException { File outputFile = new File(getCurrentPath() + File.separator + _fileName); FileReader in; FileWriter out; if (!outputFile.exists()) { outputFile.createNewFile(); } in = new FileReader(_copyFile); out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); reList(); }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) throw new IOException("Destination '" + destFile + "' exists but is a directory"); FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); if (preserveFileDate) destFile.setLastModified(srcFile.lastModified()); }
|
11
|
Code Sample 1:
public static void copy(File source, File sink) throws IOException { if (source == null) throw new NullPointerException("Source file must not be null"); if (sink == null) throw new NullPointerException("Target file must not be null"); if (!source.exists()) throw new IOException("Source file " + source.getPath() + " does not exist"); if (!source.isFile()) throw new IOException("Source file " + source.getPath() + " is not a regular file"); if (!source.canRead()) throw new IOException("Source file " + source.getPath() + " can not be read (missing acces right)"); if (!sink.exists()) throw new IOException("Target file " + sink.getPath() + " does not exist"); if (!sink.isFile()) throw new IOException("Target file " + sink.getPath() + " is not a regular file"); if (!sink.canWrite()) throw new IOException("Target file " + sink.getPath() + " is write protected"); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(source); output = new FileOutputStream(sink); byte[] buffer = new byte[1024]; while (input.available() > 0) { int bread = input.read(buffer); if (bread > 0) output.write(buffer, 0, bread); } } finally { if (input != null) try { input.close(); } catch (IOException x) { } if (output != null) try { output.close(); } catch (IOException x) { } } }
Code Sample 2:
public static void copyFile(String source, String destination, TimeSlotTracker timeSlotTracker) { LOG.info("copying [" + source + "] to [" + destination + "]"); BufferedInputStream sourceStream = null; BufferedOutputStream destStream = null; try { File destinationFile = new File(destination); if (destinationFile.exists()) { destinationFile.delete(); } sourceStream = new BufferedInputStream(new FileInputStream(source)); destStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); int readByte; while ((readByte = sourceStream.read()) > 0) { destStream.write(readByte); } Object[] arg = { destinationFile.getName() }; String msg = timeSlotTracker.getString("datasource.xml.copyFile.copied", arg); LOG.fine(msg); } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } finally { try { if (destStream != null) { destStream.close(); } if (sourceStream != null) { sourceStream.close(); } } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } } }
|
00
|
Code Sample 1:
@Test public void testCopy_inputStreamToWriter_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, null); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
Code Sample 2:
public List<AnalyzerResult> analyze(LWComponent c, boolean tryFallback) { List<AnalyzerResult> results = new ArrayList<AnalyzerResult>(); try { URL url = new URL(DEFAULT_FLOW_URL + "?" + DEFAULT_INPUT + "=" + c.getLabel()); if (flow != null) { url = new URL(flow.getUrl() + "?" + flow.getInputList().get(0) + "=" + getSpecFromComponent(c)); } System.setProperty("javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl"); XMLDecoder decoder = new XMLDecoder(url.openStream()); Map map = (Map) decoder.readObject(); for (Object key : map.keySet()) { results.add(new AnalyzerResult(key.toString(), map.get(key).toString())); } } catch (Exception ex) { ex.printStackTrace(); VueUtil.alert("Can't Execute Flow on the node " + c.getLabel(), "Can't Execute Seasr flow"); } return results; }
|
11
|
Code Sample 1:
public void includeCss(Group group, Writer out, PageContext pageContext) throws IOException { ByteArrayOutputStream outtmp = new ByteArrayOutputStream(); if (AbstractGroupBuilder.getInstance().buildGroupJsIfNeeded(group, outtmp, pageContext.getServletContext())) { FileOutputStream fileStream = null; try { fileStream = new FileOutputStream(new File(RetentionHelper.buildFullRetentionFilePath(group, ".css"))); IOUtils.copy(new ByteArrayInputStream(outtmp.toByteArray()), fileStream); } finally { if (fileStream != null) fileStream.close(); } } }
Code Sample 2:
public void testOptionalSections() throws Exception { final File implementationDirectory = this.getTestSourcesDirectory(); final File specificationDirectory = this.getTestSourcesDirectory(); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutConstructorsSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutDefaultConstructorSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutDocumentationSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("ImplementationWithoutLicenseSection.java.txt"), new FileOutputStream(new File(implementationDirectory, "Implementation.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getImplementation("Implementation"), implementationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("SpecificationWithoutDocumentationSection.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); IOUtils.copy(this.getClass().getResourceAsStream("SpecificationWithoutLicenseSection.java.txt"), new FileOutputStream(new File(specificationDirectory, "Specification.java"))); this.getTestTool().manageSources(this.getTestTool().getModules().getSpecification("Specification"), specificationDirectory); }
|
00
|
Code Sample 1:
public static String getHash(String password, String salt) { try { MessageDigest messageDigest = null; messageDigest = MessageDigest.getInstance(SHA_512); messageDigest.reset(); messageDigest.update(salt.getBytes("UTF-8")); messageDigest.update(password.getBytes("UTF-8")); byte[] input = messageDigest.digest(); for (int i = 0; i < 1000; i++) { messageDigest.reset(); input = messageDigest.digest(input); } Formatter formatter = new Formatter(); for (byte i : input) { formatter.format("%02x", i); } return formatter.toString(); } catch (NoSuchAlgorithmException e) { return ""; } catch (UnsupportedEncodingException e) { return ""; } }
Code Sample 2:
protected Context getResource3ServerInitialContext() throws Exception { if (resource3ServerJndiProps == null) { URL url = ClassLoader.getSystemResource("jndi.properties"); resource3ServerJndiProps = new java.util.Properties(); resource3ServerJndiProps.load(url.openStream()); String jndiHost = System.getProperty("jbosstest.resource3.server.host", "localhost"); String jndiUrl = "jnp://" + jndiHost + ":1099"; resource3ServerJndiProps.setProperty("java.naming.provider.url", jndiUrl); } return new InitialContext(resource3ServerJndiProps); }
|
00
|
Code Sample 1:
public String getFeatureInfoHTML(Point3d GKposition, String[] layerIds, int featureCount) { String html = ""; try { String request = null; if (version == VERSION_030) { org.gdi3d.xnavi.services.w3ds.x030.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x030.GetFeatureInfo(this.serviceEndPoint); request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount); } else if (version == VERSION_040) { org.gdi3d.xnavi.services.w3ds.x040.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x040.GetFeatureInfo(this.serviceEndPoint); request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount); } else if (version == VERSION_041) { org.gdi3d.xnavi.services.w3ds.x041.GetFeatureInfo getFeatureInfo = new org.gdi3d.xnavi.services.w3ds.x041.GetFeatureInfo(this.serviceEndPoint); request = getFeatureInfo.createRequest(GKposition, layerIds, featureCount); } if (Navigator.isVerbose()) System.out.println(request); URL url = new URL(request); int contentLength = -1; URLConnection urlc; urlc = url.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); if (getEncoding() != null) { urlc.setRequestProperty("Authorization", "Basic " + getEncoding()); } urlc.connect(); String content_type = urlc.getContentType(); if (content_type.equalsIgnoreCase("text/html") || content_type.equalsIgnoreCase("text/html;charset=UTF-8")) { InputStream is = urlc.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); StringBuffer sb = new StringBuffer(); InputStreamReader isr = new InputStreamReader(bis); char chars[] = new char[10240]; int len = 0; contentLength = 0; while ((len = isr.read(chars, 0, chars.length)) >= 0) { sb.append(chars, 0, len); contentLength += len; } chars = null; isr.close(); bis.close(); is.close(); html = sb.toString(); } } catch (Exception e) { e.printStackTrace(); } return html; }
Code Sample 2:
private void writeAndCheckFile(DataFileReader reader, String base, String path, String hash, Reference ref, boolean hashall) throws Exception { Data data = ref.data; File file = new File(base + path); file.getParentFile().mkdirs(); if (Debug.level > 1) System.err.println("read file " + data.file + " at index " + data.index); OutputStream output = new FileOutputStream(file); if (hashall) output = new DigestOutputStream(output, MessageDigest.getInstance("MD5")); reader.read(output, data.index, data.file); output.close(); if (hashall) { String filehash = StringUtils.toHex(((DigestOutputStream) output).getMessageDigest().digest()); if (!hash.equals(filehash)) throw new RuntimeException("hash wasn't equal for " + file); } file.setLastModified(ref.lastmod); if (file.length() != data.size) throw new RuntimeException("corrupted file " + file); }
|
11
|
Code Sample 1:
public static InputSource getInputSource(URL url) throws IOException { String proto = url.getProtocol().toLowerCase(); if (!("http".equals(proto) || "https".equals(proto))) throw new IllegalArgumentException("OAI-PMH only allows HTTP(S) as network protocol!"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder ua = new StringBuilder("Java/"); ua.append(System.getProperty("java.version")); ua.append(" ("); ua.append(OAIHarvester.class.getName()); ua.append(')'); conn.setRequestProperty("User-Agent", ua.toString()); conn.setRequestProperty("Accept-Encoding", "gzip, deflate, identity;q=0.3, *;q=0"); conn.setRequestProperty("Accept-Charset", "utf-8, *;q=0.1"); conn.setRequestProperty("Accept", "text/xml, application/xml, *;q=0.1"); conn.setUseCaches(false); conn.setFollowRedirects(true); log.debug("Opening connection..."); InputStream in = null; try { conn.connect(); in = conn.getInputStream(); } catch (IOException ioe) { int after, code; try { after = conn.getHeaderFieldInt("Retry-After", -1); code = conn.getResponseCode(); } catch (IOException ioe2) { after = -1; code = -1; } if (code == HttpURLConnection.HTTP_UNAVAILABLE && after > 0) throw new RetryAfterIOException(after, ioe); throw ioe; } String encoding = conn.getContentEncoding(); if (encoding == null) encoding = "identity"; encoding = encoding.toLowerCase(); log.debug("HTTP server uses " + encoding + " content encoding."); if ("gzip".equals(encoding)) in = new GZIPInputStream(in); else if ("deflate".equals(encoding)) in = new InflaterInputStream(in); else if (!"identity".equals(encoding)) throw new IOException("Server uses an invalid content encoding: " + encoding); String contentType = conn.getContentType(); String charset = null; if (contentType != null) { contentType = contentType.toLowerCase(); int charsetStart = contentType.indexOf("charset="); if (charsetStart >= 0) { int charsetEnd = contentType.indexOf(";", charsetStart); if (charsetEnd == -1) charsetEnd = contentType.length(); charsetStart += "charset=".length(); charset = contentType.substring(charsetStart, charsetEnd).trim(); } } log.debug("Charset from Content-Type: '" + charset + "'"); InputSource src = new InputSource(in); src.setSystemId(url.toString()); src.setEncoding(charset); return src; }
Code Sample 2:
private void checkForNewVersion() { try { org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(net.xan.taskstack.TaskStackApp.class).getContext().getResourceMap(NewTaskDialog.class); String versionUrl = resourceMap.getString("Application.versionFileUrl"); long startTime = System.currentTimeMillis(); System.out.println("Retrieving version file from\n" + versionUrl); URL url = new URL(versionUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { if (str.startsWith("LastVersion")) { String remoteVersion = str.substring(str.indexOf("=") + 1); String localVersion = resourceMap.getString("Application.version"); System.out.println("Version file found"); System.out.println("Local version: " + localVersion); System.out.println("Remote version: " + remoteVersion); if (remoteVersion.compareTo(localVersion) > 0) { askDownloadNewVersion(remoteVersion, localVersion); } break; } } long endTime = System.currentTimeMillis(); System.out.println("Elapsed time " + (endTime - startTime) + "ms"); in.close(); } catch (MalformedURLException e) { System.err.println(e.getMessage()); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void copyFileFromLocalMachineToRemoteMachine(InputStream source, File destination) throws Exception { String fileName = destination.getPath(); File f = new File(getFtpServerHome(), "" + System.currentTimeMillis()); f.deleteOnExit(); org.apache.commons.io.IOUtils.copy(source, new FileOutputStream(f)); remoteHostClient.setAscii(isAscii()); remoteHostClient.setPromptOn(isPrompt()); remoteHostClient.copyFileFromLocalMachineToRemoteClient(f.getName(), fileName); }
Code Sample 2:
public static void copyFolderStucture(String strPath, String dstPath) throws IOException { Constants.iLog.LogInfoLine("copying " + strPath); File src = new File(strPath); File dest = new File(dstPath); if (src.isDirectory()) { dest.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String dest1 = dest.getAbsolutePath() + "\\" + list[i]; String src1 = src.getAbsolutePath() + "\\" + list[i]; copyFolderStucture(src1, dest1); } } else { FileInputStream fin = new FileInputStream(src); FileOutputStream fout = new FileOutputStream(dest); int c; while ((c = fin.read()) >= 0) fout.write(c); fin.close(); fout.close(); } }
|
00
|
Code Sample 1:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
Code Sample 2:
protected void initDefaultRolesFile() { String webConfigPath = System.getProperty("dcm4chee-web3.cfg.path", "conf/dcm4chee-web3"); File mappingFile = new File(webConfigPath + "roles.json"); if (!mappingFile.isAbsolute()) mappingFile = new File(ServerConfigLocator.locate().getServerHomeDir(), mappingFile.getPath()); if (mappingFile.exists()) return; log.info("Init default Role Mapping file! mappingFile:" + mappingFile); if (mappingFile.getParentFile().mkdirs()) log.info("M-WRITE dir:" + mappingFile.getParent()); FileChannel fos = null; InputStream is = null; try { URL url = getClass().getResource("/META-INF/roles-default.json"); log.info("Use default Mapping File content of url:" + url); is = url.openStream(); ReadableByteChannel inCh = Channels.newChannel(is); fos = new FileOutputStream(mappingFile).getChannel(); int pos = 0; while (is.available() > 0) pos += fos.transferFrom(inCh, pos, is.available()); } catch (Exception e) { log.error("Roles file doesn't exist and the default can't be created!", e); } finally { close(is); close(fos); } }
|
11
|
Code Sample 1:
public void copyTo(File folder) { if (!isNewFile()) { return; } if (!folder.exists()) { folder.mkdir(); } File dest = new File(folder, name); try { FileInputStream in = new FileInputStream(currentPath); FileOutputStream out = new FileOutputStream(dest); byte[] readBuf = new byte[1024 * 512]; int readLength; long totalCopiedSize = 0; boolean canceled = false; while ((readLength = in.read(readBuf)) != -1) { out.write(readBuf, 0, readLength); } in.close(); out.close(); if (canceled) { dest.delete(); } else { currentPath = dest; newFile = false; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void sendSimpleHTMLMessage(Map<String, String> recipients, String object, String htmlContent, String from) { String message; try { File webinfDir = ClasspathUtils.getClassesDir().getParentFile(); File mailDir = new File(webinfDir, "mail"); File templateFile = new File(mailDir, "HtmlMessageTemplate.html"); StringWriter sw = new StringWriter(); Reader r = new BufferedReader(new FileReader(templateFile)); IOUtils.copy(r, sw); sw.close(); message = sw.getBuffer().toString(); message = message.replaceAll("%MESSAGE_HTML%", htmlContent).replaceAll("%APPLICATION_URL%", FGDSpringUtils.getExternalServerURL()); } catch (IOException e) { throw new RuntimeException(e); } Properties prop = getRealSMTPServerProperties(); if (prop != null) { try { MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); multipart.addBodyPart(messageBodyPart); sendHTML(recipients, object, multipart, from); } catch (MessagingException e) { throw new RuntimeException(e); } } else { StringBuffer contenuCourriel = new StringBuffer(); for (Entry<String, String> recipient : recipients.entrySet()) { if (recipient.getValue() == null) { contenuCourriel.append("À : " + recipient.getKey()); } else { contenuCourriel.append("À : " + recipient.getValue() + "<" + recipient.getKey() + ">"); } contenuCourriel.append("\n"); } contenuCourriel.append("Sujet : " + object); contenuCourriel.append("\n"); contenuCourriel.append("Message : "); contenuCourriel.append("\n"); contenuCourriel.append(message); } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test1.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.encrypt(reader, writer, key, mode); }
Code Sample 2:
public void get(String path, File fileToGet) throws IOException { FTPClient ftp = new FTPClient(); try { int reply = 0; ftp.connect(this.endpointURL, this.endpointPort); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp get server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); OutputStream output = new FileOutputStream(fileToGet.getName()); if (ftp.retrieveFile(path, output) != true) { ftp.logout(); output.close(); throw new IOException("FTP get exception, maybe file not found"); } ftp.logout(); } catch (Exception e) { throw new IOException(e.getMessage()); } }
|
11
|
Code Sample 1:
private synchronized boolean createOrganization(String organizationName, HttpServletRequest req) { if ((organizationName == null) || (organizationName.equals(""))) { message = "invalid new_organization_name."; return false; } String tmpxml = TextUtil.xmlEscape(organizationName); String tmpdb = DBAccess.SQLEscape(organizationName); if ((!organizationName.equals(tmpxml)) || (!organizationName.equals(tmpdb)) || (!TextUtil.isValidFilename(organizationName))) { message = "invalid new_organization_name."; return false; } if ((organizationName.indexOf('-') > -1) || (organizationName.indexOf(' ') > -1)) { message = "invalid new_organization_name."; return false; } String[] orgnames = ServerConsoleServlet.getOrganizationNames(); for (int i = 0; i < orgnames.length; i++) { if (orgnames.equals(organizationName)) { message = "already exists."; return false; } } message = "create new organization: " + organizationName; File newOrganizationDirectory = new File(ServerConsoleServlet.RepositoryLocalDirectory.getAbsolutePath() + File.separator + organizationName); if (!newOrganizationDirectory.mkdir()) { message = "cannot create directory."; return false; } File cacheDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("CacheDirName")); cacheDir.mkdir(); File confDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ConfDirName")); confDir.mkdir(); File rdfDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("RDFDirName")); rdfDir.mkdir(); File resourceDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("ResourceDirName")); resourceDir.mkdir(); File obsoleteDir = new File(resourceDir.getAbsolutePath() + File.separator + "obsolete"); obsoleteDir.mkdir(); File schemaDir = new File(newOrganizationDirectory.getAbsolutePath() + File.separator + ServerConsoleServlet.getConfigByTagName("SchemaDirName")); schemaDir.mkdir(); String organization_temp_dir = ServerConsoleServlet.convertToAbsolutePath(ServerConsoleServlet.getConfigByTagName("OrganizationTemplate")); File templ = new File(organization_temp_dir); File[] confFiles = templ.listFiles(); for (int i = 0; i < confFiles.length; i++) { try { FileReader fr = new FileReader(confFiles[i]); FileWriter fw = new FileWriter(confDir.getAbsolutePath() + File.separator + confFiles[i].getName()); int c = -1; while ((c = fr.read()) != -1) fw.write(c); fw.flush(); fw.close(); fr.close(); } catch (IOException e) { } } SchemaModelHolder.reloadSchemaModel(organizationName); ResourceModelHolder.reloadResourceModel(organizationName); UserLogServlet.initializeUserLogDB(organizationName); MetaEditServlet.createNewProject(organizationName, "standard", MetaEditServlet.convertProjectIdToProjectUri(organizationName, "standard", req), this.username); ResourceModelHolder.reloadResourceModel(organizationName); message = organizationName + " is created. Restart Tomcat to activate this organization."; return true; }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
public void initFromXml(final String xmlFileName) throws java.net.MalformedURLException, ConfigurationException, IOException { if (xmlInitialized) { return; } templates = null; MergeTemplateWriter.setTokenList(getTokenProvider().getKnownTokens()); java.net.URL url = new FileFinder().getUrl(getTokenProvider().getClass(), xmlFileName); InputStreamReader xmlFileReader = new InputStreamReader(url.openStream()); KnownTemplates temps = MergeTemplateWriter.importFromXML(xmlFileReader); xmlFileReader.close(); KnownTemplates.setDefaultInstance(temps); setTemplates(temps); setInitialized(true); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
Code Sample 2:
protected void doRestoreOrganizeType() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_TABLE; String strSelQuery = "SELECT organize_type_id,organize_type_name,width " + "FROM " + Common.ORGANIZE_TYPE_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_TABLE + " " + "(organize_type_id,organize_type_name,width) " + "VALUES (?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("organize_type_id")); ps.setString(2, result.getString("organize_type_name")); ps.setInt(3, result.getInt("width")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): SQLException while committing or rollback"); } }
|
00
|
Code Sample 1:
private final String encryptPassword(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.log(Level.WARNING, "Error while obtaining decript algorithm", e); throw new RuntimeException("AccountData.encryptPassword()"); } try { md.update(pass.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { log.log(Level.WARNING, "Problem with decript algorithm occured.", e); throw new RuntimeException("AccountData.encryptPassword()"); } return new BASE64Encoder().encode(md.digest()); }
Code Sample 2:
public static boolean download(String url, File file) { HttpURLConnection conn = null; BufferedInputStream in = null; BufferedOutputStream out = null; try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.connect(); if (conn.getResponseCode() == 200) { System.out.println("length:" + conn.getContentLength()); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(file)); byte[] b = new byte[1024 << 10]; int i = 0; while ((i = in.read(b)) > -1) { if (i > 0) out.write(b, 0, i); } return true; } else { System.out.println(conn.getResponseCode() + ":" + url); } } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } if (conn != null) conn.disconnect(); } return false; }
|
11
|
Code Sample 1:
public void writeTo(File f) throws IOException { if (state != STATE_OK) throw new IllegalStateException("Upload failed"); if (tempLocation == null) throw new IllegalStateException("File already saved"); if (f.isDirectory()) f = new File(f, filename); FileInputStream fis = new FileInputStream(tempLocation); FileOutputStream fos = new FileOutputStream(f); byte[] buf = new byte[BUFFER_SIZE]; try { int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } finally { deleteTemporaryFile(); fis.close(); fos.close(); } }
Code Sample 2:
private void copyFile(String sourceFilename, String targetFilename) throws IOException { File source = new File(sourceFilename); File target = new File(targetFilename); InputStream in = new FileInputStream(source); OutputStream out = new FileOutputStream(target); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
|
00
|
Code Sample 1:
@Override public void run() { try { status = UploadStatus.INITIALISING; DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.filedropper.com"); httpget.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2 GTBDFff GTB7.0"); HttpResponse httpresponse = httpclient.execute(httpget); httpresponse.getEntity().consumeContent(); httppost = new HttpPost("http://www.filedropper.com/index.php?xml=true"); httppost.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2 GTBDFff GTB7.0"); MultipartEntity requestEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); requestEntity.addPart("file", new MonitoredFileBody(file, uploadProgress)); requestEntity.addPart("Upload", new StringBody("Submit Query")); httppost.setEntity(requestEntity); status = UploadStatus.UPLOADING; httpresponse = httpclient.execute(httppost); String strResponse = EntityUtils.toString(httpresponse.getEntity()); status = UploadStatus.GETTINGLINK; downURL = "http://www.filedropper.com/" + strResponse.substring(strResponse.lastIndexOf("=") + 1); NULogger.getLogger().info(downURL); uploadFinished(); } catch (Exception ex) { ex.printStackTrace(); NULogger.getLogger().severe(ex.toString()); uploadFailed(); } }
Code Sample 2:
public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
|
00
|
Code Sample 1:
public boolean loadResource(String resourcePath) { try { URL url = Thread.currentThread().getContextClassLoader().getResource(resourcePath); if (url == null) { logger.error("Cannot find the resource named: '" + resourcePath + "'. Failed to load the keyword list."); return false; } InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ligne = br.readLine(); while (ligne != null) { if (!contains(ligne.toUpperCase())) addLast(ligne.toUpperCase()); ligne = br.readLine(); } return true; } catch (IOException ioe) { logger.log(Level.ERROR, "Cannot load default SQL keywords file.", ioe); } return false; }
Code Sample 2:
private String calculateMD5(String input) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(input.getBytes()); byte[] md5 = digest.digest(); String tmp = ""; String res = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } return res; }
|
11
|
Code Sample 1:
private void convertClasses(File source, File destination) throws PostProcessingException, CodeCheckException, IOException { Stack sourceStack = new Stack(); Stack destinationStack = new Stack(); sourceStack.push(source); destinationStack.push(destination); while (!sourceStack.isEmpty()) { source = (File) sourceStack.pop(); destination = (File) destinationStack.pop(); if (!destination.exists()) destination.mkdirs(); File[] files = source.listFiles(); for (int i = 0; i < files.length; i++) { File current = (File) files[i]; if (current.isDirectory()) { sourceStack.push(current); destinationStack.push(new File(destination, current.getName())); } else if (current.getName().endsWith(".class")) { ClassWriter writer = new ClassWriter(); InputStream is = new BufferedInputStream(new FileInputStream(current)); writer.readClass(is); is.close(); if ((getStatusFlags(writer.getClassName(writer.getCurrentClassIndex())) & PP_PROCESSED) != 0) { ClassWriter[] auxWriter = new ClassWriter[1]; transformClass(writer, auxWriter); File output = new File(destination, current.getName()); OutputStream os = new BufferedOutputStream(new FileOutputStream(output)); writer.writeClass(os); os.close(); if (auxWriter[0] != null) { String className = auxWriter[0].getClassName(auxWriter[0].getCurrentClassIndex()); className = className.substring(className.lastIndexOf('.') + 1, className.length()); output = new File(destination, className + ".class"); os = new BufferedOutputStream(new FileOutputStream(output)); auxWriter[0].writeClass(os); os.close(); } } } } } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
Code Sample 2:
private byte[] hash(String data, HashAlg alg) { try { MessageDigest digest = MessageDigest.getInstance(alg.toString()); digest.update(data.getBytes()); byte[] hash = digest.digest(); return hash; } catch (NoSuchAlgorithmException e) { } return null; }
|
11
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void main(String[] args) { if (args.length <= 0) { System.out.println(" *** SQL script generator and executor ***"); System.out.println(" You must specify name of the file with SQL script data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with administrator priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have: '@' before schema to create,"); System.out.println(" '#' before table to create, '&' before table to insert,"); System.out.println(" '$' before trigger (inverse 'FK on delete cascade') to create,"); System.out.println(" '>' before table to drop, '<' before schema to drop."); System.out.println(" Other rows contain parameters of these actions:"); System.out.println(" for & action each parameter is a list of values,"); System.out.println(" for @ -//- is # acrion, for # -//- is column/constraint "); System.out.println(" definition or $ action. $ syntax to delete from table:"); System.out.println(" fullNameOfTable:itsColInWhereClause=matchingColOfThisTable"); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" If you specify 2nd command line argument - file name too -"); System.out.println(" connection will be established but all statements will"); System.out.println(" be saved in that output file and not transmitted to DB"); System.out.println(" If you specify 3nd command line argument - connect_string -"); System.out.println(" connect information will be added to output file"); System.out.println(" in the form 'connect user/password@connect_string'"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; try { for (int i = 0; i < 4; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); SQLScript script = new SQLScript(connection); if (args.length > 1) { writer = new FileWriter(args[1]); if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator); } try { System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); System.out.println(" Script execution error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } }
|
00
|
Code Sample 1:
public int executeUpdate(String query, QueryParameter params) throws DAOException { PreparedStatement ps = null; Query queryObj = getModel().getQuery(query); if (conditionalQueries != null && conditionalQueries.containsKey(query)) { queryObj = (Query) conditionalQueries.get(query); } String sql = queryObj.getStatement(params.getVariables()); logger.debug(sql); try { if (con == null || con.isClosed()) { con = DataSource.getInstance().getConnection(getModel().getDataSource()); } ps = con.prepareStatement(sql); setParameters(ps, queryObj, params); return ps.executeUpdate(); } catch (SQLException e) { logger.error("DataBase Error :", e); if (transactionMode) rollback(); transactionMode = false; throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", e.getMessage()); } catch (Exception ex) { logger.error("Error :", ex); if (transactionMode) rollback(); transactionMode = false; throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", ex.getMessage()); } finally { try { if (!transactionMode) con.commit(); if (ps != null) ps.close(); if (!transactionMode && con != null) con.close(); } catch (SQLException e) { throw new DAOException("Unexpected Error Query (" + query + ")", "error.DAO.database", e.getMessage()); } } }
Code Sample 2:
public static void main(String[] args) throws IOException { PostParameter a1 = new PostParameter("v", Utils.encode("1.0")); PostParameter a2 = new PostParameter("api_key", Utils.encode(RenRenConstant.apiKey)); PostParameter a3 = new PostParameter("method", Utils.encode("notifications.send")); PostParameter a4 = new PostParameter("call_id", System.nanoTime()); PostParameter a5 = new PostParameter("session_key", Utils.encode("5.22af9ee9ad842c7eb52004ece6e96b10.86400.1298646000-350727914")); PostParameter a6 = new PostParameter("to_ids", Utils.encode("350727914")); PostParameter a7 = new PostParameter("notification", "又到了要睡觉的时间了。"); PostParameter a8 = new PostParameter("format", Utils.encode("JSON")); RenRenPostParameters ps = new RenRenPostParameters(Utils.encode(RenRenConstant.secret)); ps.addParameter(a1); ps.addParameter(a2); ps.addParameter(a3); ps.addParameter(a4); ps.addParameter(a5); ps.addParameter(a6); ps.addParameter(a7); ps.addParameter(a8); System.out.println(RenRenConstant.apiUrl + "?" + ps.generateUrl()); URL url = new URL(RenRenConstant.apiUrl + "?" + ps.generateUrl()); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setDoOutput(true); request.setRequestMethod("POST"); System.out.println("Sending request..."); request.connect(); System.out.println("Response: " + request.getResponseCode() + " " + request.getResponseMessage()); BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); String b = null; while ((b = reader.readLine()) != null) { System.out.println(b); } }
|
11
|
Code Sample 1:
public static void main(String[] argv) { if (1 < argv.length) { File[] sources = Source(argv[0]); if (null != sources) { for (File src : sources) { File[] targets = Target(src, argv); if (null != targets) { final long srclen = src.length(); try { FileChannel source = new FileInputStream(src).getChannel(); try { for (File tgt : targets) { FileChannel target = new FileOutputStream(tgt).getChannel(); try { source.transferTo(0L, srclen, target); } finally { target.close(); } System.out.printf("Updated %s\n", tgt.getPath()); File[] deletes = Delete(src, tgt); if (null != deletes) { for (File del : deletes) { if (SVN) { if (SvnDelete(del)) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } else if (del.delete()) System.out.printf("Deleted %s\n", del.getPath()); else System.out.printf("Failed to delete %s\n", del.getPath()); } } if (SVN) SvnAdd(tgt); } } finally { source.close(); } } catch (Exception exc) { exc.printStackTrace(); System.exit(1); } } } System.exit(0); } else { System.err.printf("Source file(s) not found in '%s'\n", argv[0]); System.exit(1); } } else { usage(); System.exit(1); } }
Code Sample 2:
private static final void copyFile(File srcFile, File destDir, byte[] buffer) { try { File destFile = new File(destDir, srcFile.getName()); InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); out.close(); } catch (IOException ioe) { System.err.println("Couldn't copy file '" + srcFile + "' to directory '" + destDir + "'"); } }
|
11
|
Code Sample 1:
public static boolean insereLicao(final Connection con, Licao lic, Autor aut, Descricao desc) { try { con.setAutoCommit(false); Statement smt = con.createStatement(); if (aut.getCodAutor() == 0) { GeraID.gerarCodAutor(con, aut); smt.executeUpdate("INSERT INTO autor VALUES(" + aut.getCodAutor() + ",'" + aut.getNome() + "','" + aut.getEmail() + "')"); } GeraID.gerarCodDescricao(con, desc); GeraID.gerarCodLicao(con, lic); String titulo = lic.getTitulo().replaceAll("['\"]", ""); String coment = lic.getComentario().replaceAll("[']", "\""); String texto = desc.getTexto().replaceAll("[']", "\""); smt.executeUpdate("INSERT INTO descricao VALUES(" + desc.getCodDesc() + ",'" + texto + "')"); smt.executeUpdate("INSERT INTO licao VALUES(" + lic.getCodigo() + ",'" + titulo + "','" + coment + "'," + desc.getCodDesc() + ")"); smt.executeUpdate("INSERT INTO lic_aut VALUES(" + lic.getCodigo() + "," + aut.getCodAutor() + ")"); con.commit(); return (true); } catch (SQLException e) { try { JOptionPane.showMessageDialog(null, "Rolling back transaction", "LICAO: Database error", JOptionPane.ERROR_MESSAGE); con.rollback(); } catch (SQLException e1) { System.err.print(e1.getSQLState()); } return (false); } finally { try { con.setAutoCommit(true); } catch (SQLException e2) { System.err.print(e2.getSQLState()); } } }
Code Sample 2:
public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
|
11
|
Code Sample 1:
public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
00
|
Code Sample 1:
private String readScriptFromURL(URL context, String s) { Object content = null; URL url; try { url = new URL(context, s); } catch (MalformedURLException e) { return null; } try { content = url.getContent(); } catch (UnknownServiceException e) { Class jar_class; try { jar_class = Class.forName("java.net.JarURLConnection"); } catch (Exception e2) { return null; } Object jar; try { jar = url.openConnection(); } catch (IOException e2) { return null; } if (jar == null) { return null; } try { Method m = jar_class.getMethod("openConnection", ((java.lang.Class[]) null)); content = m.invoke(jar, ((java.lang.Object[]) null)); } catch (Exception e2) { return null; } } catch (IOException e) { return null; } catch (SecurityException e) { return null; } if (content instanceof String) { return (String) content; } else if (content instanceof InputStream) { InputStream fs = (InputStream) content; try { byte charArray[] = new byte[fs.available()]; fs.read(charArray); return new String(charArray); } catch (IOException e2) { return null; } finally { closeInputStream(fs); } } else { return null; } }
Code Sample 2:
private void loadDDL() throws IOException { try { conn.createStatement().executeQuery("SELECT * FROM overrides").close(); } catch (SQLException e) { Statement stmt = null; if (!e.getMessage().matches(ERR_MISSING_TABLE)) { LOG.trace(SQL_ERROR, e); LOG.fatal(e); throw new IOException("Error on initial data store read", e); } String[] qry = { "CREATE TABLE overrides (id INT NOT NULL, title VARCHAR(255) NOT NULL, subtitle VARCHAR(255) NOT NULL, PRIMARY KEY(id))", "CREATE TABLE settings (var VARCHAR(32) NOT NULL, val VARCHAR(255) NOT NULL, PRIMARY KEY(var))", "INSERT INTO settings (var, val) VALUES ('schema', '1')" }; try { conn.setAutoCommit(false); stmt = conn.createStatement(); for (String q : qry) stmt.executeUpdate(q); conn.commit(); } catch (SQLException e2) { try { conn.rollback(); } catch (SQLException e3) { LOG.trace(SQL_ERROR, e3); LOG.error(e3); } LOG.trace(SQL_ERROR, e2); throw new IOException("Error initializing data store", e2); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e4) { LOG.trace(SQL_ERROR, e4); LOG.error(e4); throw new IOException("Unable to cleanup data store resources", e4); } } try { conn.setAutoCommit(true); } catch (SQLException e3) { LOG.trace(SQL_ERROR, e3); LOG.error(e3); throw new IOException("Unable to reset data store auto commit", e3); } } } return; }
|
11
|
Code Sample 1:
public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hexString.toString(); }
Code Sample 2:
public static String encrypt(String plaintext) throws Exception { String algorithm = XML.get("security.algorithm"); if (algorithm == null) algorithm = "SHA-1"; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(plaintext.getBytes("UTF-8")); return new BASE64Encoder().encode(md.digest()); }
|
00
|
Code Sample 1:
private void SaveToArchive(Layer layer, String layerFileName) throws Exception { Object archiveObj = layer.getBlackboard().get("ArchiveFileName"); Object entryObj = layer.getBlackboard().get("ArchiveEntryPrefix"); if ((archiveObj == null) || (entryObj == null)) return; String archiveName = archiveObj.toString(); String entryPrefix = entryObj.toString(); if ((archiveName == "") || (entryPrefix == "")) return; File tempZip = File.createTempFile("tmp", ".zip"); InputStream in = new BufferedInputStream(new FileInputStream(archiveName)); OutputStream out = new BufferedOutputStream(new FileOutputStream(tempZip)); copy(in, out); in.close(); out.close(); ZipFile zipFile = new ZipFile(tempZip); ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(archiveName))); ZipInputStream zin = new ZipInputStream(new FileInputStream(tempZip)); ZipEntry entry = zin.getNextEntry(); while (entry != null) { String entryName = entry.getName(); String en = GUIUtil.nameWithoutExtension(new File(entryName)); if (en.equalsIgnoreCase(entryPrefix)) { if (entryName.endsWith(".jmp")) { String layerTaskPath = CreateArchivePlugIn.createLayerTask(layer, archiveName, entryPrefix); CreateArchivePlugIn.WriteZipEntry(layerTaskPath, entryPrefix, zout); } else if ((!entryName.endsWith(".shx")) && (!entryName.endsWith(".dbf")) && (!entryName.endsWith(".shp.xml")) && (!entryName.endsWith(".prj"))) { CreateArchivePlugIn.WriteZipEntry(layerFileName, entryPrefix, zout); } } else { zout.putNextEntry(entry); copy(zin, zout); } entry = zin.getNextEntry(); } zin.close(); zout.close(); zipFile.close(); tempZip.delete(); }
Code Sample 2:
public void show(HttpServletRequest request, HttpServletResponse response, String pantalla, Atributos modelos) { URL url = getRecurso(pantalla); try { IOUtils.copy(url.openStream(), response.getOutputStream()); } catch (IOException e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
public String getWeather(String cityName, String fileAddr) { try { URL url = new URL("http://www.google.com/ig/api?hl=zh_cn&weather=" + cityName); InputStream inputstream = url.openStream(); String s, str; BufferedReader in = new BufferedReader(new InputStreamReader(inputstream)); StringBuffer stringbuffer = new StringBuffer(); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileAddr), "utf-8")); while ((s = in.readLine()) != null) { stringbuffer.append(s); } str = new String(stringbuffer); out.write(str); out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } File file = new File(fileAddr); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); String str = null; try { DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(file); NodeList nodelist1 = (NodeList) doc.getElementsByTagName("forecast_conditions"); NodeList nodelist2 = nodelist1.item(0).getChildNodes(); str = nodelist2.item(4).getAttributes().item(0).getNodeValue() + ",temperature:" + nodelist2.item(1).getAttributes().item(0).getNodeValue() + "℃-" + nodelist2.item(2).getAttributes().item(0).getNodeValue() + "℃"; } catch (Exception e) { e.printStackTrace(); } return str; }
Code Sample 2:
private void loadDateFormats() { String fileToLocate = "/" + FILENAME_DATE_FMT; URL url = getClass().getClassLoader().getResource(fileToLocate); if (url == null) { return; } List<String> lines; try { lines = IOUtils.readLines(url.openStream()); } catch (IOException e) { throw new ConfigurationException("Problem loading file " + fileToLocate, e); } for (String line : lines) { if (line.startsWith("#") || StringUtils.isBlank(line)) { continue; } String[] parts = StringUtils.split(line, "="); addFormat(parts[0], new SimpleDateFormat(parts[1])); } }
|
00
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public static void changeStructure(double version) throws DException { try { Class cl = Class.forName("com.daffodilwoods.daffodildb.server.datadictionarysystem.SystemTablesCreator"); java.net.URL urlw = cl.getResource("/com/daffodilwoods/daffodildb/server/datadictionarysystem/systemtablesStructure.obj"); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(urlw.openStream())); structureMap = (HashMap) ois.readObject(); if (version >= 3.4) { Object[][] columnsTableStructure = (Object[][]) structureMap.get((Object) SystemTables.columns_TableName); columnsTableStructure[9][2] = new Integer(1027); } ois.close(); } catch (IOException ex) { } catch (ClassNotFoundException ex) { } }
|
00
|
Code Sample 1:
public static void createModelZip(String filename, String tempdir) throws EDITSException { try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); } catch (Exception e) { throw new EDITSException("Can not create a model in file " + filename + " from folder " + tempdir); } }
Code Sample 2:
public void fetchFile(String ID) { String url = "http://www.nal.usda.gov/cgi-bin/agricola-ind?bib=" + ID + "&conf=010000++++++++++++++&screen=MA"; System.out.println(url); try { PrintWriter pw = new PrintWriter(new FileWriter("MARC" + ID + ".txt")); if (!id.contains("MARC" + ID + ".txt")) { id.add("MARC" + ID + ".txt"); } in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); in.readLine(); String inputLine, stx = ""; StringBuffer sb = new StringBuffer(); while ((inputLine = in.readLine()) != null) { if (inputLine.startsWith("<TR><TD><B>")) { String sts = (inputLine.substring(inputLine.indexOf("B>") + 2, inputLine.indexOf("</"))); int i = 0; try { i = Integer.parseInt(sts); } catch (NumberFormatException nfe) { } if (i > 0) { stx = stx + "\n" + sts + " - "; } else { stx += sts; } } if (!(inputLine.startsWith("<") || inputLine.startsWith(" <") || inputLine.startsWith(">"))) { String tx = inputLine.trim(); stx += tx; } } pw.println(stx); pw.close(); } catch (Exception e) { System.out.println("Couldn't open stream"); System.out.println(e); } }
|
00
|
Code Sample 1:
private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; }
Code Sample 2:
public boolean loadFile(String inpfile) { if (osmlContainer == null) return false; hApdx.clear(); try { BufferedReader in = null; if (inpfile.indexOf("http://") >= 0) { URL url = null; url = new URL(inpfile); URLConnection conn = url.openConnection(); conn.setUseCaches(false); InputStreamReader is = new InputStreamReader(conn.getInputStream()); in = new BufferedReader(is); } else { in = new BufferedReader(new FileReader(inpfile)); } String pline = null; while ((pline = in.readLine()) != null) { StringTokenizer tok = new StringTokenizer(pline, "\t\n\r"); if (tok.countTokens() < 2) continue; String name = tok.nextToken(); String apdx = tok.nextToken(); String note = ""; if (tok.countTokens() > 0) note = tok.nextToken(); if (name.length() == 0 || apdx.length() == 0) continue; OmicElementContainer element = (OmicElementContainer) OmicElementContainer.createContainer(); element.setName(name); element.setNote(note); element.addAppendix(apdx); String keys[] = commaPattern.split(apdx); for (int j = 0; j < keys.length; j++) { ArrayList v = (ArrayList) hApdx.get(keys[j]); if (v == null) v = new ArrayList(); v.add(element); hApdx.put(keys[j], v); } } in.close(); } catch (MalformedURLException mfe) { System.out.println("MalformedURLException"); return false; } catch (IOException ioe) { System.out.println("IOException"); return false; } System.out.println("appendix name list size " + hApdx.size()); if (bElementDirected) { int nCount = 0; ArrayList<OmicElementContainer> omicElementList = osmlContainer.getAllOmicElementContainers(); for (OmicElementContainer element : omicElementList) { String name = element.getName(); String apdx = element.getAppendix(); if (name.length() == 0) continue; String names[] = commaPattern.split(name); String apdxs[] = commaPattern.split(apdx); String list[] = new String[names.length + apdxs.length]; for (int j = 0; j < names.length; j++) list[j] = names[j]; for (int j = 0; j < apdxs.length; j++) list[j + names.length] = apdxs[j]; for (int j = 0; j < list.length; j++) { ArrayList v = (ArrayList) hApdx.get(list[j]); if (v == null) continue; for (int k = 0; k < v.size(); k++) { OmicElementContainer appendix = (OmicElementContainer) v.get(k); element.addAppendix(appendix.getName()); nCount++; } } } System.out.println("match appendix element " + nCount + " items"); } if (bFunctionDirected) { int nCount = 0; FunctionalClassContainer functions[] = osmlContainer.getFunctionalClassContainer("[@container=all]"); ArrayList vFunction = new ArrayList(); for (int i = 0; i < functions.length; i++) { if (!vFunction.contains(functions[i])) vFunction.add(functions[i]); } for (int i = 0; i < vFunction.size(); i++) { FunctionalClassContainer function = (FunctionalClassContainer) vFunction.get(i); String name = function.getName(); if (name.length() == 0) continue; String names[] = name.split(","); for (int j = 0; j < names.length; j++) { ArrayList v = (ArrayList) hApdx.get(names[j]); if (v == null) continue; for (int k = 0; k < v.size(); k++) { OmicElementContainer appendix = (OmicElementContainer) v.get(k); functions[i].addOmicElementContainer(appendix); nCount++; } } } System.out.println("match appendix function " + nCount + " items"); } return true; }
|
00
|
Code Sample 1:
public static synchronized String hash(String data) { if (digest == null) { try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException nsae) { nsae.printStackTrace(); } } try { digest.update(data.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println(e); } return encodeHex(digest.digest()); }
Code Sample 2:
public int delete(BusinessObject o) throws DAOException { int delete = 0; Contact contact = (Contact) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_CONTACT")); pst.setInt(1, contact.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
|
00
|
Code Sample 1:
protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; }
Code Sample 2:
private void nioBuild() { try { final ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 4); final FileChannel out = new FileOutputStream(dest).getChannel(); for (File part : parts) { setState(part.getName(), BUILDING); FileChannel in = new FileInputStream(part).getChannel(); while (in.read(buffer) > 0) { buffer.flip(); written += out.write(buffer); buffer.clear(); } in.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
private List<String> createProjectInfoFile() throws SocketException, IOException { FTPClient client = new FTPClient(); Set<String> projects = new HashSet<String>(); client.connect("ftp.drupal.org"); System.out.println("Connected to ftp.drupal.org"); System.out.println(client.getReplyString()); boolean loggedIn = client.login("anonymous", "info@regilo.org"); if (loggedIn) { FTPFile[] files = client.listFiles("pub/drupal/files/projects"); for (FTPFile file : files) { String name = file.getName(); Pattern p = Pattern.compile("([a-zAZ_]*)-(\\d.x)-(.*)"); Matcher m = p.matcher(name); if (m.matches()) { String projectName = m.group(1); String version = m.group(2); if (version.equals("6.x")) { projects.add(projectName); } } } } List<String> projectList = new ArrayList<String>(); for (String project : projects) { projectList.add(project); } Collections.sort(projectList); return projectList; }
Code Sample 2:
public static SpeciesTree create(String url) throws IOException { SpeciesTree tree = new SpeciesTree(); tree.setUrl(url); System.out.println("Fetching URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String toParse = null; Properties properties = new Properties(); properties.load(in); String line = properties.getProperty("TREE"); if (line == null) return null; int end = line.indexOf(';'); if (end < 0) end = line.length(); toParse = line.substring(0, end).trim(); System.out.print("Parsing... "); parse(tree, toParse, properties); return tree; }
|
11
|
Code Sample 1:
private void doIt() throws Throwable { int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east)); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } logger.info(backTiles.size() + " tiles to cache"); for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { int i = 4; while (--i > 0) { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) { logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); Thread.sleep(1000L * (long) Math.pow(2, 8 - i)); continue; } in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); break; } else throw new IllegalStateException("opened stream is null"); } } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 10 == 0) { logger.info(numCachedTiles + " tiles cached"); Thread.sleep(sleep); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw e; } }
Code Sample 2:
public static void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
|
00
|
Code Sample 1:
public void run() { if (!shouldLogin) { u.p("skipping the auto-login"); return; } try { u.p("logging in to the server"); String query = "hostname=blahfoo2.com" + "&osname=" + URLEncoder.encode(System.getProperty("os.name"), "UTF-8") + "&javaver=" + URLEncoder.encode(System.getProperty("java.runtime.version"), "UTF-8") + "&timezone=" + URLEncoder.encode(TimeZone.getDefault().getID(), "UTF-8"); u.p("unencoded query: \n" + query); String login_url = "http://joshy.org:8088/org.glossitopeTracker/login.jsp?"; String url = login_url + query; u.p("final encoded url = \n" + url); InputStream in = new URL(url).openStream(); byte[] buf = new byte[256]; while (true) { int n = in.read(buf); if (n == -1) break; for (int i = 0; i < n; i++) { } } } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } }
Code Sample 2:
@Override public String entryToObject(TupleInput input) { boolean zipped = input.readBoolean(); if (!zipped) { return input.readString(); } int len = input.readInt(); try { byte array[] = new byte[len]; input.read(array); GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(array)); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copyTo(in, out); in.close(); out.close(); return new String(out.toByteArray()); } catch (IOException err) { throw new RuntimeException(err); } }
|
11
|
Code Sample 1:
public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } }
Code Sample 2:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
|
11
|
Code Sample 1:
public static String SHA1(String password) throws BusinessException { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(password.getBytes()); BigInteger hash = new BigInteger(1, digest.digest()); return hash.toString(16); } catch (java.security.NoSuchAlgorithmException e) { throw new BusinessException(); } }
Code Sample 2:
public static byte[] md5raw(String data) { try { MessageDigest md = MessageDigest.getInstance(MD); md.update(data.getBytes(UTF8)); return md.digest(); } catch (Exception e) { throw new RuntimeException(e); } }
|
11
|
Code Sample 1:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel sourceChannel = new FileInputStream(in).getChannel(); final FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
private LinkedList<Datum> processDatum(Datum dataset) { ArrayList<Object[]> markerTestResults = new ArrayList<Object[]>(); ArrayList<Object[]> alleleEstimateResults = new ArrayList<Object[]>(); boolean hasAlleleNames = false; String blank = new String(""); MarkerPhenotypeAdapter theAdapter; if (dataset.getDataType().equals(MarkerPhenotype.class)) { theAdapter = new MarkerPhenotypeAdapter((MarkerPhenotype) dataset.getData()); } else theAdapter = new MarkerPhenotypeAdapter((Phenotype) dataset.getData()); int numberOfMarkers = theAdapter.getNumberOfMarkers(); if (numberOfMarkers == 0) { return calculateBLUEsFromPhenotypes(theAdapter, dataset.getName()); } int numberOfCovariates = theAdapter.getNumberOfCovariates(); int numberOfFactors = theAdapter.getNumberOfFactors(); int numberOfPhenotypes = theAdapter.getNumberOfPhenotypes(); int expectedIterations = numberOfPhenotypes * numberOfMarkers; int iterationsSofar = 0; int percentFinished = 0; File tempFile = null; File ftestFile = null; File blueFile = null; BufferedWriter ftestWriter = null; BufferedWriter BLUEWriter = null; String ftestHeader = "Trait\tMarker\tLocus\tLocus_pos\tChr\tChr_pos\tmarker_F\tmarker_p\tperm_p\tmarkerR2\tmarkerDF\tmarkerMS\terrorDF\terrorMS\tmodelDF\tmodelMS"; String BLUEHeader = "Trait\tMarker\tObs\tLocus\tLocus_pos\tChr\tChr_pos\tAllele\tEstimate"; if (writeOutputToFile) { String outputbase = outputName; if (outputbase.endsWith(".txt")) { int index = outputbase.lastIndexOf("."); outputbase = outputbase.substring(0, index); } String datasetNameNoSpace = dataset.getName().trim().replaceAll("\\ ", "_"); ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.txt"); int count = 0; while (ftestFile.exists()) { count++; ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest" + count + ".txt"); } blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs.txt"); count = 0; while (blueFile.exists()) { count++; blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs" + count + ".txt"); } tempFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.tmp"); try { if (permute) { ftestWriter = new BufferedWriter(new FileWriter(tempFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } else { ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } if (reportBLUEs) { BLUEWriter = new BufferedWriter(new FileWriter(blueFile)); BLUEWriter.write(BLUEHeader); BLUEWriter.newLine(); } } catch (IOException e) { myLogger.error("Failed to open file for output"); myLogger.error(e); return null; } } if (permute) { minP = new double[numberOfPhenotypes][numberOfPermutations]; for (int i = 0; i < numberOfPermutations; i++) { for (int j = 0; j < numberOfPhenotypes; j++) { minP[j][i] = 1; } } } for (int ph = 0; ph < numberOfPhenotypes; ph++) { double[] phenotypeData = theAdapter.getPhenotypeValues(ph); boolean[] missing = theAdapter.getMissingPhenotypes(ph); ArrayList<String[]> factorList = MarkerPhenotypeAdapterUtils.getFactorList(theAdapter, ph, missing); ArrayList<double[]> covariateList = MarkerPhenotypeAdapterUtils.getCovariateList(theAdapter, ph, missing); double[][] permutedData = null; if (permute) { permutedData = permuteData(phenotypeData, missing, factorList, covariateList, theAdapter); } for (int m = 0; m < numberOfMarkers; m++) { Object[] markerData = theAdapter.getMarkerValue(ph, m); boolean[] finalMissing = new boolean[missing.length]; System.arraycopy(missing, 0, finalMissing, 0, missing.length); MarkerPhenotypeAdapterUtils.updateMissing(finalMissing, theAdapter.getMissingMarkers(ph, m)); int[] nonmissingRows = MarkerPhenotypeAdapterUtils.getNonMissingIndex(finalMissing); int numberOfObs = nonmissingRows.length; double[] y = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) y[i] = phenotypeData[nonmissingRows[i]]; int firstMarkerAlleleEstimate = 1; ArrayList<ModelEffect> modelEffects = new ArrayList<ModelEffect>(); FactorModelEffect meanEffect = new FactorModelEffect(new int[numberOfObs], false); meanEffect.setID("mean"); modelEffects.add(meanEffect); if (numberOfFactors > 0) { for (int f = 0; f < numberOfFactors; f++) { String[] afactor = factorList.get(f); String[] factorLabels = new String[numberOfObs]; for (int i = 0; i < numberOfObs; i++) factorLabels[i] = afactor[nonmissingRows[i]]; FactorModelEffect fme = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(factorLabels), true, theAdapter.getFactorName(f)); modelEffects.add(fme); firstMarkerAlleleEstimate += fme.getNumberOfLevels() - 1; } } if (numberOfCovariates > 0) { for (int c = 0; c < numberOfCovariates; c++) { double[] covar = new double[numberOfObs]; double[] covariateData = covariateList.get(c); for (int i = 0; i < numberOfObs; i++) covar[i] = covariateData[nonmissingRows[i]]; modelEffects.add(new CovariateModelEffect(covar, theAdapter.getCovariateName(c))); firstMarkerAlleleEstimate++; } } ModelEffect markerEffect; boolean markerIsDiscrete = theAdapter.isMarkerDiscrete(m); ArrayList<Object> alleleNames = new ArrayList<Object>(); if (markerIsDiscrete) { Object[] markers = new Object[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markers[i] = markerData[nonmissingRows[i]]; int[] markerLevels = ModelEffectUtils.getIntegerLevels(markers, alleleNames); markerEffect = new FactorModelEffect(markerLevels, true, theAdapter.getMarkerName(m)); hasAlleleNames = true; } else { double[] markerdbl = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markerdbl[i] = ((Double) markerData[nonmissingRows[i]]).doubleValue(); markerEffect = new CovariateModelEffect(markerdbl, theAdapter.getMarkerName(m)); } int[] alleleCounts = markerEffect.getLevelCounts(); modelEffects.add(markerEffect); int markerEffectNumber = modelEffects.size() - 1; Identifier[] taxaSublist = new Identifier[numberOfObs]; Identifier[] taxa = theAdapter.getTaxa(ph); for (int i = 0; i < numberOfObs; i++) taxaSublist[i] = taxa[nonmissingRows[i]]; boolean areTaxaReplicated = containsDuplicates(taxaSublist); double[] markerSSdf = null, errorSSdf = null, modelSSdf = null; double F, p; double[] beta = null; if (areTaxaReplicated && markerIsDiscrete) { ModelEffect taxaEffect = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(taxaSublist), true); modelEffects.add(taxaEffect); SweepFastNestedModel sfnm = new SweepFastNestedModel(modelEffects, y); double[] taxaSSdf = sfnm.getTaxaInMarkerSSdf(); double[] residualSSdf = sfnm.getErrorSSdf(); markerSSdf = sfnm.getMarkerSSdf(); errorSSdf = sfnm.getErrorSSdf(); modelSSdf = sfnm.getModelcfmSSdf(); F = markerSSdf[0] / markerSSdf[1] / taxaSSdf[0] * taxaSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], taxaSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sfnm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sfnm.getInverseOfXtX(), markerdf); } } else { SweepFastLinearModel sflm = new SweepFastLinearModel(modelEffects, y); modelSSdf = sflm.getModelcfmSSdf(); markerSSdf = sflm.getMarginalSSdf(markerEffectNumber); errorSSdf = sflm.getResidualSSdf(); F = markerSSdf[0] / markerSSdf[1] / errorSSdf[0] * errorSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], errorSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sflm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sflm.getInverseOfXtX(), markerdf); } } if (!filterOutput || p < maxp) { String traitname = theAdapter.getPhenotypeName(ph); if (traitname == null) traitname = blank; String marker = theAdapter.getMarkerName(m); if (marker == null) marker = blank; String locus = theAdapter.getLocusName(m); Integer site = new Integer(theAdapter.getLocusPosition(m)); String chrname = ""; Double chrpos = Double.NaN; if (hasMap) { int ndx = -1; ndx = myMap.getMarkerIndex(marker); if (ndx > -1) { chrname = myMap.getChromosome(ndx); chrpos = myMap.getGeneticPosition(ndx); } } Object[] result = new Object[16]; int col = 0; result[col++] = traitname; result[col++] = marker; result[col++] = locus; result[col++] = site; result[col++] = chrname; result[col++] = chrpos; result[col++] = new Double(F); result[col++] = new Double(p); result[col++] = Double.NaN; result[col++] = new Double(markerSSdf[0] / (modelSSdf[0] + errorSSdf[0])); result[col++] = new Double(markerSSdf[1]); result[col++] = new Double(markerSSdf[0] / markerSSdf[1]); result[col++] = new Double(errorSSdf[1]); result[col++] = new Double(errorSSdf[0] / errorSSdf[1]); result[col++] = new Double(modelSSdf[1]); result[col++] = new Double(modelSSdf[0] / modelSSdf[1]); if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int i = 1; i < 16; i++) sb.append("\t").append(result[i]); try { ftestWriter.write(sb.toString()); ftestWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { markerTestResults.add(result); } int numberOfMarkerAlleles = alleleNames.size(); if (numberOfMarkerAlleles == 0) numberOfMarkerAlleles++; for (int i = 0; i < numberOfMarkerAlleles; i++) { result = new Object[9]; result[0] = traitname; result[1] = marker; result[2] = new Integer(alleleCounts[i]); result[3] = locus; result[4] = site; result[5] = chrname; result[6] = chrpos; if (numberOfMarkerAlleles == 1) result[7] = ""; else result[7] = alleleNames.get(i); if (i == numberOfMarkerAlleles - 1) result[8] = 0.0; else result[8] = beta[firstMarkerAlleleEstimate + i]; if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int j = 1; j < 9; j++) sb.append("\t").append(result[j]); try { BLUEWriter.write(sb.toString()); BLUEWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { alleleEstimateResults.add(result); } } } int tmpPercent = ++iterationsSofar * 100 / expectedIterations; if (tmpPercent > percentFinished) { percentFinished = tmpPercent; fireProgress(percentFinished); } } } fireProgress(0); if (writeOutputToFile) { try { ftestWriter.close(); BLUEWriter.close(); } catch (IOException e) { e.printStackTrace(); } } HashMap<String, Integer> traitnameMap = new HashMap<String, Integer>(); if (permute) { for (int ph = 0; ph < numberOfPhenotypes; ph++) { Arrays.sort(minP[ph]); traitnameMap.put(theAdapter.getPhenotypeName(ph), ph); } if (writeOutputToFile) { try { BufferedReader tempReader = new BufferedReader(new FileReader(tempFile)); ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(tempReader.readLine()); ftestWriter.newLine(); String input; String[] data; Pattern tab = Pattern.compile("\t"); while ((input = tempReader.readLine()) != null) { data = tab.split(input); String trait = data[0]; double pval = Double.parseDouble(data[7]); int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; data[8] = Double.toString((double) ndx / (double) numberOfPermutations); ftestWriter.write(data[0]); for (int i = 1; i < data.length; i++) { ftestWriter.write("\t"); ftestWriter.write(data[i]); } ftestWriter.newLine(); } tempReader.close(); ftestWriter.close(); tempFile.delete(); } catch (IOException e) { myLogger.error(e); } } else { for (Object[] result : markerTestResults) { String trait = result[0].toString(); double pval = (Double) result[7]; int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; result[8] = new Double((double) ndx / (double) numberOfPermutations); } } } String[] columnLabels = new String[] { "Trait", "Marker", "Locus", "Locus_pos", "Chr", "Chr_pos", "marker_F", "marker_p", "perm_p", "markerR2", "markerDF", "markerMS", "errorDF", "errorMS", "modelDF", "modelMS" }; boolean hasMarkerNames = theAdapter.hasMarkerNames(); LinkedList<Integer> outputList = new LinkedList<Integer>(); outputList.add(0); if (hasMarkerNames) outputList.add(1); outputList.add(2); outputList.add(3); if (hasMap) { outputList.add(4); outputList.add(5); } outputList.add(6); outputList.add(7); if (permute) outputList.add(8); for (int i = 9; i < 16; i++) outputList.add(i); LinkedList<Datum> resultset = new LinkedList<Datum>(); int nrows = markerTestResults.size(); Object[][] table = new Object[nrows][]; int numberOfColumns = outputList.size(); String[] colnames = new String[numberOfColumns]; int count = 0; for (Integer ndx : outputList) colnames[count++] = columnLabels[ndx]; for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = markerTestResults.get(i); count = 0; for (Integer ndx : outputList) table[i][count++] = result[ndx]; } StringBuilder tableName = new StringBuilder("GLM_marker_test_"); tableName.append(dataset.getName()); StringBuilder comments = new StringBuilder("Tests of Marker-Phenotype Association"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + ftestFile.getPath()); } TableReport markerTestReport = new SimpleTableReport("Marker Test", colnames, table); resultset.add(new Datum(tableName.toString(), markerTestReport, comments.toString())); int[] outputIndex; columnLabels = new String[] { "Trait", "Marker", "Obs", "Locus", "Locus_pos", "Chr", "Chr_pos", "Allele", "Estimate" }; if (hasAlleleNames) { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 7, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 7, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 7, 8 }; } } else { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 8 }; } } nrows = alleleEstimateResults.size(); table = new Object[nrows][]; numberOfColumns = outputIndex.length; colnames = new String[numberOfColumns]; for (int j = 0; j < numberOfColumns; j++) { colnames[j] = columnLabels[outputIndex[j]]; } for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = alleleEstimateResults.get(i); for (int j = 0; j < numberOfColumns; j++) { table[i][j] = result[outputIndex[j]]; } } tableName = new StringBuilder("GLM allele estimates for "); tableName.append(dataset.getName()); comments = new StringBuilder("Marker allele effect estimates\n"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + blueFile.getPath()); } TableReport alleleEstimateReport = new SimpleTableReport("Allele Estimates", colnames, table); resultset.add(new Datum(tableName.toString(), alleleEstimateReport, comments.toString())); fireProgress(0); return resultset; }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public void copyContent(long mailId1, long mailId2) throws Exception { File file1 = new File(this.getMailDir(mailId1) + "/"); File file2 = new File(this.getMailDir(mailId2) + "/"); this.recursiveDir(file2); if (file1.isDirectory()) { File[] files = file1.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i].isFile()) { File file2s = new File(file2.getAbsolutePath() + "/" + files[i].getName()); if (!file2s.exists()) { file2s.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2s)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(files[i])); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); if (in != null) { try { in.close(); } catch (IOException ex1) { ex1.printStackTrace(); } } if (out != null) { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } } } } }
|
00
|
Code Sample 1:
public FileBean create(MimeTypeBean mimeType, SanBean san) throws SQLException { long fileId = 0; DataSource ds = getDataSource(DEFAULT_DATASOURCE); Connection conn = ds.getConnection(); try { conn.setAutoCommit(false); Statement stmt = conn.createStatement(); stmt.execute(NEXT_FILE_ID); ResultSet rs = stmt.getResultSet(); while (rs.next()) { fileId = rs.getLong(NEXTVAL); } PreparedStatement pstmt = conn.prepareStatement(INSERT_FILE); pstmt.setLong(1, fileId); pstmt.setLong(2, mimeType.getId()); pstmt.setLong(3, san.getId()); pstmt.setLong(4, WORKFLOW_ATTENTE_VALIDATION); int nbrow = pstmt.executeUpdate(); if (nbrow == 0) { throw new SQLException(); } conn.commit(); closeRessources(conn, pstmt); } catch (SQLException e) { log.error("Can't FileDAOImpl.create " + e.getMessage()); conn.rollback(); throw e; } FileBean fileBean = new FileBean(); return fileBean; }
Code Sample 2:
public String loadURLString(java.net.URL url) { try { BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String s = ""; while (br.ready() && s != null) { s = br.readLine(); if (s != null) { buf.append(s); buf.append("\n"); } } return buf.toString(); } catch (IOException ex) { return ""; } catch (NullPointerException npe) { return ""; } }
|
00
|
Code Sample 1:
private static void recurseFiles(File root, File file, TarArchiveOutputStream taos, boolean absolute) throws IOException { if (file.isDirectory()) { File[] files = file.listFiles(); for (File file2 : files) { recurseFiles(root, file2, taos, absolute); } } else if ((!file.getName().endsWith(".tar")) && (!file.getName().endsWith(".TAR"))) { String filename = null; if (absolute) { filename = file.getAbsolutePath().substring(root.getAbsolutePath().length()); } else { filename = file.getName(); } TarArchiveEntry tae = new TarArchiveEntry(filename); tae.setSize(file.length()); taos.putArchiveEntry(tae); FileInputStream fis = new FileInputStream(file); IOUtils.copy(fis, taos); taos.closeArchiveEntry(); } }
Code Sample 2:
public static void writeFromURL(String urlstr, String filename) throws Exception { URL url = new URL(urlstr); InputStream in = url.openStream(); BufferedReader bf = null; StringBuffer sb = new StringBuffer(); try { bf = new BufferedReader(new InputStreamReader(in, "latin1")); String s; while (true) { s = bf.readLine(); if (s != null) { sb.append(s); } else { break; } } } catch (Exception e) { throw e; } finally { bf.close(); } writeRawBytes(sb.toString(), filename); }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
public static String checkPublicIP() { String ipAddress = null; try { URL url; url = new URL("http://checkip.dyndns.org/"); InputStreamReader in = new InputStreamReader(url.openStream()); BufferedReader buffer = new BufferedReader(in); String line; Pattern p = Pattern.compile("\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b"); while ((line = buffer.readLine()) != null) { if (line.indexOf("IP Address:") != -1) { Matcher m = p.matcher(line); if (m.find()) { ipAddress = m.group(); break; } } } buffer.close(); in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ipAddress; }
|
11
|
Code Sample 1:
public boolean copyFile(File source, File dest) { try { FileReader in = new FileReader(source); FileWriter out = new FileWriter(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return true; } catch (Exception e) { return false; } }
Code Sample 2:
public static void writeInputStreamToFile(final InputStream stream, final File target) { long size = 0; FileOutputStream fileOut; try { fileOut = new FileOutputStream(target); size = IOUtils.copyLarge(stream, fileOut); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (log.isInfoEnabled()) { log.info("Wrote " + size + " bytes to " + target.getAbsolutePath()); } else { System.out.println("Wrote " + size + " bytes to " + target.getAbsolutePath()); } }
|
00
|
Code Sample 1:
private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; BOTLRuleDiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((BOTLRuleDiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } }
Code Sample 2:
public static String sendSoapMsg(String SOAPUrl, byte[] b, String SOAPAction) throws IOException { log.finest("HTTP REQUEST SIZE " + b.length); if (SOAPAction.startsWith("\"") == false) SOAPAction = "\"" + SOAPAction + "\""; URL url = new URL(SOAPUrl); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestProperty("SOAPAction", SOAPAction); httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"utf-8\""); httpConn.setRequestProperty("Content-Length", String.valueOf(b.length)); httpConn.setRequestProperty("Cache-Control", "no-cache"); httpConn.setRequestProperty("Pragma", "no-cache"); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); OutputStream out = httpConn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); BufferedReader in = new BufferedReader(isr); StringBuffer response = new StringBuffer(1024); String inputLine; while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); log.finest("HTTP RESPONSE SIZE: " + response.length()); return response.toString(); }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private void zipFiles(File file, File[] fa) throws Exception { File f = new File(file, ALL_FILES_NAME); if (f.exists()) { f.delete(); f = new File(file, ALL_FILES_NAME); } ZipOutputStream zoutstrm = new ZipOutputStream(new FileOutputStream(f)); for (int i = 0; i < fa.length; i++) { ZipEntry zipEntry = new ZipEntry(fa[i].getName()); zoutstrm.putNextEntry(zipEntry); FileInputStream fr = new FileInputStream(fa[i]); byte[] buffer = new byte[1024]; int readCount = 0; while ((readCount = fr.read(buffer)) > 0) { zoutstrm.write(buffer, 0, readCount); } fr.close(); zoutstrm.closeEntry(); } zoutstrm.close(); log("created zip file: " + file.getName() + "/" + ALL_FILES_NAME); }
|
11
|
Code Sample 1:
public void actionPerformed(ActionEvent e) { String digest = null; try { MessageDigest m = MessageDigest.getInstance("sha1"); m.reset(); String pw = String.copyValueOf(this.login.getPassword()); m.update(pw.getBytes()); byte[] digestByte = m.digest(); BigInteger bi = new BigInteger(digestByte); digest = bi.toString(); System.out.println(digest); } catch (NoSuchAlgorithmException e1) { e1.printStackTrace(); } this.model.login(this.login.getHost(), this.login.getPort(), this.login.getUser(), digest); }
Code Sample 2:
public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { if (globali.jcVariabili.DEBUG) globali.jcFunzioni.erroreSQL(ex.toString()); } return res; }
|
00
|
Code Sample 1:
public static void loadPackage1(String ycCode) { InputStream input = null; try { TrustManager[] trustAllCerts = new TrustManager[] { new FakeTrustManager() }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); URL url = Retriever.getPackage1Url(String.valueOf(YouthClub.getMiniModel().getBasics().getTeamId()), ycCode); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection uc = (HttpsURLConnection) url.openConnection(); uc.setHostnameVerifier(new FakeHostnameVerifier()); uc.setConnectTimeout(CONNECTION_TIMEOUT); uc.setReadTimeout(CONNECTION_TIMEOUT); input = uc.getInputStream(); StringBuilder sb = new StringBuilder(); int c; while ((c = input.read()) != -1) { sb.append((char) c); } Document doc = YouthClub.getMiniModel().getXMLParser().parseString(sb.toString()); String target = System.getProperty("user.home") + System.getProperty("file.separator") + "youthclub_" + new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date()) + ".xml"; YouthClub.getMiniModel().getXMLParser().writeXML(doc, target); Debug.log("YC XML saved to " + target); } catch (Exception e) { Debug.logException(e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } }
Code Sample 2:
private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); }
|
11
|
Code Sample 1:
private static void addFolderToZip(File folder, ZipOutputStream zip, String baseName) throws IOException { File[] files = folder.listFiles(); for (File file : files) { if (file.isDirectory()) { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(name + "/"); zip.putNextEntry(zipEntry); zip.closeEntry(); addFolderToZip(file, zip, baseName); } else { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(updateFilename(name)); zip.putNextEntry(zipEntry); IOUtils.copy(new FileInputStream(file), zip); zip.closeEntry(); } } }
Code Sample 2:
public static void copyFile(File srcFile, File dstFile) { logger.info("Create file : " + dstFile.getPath()); try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel dstChannel = new FileOutputStream(dstFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
private void loadHtmlHeader() { String skinUrl = getClass().getResource("/" + Properties.defaultSkinFileName).toString(); if (Properties.headerSkin != null && !Properties.headerSkin.equals("")) { try { URL url = new URL(Properties.headerSkin); if (url.getProtocol().equalsIgnoreCase("http")) { isHttpUrl = true; HttpURLConnection.setFollowRedirects(false); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("HEAD"); boolean urlExists = (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK); if (urlExists) skinUrl = Properties.headerSkin; } else if (url.getProtocol().equalsIgnoreCase("jar")) { String jarFile = Properties.headerSkin.substring(9).split("!")[0]; File skinFile = new File(jarFile); if (skinFile.exists() && skinFile.canRead()) skinUrl = Properties.headerSkin; } else if (url.getProtocol().equalsIgnoreCase("file")) { File skinFile = new File(Properties.headerSkin.substring(5)); if (skinFile.exists() && skinFile.canRead()) skinUrl = Properties.headerSkin; } else { File skinFile = new File(Properties.headerSkin); if (skinFile.exists() && skinFile.canRead()) skinUrl = Properties.headerSkin; } } catch (Exception ex) { XohmLogger.debugPrintln("Header skin url not valid. " + ex.getMessage()); XohmLogger.debugPrintln("Loading the default skin."); ex.printStackTrace(); } } XohmLogger.debugPrintln("Header skin file = " + skinUrl); try { LocalHtmlRendererContext rendererContext = new LocalHtmlRendererContext(htmlHeaderPanel, new SimpleUserAgentContext()); rendererContext.navigate(skinUrl); headerLoaded = true; } catch (IOException urlEx) { XohmLogger.debugPrintln("Exception occured while loading the skin. " + urlEx.getMessage()); } }
Code Sample 2:
protected InputStream transform(URL url) throws IOException { TransformerFactory tf = TransformerFactory.newInstance(); InputStream xsl_is = null; InputStream url_is = null; ByteArrayOutputStream os = null; byte[] output; try { xsl_is = Classes.getThreadClassLoader().getResourceAsStream(getStylesheet()); url_is = new BufferedInputStream(url.openStream()); os = new ByteArrayOutputStream(); Transformer tr = tf.newTransformer(new StreamSource(xsl_is)); tr.transform(new StreamSource(url_is), new StreamResult(os)); output = os.toByteArray(); } catch (TransformerConfigurationException tce) { throw new IOException(tce.getLocalizedMessage()); } catch (TransformerException te) { throw new IOException(te.getLocalizedMessage()); } finally { try { if (os != null) os.close(); } catch (Throwable t) { } try { if (url_is != null) url_is.close(); } catch (Throwable t) { } try { if (xsl_is != null) xsl_is.close(); } catch (Throwable t) { } } if (logService.isEnabledFor(LogLevel.TRACE)) logService.log(LogLevel.TRACE, new String(output)); return new ByteArrayInputStream(output); }
|
11
|
Code Sample 1:
public int procesar() { int mas = 0; String uriOntologia = "", source = "", uri = ""; String fichOrigenHTML = "", fichOrigenLN = ""; String ficheroOutOWL = ""; md5 firma = null; StringTokenV2 entra = null, entra2 = null, entra3 = null; FileInputStream lengNat = null; BufferedInputStream lengNat2 = null; DataInputStream entradaLenguajeNatural = null; FileWriter salOWL = null; BufferedWriter salOWL2 = null; PrintWriter salidaOWL = null; String sujeto = "", verbo = "", CD = "", CI = "", fraseOrigen = ""; StringTokenV2 token2; boolean bandera = false; OntClass c = null; OntClass cBak = null; String claseTrabajo = ""; String nombreClase = "", nombrePropiedad = "", variasPalabras = ""; int incre = 0, emergencia = 0; String lineaSalida = ""; String[] ontologia = new String[5]; ontologia[0] = "http://www.criado.info/owl/vertebrados_es.owl#"; ontologia[1] = "http://www.w3.org/2001/sw/WebOnt/guide-src/wine#"; ontologia[2] = "http://www.co-ode.org/ontologies/pizza/2005/10/18/pizza.owl#"; ontologia[3] = "http://www.w3.org/2001/sw/WebOnt/guide-src/food#"; ontologia[4] = "http://www.daml.org/2001/01/gedcom/gedcom#"; String[] ontologiaSource = new String[5]; ontologiaSource[0] = this.directorioMapeo + "\\" + "mapeo_vertebrados_es.xml"; ontologiaSource[1] = this.directorioMapeo + "\\" + "mapeo_wine_es.xml"; ontologiaSource[2] = this.directorioMapeo + "\\" + "mapeo_pizza_es.xml"; ontologiaSource[3] = this.directorioMapeo + "\\" + "mapeo_food_es.xml"; ontologiaSource[4] = this.directorioMapeo + "\\" + "mapeo_parentesco_es.xml"; mapeoIdiomas clasesOntologias; try { if ((entrada = entradaFichero.readLine()) != null) { if (entrada.trim().length() > 10) { entrada2 = new StringTokenV2(entrada.trim(), "\""); if (entrada2.isIncluidaSubcadena("<fichero ontologia=")) { ontologiaOrigen = entrada2.getToken(2); fichOrigenHTML = entrada2.getToken(4); fichOrigenLN = entrada2.getToken(6); if (ontologiaOrigen.equals("VERTEBRADOS")) { source = ontologiaSource[0]; uriOntologia = ontologia[0]; } if (ontologiaOrigen.equals("WINE")) { source = ontologiaSource[1]; uriOntologia = ontologia[1]; } if (ontologiaOrigen.equals("PIZZA")) { source = ontologiaSource[2]; uriOntologia = ontologia[2]; } if (ontologiaOrigen.equals("FOOD")) { source = ontologiaSource[3]; uriOntologia = ontologia[3]; } if (ontologiaOrigen.equals("PARENTESCOS")) { source = ontologiaSource[4]; uriOntologia = ontologia[4]; } firma = new md5(uriOntologia, false); clasesOntologias = new mapeoIdiomas(source); uri = ""; ficheroOutOWL = ""; entra2 = new StringTokenV2(fichOrigenHTML, "\\"); int numToken = entra2.getNumeroTokenTotales(); entra = new StringTokenV2(fichOrigenHTML, " "); if (entra.isIncluidaSubcadena(directorioLocal)) { entra = new StringTokenV2(entra.getQuitar(directorioLocal) + "", " "); uri = entra.getCambiar("\\", "/"); uri = entra.getQuitar(entra2.getToken(numToken)) + ""; entra3 = new StringTokenV2(entra2.getToken(numToken), "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; uri = urlPatron + uri + ficheroOutOWL; } entra3 = new StringTokenV2(fichOrigenHTML, "."); ficheroOutOWL = entra3.getToken(1) + "_" + firma.toString() + ".owl"; lineaSalida = "<vistasemantica origen=\"" + fichOrigenLN + "\" destino=\"" + uri + "\" />"; lengNat = new FileInputStream(fichOrigenLN); lengNat2 = new BufferedInputStream(lengNat); entradaLenguajeNatural = new DataInputStream(lengNat2); salOWL = new FileWriter(ficheroOutOWL); salOWL2 = new BufferedWriter(salOWL); salidaOWL = new PrintWriter(salOWL2); while ((entradaInstancias = entradaLenguajeNatural.readLine()) != null) { sujeto = ""; verbo = ""; CD = ""; CI = ""; fraseOrigen = ""; if (entradaInstancias.trim().length() > 10) { entrada2 = new StringTokenV2(entradaInstancias.trim(), "\""); if (entrada2.isIncluidaSubcadena("<oracion sujeto=")) { sujeto = entrada2.getToken(2).trim(); verbo = entrada2.getToken(4).trim(); CD = entrada2.getToken(6).trim(); CI = entrada2.getToken(8).trim(); fraseOrigen = entrada2.getToken(10).trim(); if (sujeto.length() > 0 & verbo.length() > 0 & CD.length() > 0) { bandera = false; c = null; cBak = null; nombreClase = clasesOntologias.getClaseInstancia(CD); if (nombreClase.length() > 0) { bandera = true; } if (bandera) { if (incre == 0) { salidaOWL.write(" <rdf:RDF " + "\n"); salidaOWL.write(" xmlns:j.0=\"" + uriOntologia + "\"" + "\n"); salidaOWL.write(" xmlns:protege=\"http://protege.stanford.edu/plugins/owl/protege#\"" + "\n"); salidaOWL.write(" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"" + "\n"); salidaOWL.write(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema#\"" + "\n"); salidaOWL.write(" xmlns:rdfs=\"http://www.w3.org/2000/01/rdf-schema#\"" + "\n"); salidaOWL.write(" xmlns:owl=\"http://www.w3.org/2002/07/owl#\" " + "\n"); salidaOWL.write(" xmlns=\"" + uri + "#\"" + "\n"); salidaOWL.write(" xml:base=\"" + uri + "\">" + "\n"); salidaOWL.write(" <owl:Ontology rdf:about=\"\">" + "\n"); salidaOWL.write(" <owl:imports rdf:resource=\"" + uriOntologia + "\"/>" + "\n"); salidaOWL.write(" </owl:Ontology>" + "\n"); salidaOWL.flush(); salida.write(lineaSalida + "\n"); salida.flush(); incre = 1; } salidaOWL.write(" <j.0:" + nombreClase + " rdf:ID=\"" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" <owl:AllDifferent>" + "\n"); salidaOWL.write(" <owl:distinctMembers rdf:parseType=\"Collection\">" + "\n"); salidaOWL.write(" <" + nombreClase + " rdf:about=\"#" + sujeto.toUpperCase() + "\"/>" + "\n"); salidaOWL.write(" </owl:distinctMembers>" + "\n"); salidaOWL.write(" </owl:AllDifferent>" + "\n"); salidaOWL.flush(); bandera = false; } } } } } salidaOWL.write(" </rdf:RDF>" + "\n" + "\n"); salidaOWL.write("<!-- Creado por [html2ws] http://www.luis.criado.org -->" + "\n"); salidaOWL.flush(); } } mas = 1; } else { salida.write("</listaVistasSemanticas>\n"); salida.flush(); salida.close(); bw2.close(); fw2.close(); salidaOWL.close(); entradaFichero.close(); ent2.close(); ent1.close(); mas = -1; } } catch (Exception e) { mas = -2; salida.write("No se encuentra: " + fichOrigen + "\n"); salida.flush(); } return mas; }
Code Sample 2:
public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } }
|
11
|
Code Sample 1:
@Before public void setUp() throws IOException { testSbk = File.createTempFile("songbook", "sbk"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("test.sbk"), new FileOutputStream(testSbk)); test1Sbk = File.createTempFile("songbook", "sbk"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("test1.sbk"), new FileOutputStream(test1Sbk)); }
Code Sample 2:
@Override public void save(File folder) { actInstance = instance; this.setProperty(EsomMapper.PROPERTY_INSTANCE, String.valueOf(actInstance)); log.debug("instance: " + this.getProperty(EsomMapper.PROPERTY_INSTANCE)); if (this.getProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED) == EsomMapper.RADIO_LOAD_SELECTED) { File src = new File(this.getProperty(EsomMapper.PROPERTY_LRN_FILE)); if (src.getParent() != folder.getPath()) { log.debug("saving lrn file in save folder " + folder.getPath()); File dst = new File(folder.getAbsolutePath() + File.separator + src.getName() + String.valueOf(actInstance)); try { FileReader fr = new FileReader(src); BufferedReader br = new BufferedReader(fr); dst.createNewFile(); FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); int i = 0; while ((i = br.read()) != -1) bw.write(i); bw.flush(); bw.close(); br.close(); fr.close(); } catch (FileNotFoundException e) { log.error("Error while opening lrn sourcefile! Saving wasn't possible!!!"); e.printStackTrace(); } catch (IOException e) { log.error("Error while creating lrn destfile! Creating wasn't possible!!!"); e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_LRN_FILE, dst.getName()); log.debug("done saving lrn file"); } } if (this.getProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED) == EsomMapper.RADIO_LOAD_SELECTED) { File src = new File(this.getProperty(EsomMapper.PROPERTY_WTS_FILE)); if (src.getParent() != folder.getPath()) { log.debug("saving wts file in save folder " + folder.getPath()); File dst = new File(folder.getAbsolutePath() + File.separator + src.getName() + String.valueOf(actInstance)); try { FileReader fr = new FileReader(src); BufferedReader br = new BufferedReader(fr); dst.createNewFile(); FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); int i = 0; while ((i = br.read()) != -1) bw.write(i); bw.flush(); bw.close(); br.close(); fr.close(); } catch (FileNotFoundException e) { log.error("Error while opening wts sourcefile! Saving wasn't possible!!!"); e.printStackTrace(); } catch (IOException e) { log.error("Error while creating wts destfile! Creating wasn't possible!!!"); e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_WTS_FILE, dst.getName()); log.debug("done saving wts file"); } } if (this.getProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED) == EsomMapper.RADIO_SELECT_FROM_DATANAV_SELECTED) { this.setProperty(EsomMapper.PROPERTY_LRN_FILE, "EsomMapper" + this.actInstance + ".lrn"); File dst = new File(folder + File.separator + this.getProperty(EsomMapper.PROPERTY_LRN_FILE)); try { FileWriter fw = new FileWriter(dst); BufferedWriter bw = new BufferedWriter(fw); bw.write("# EsomMapper LRN save file\n"); bw.write("% " + this.inputVectors.getNumRows() + "\n"); bw.write("% " + this.inputVectors.getNumCols() + "\n"); bw.write("% 9"); for (IColumn col : this.inputVectors.getColumns()) { if (col.getType() == IClusterNumber.class) bw.write("\t2"); else if (col.getType() == String.class) bw.write("\t8"); else bw.write("\t1"); } bw.write("\n% Key"); for (IColumn col : this.inputVectors.getColumns()) { bw.write("\t" + col.getLabel()); } bw.write("\n"); int keyIterator = 0; for (Vector<Object> row : this.inputVectors.getGrid()) { bw.write(this.inputVectors.getKey(keyIterator++).toString()); for (Object point : row) bw.write("\t" + point.toString()); bw.write("\n"); } bw.flush(); fw.flush(); bw.close(); fw.close(); } catch (IOException e) { e.printStackTrace(); } this.setProperty(EsomMapper.PROPERTY_LRN_RADIO_SELECTED, EsomMapper.RADIO_LOAD_SELECTED); } if (this.getProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED) == EsomMapper.RADIO_SELECT_FROM_DATANAV_SELECTED) { this.setProperty(EsomMapper.PROPERTY_WTS_FILE, "EsomMapper" + this.actInstance + ".wts"); MyRetina tempRetina = new MyRetina(this.outputRetina.getNumRows(), this.outputRetina.getNumCols(), this.outputRetina.getDim(), this.outputRetina.getDistanceFunction(), this.outputRetina.isToroid()); for (int row = 0; row < this.outputRetina.getNumRows(); row++) { for (int col = 0; col < this.outputRetina.getNumCols(); col++) { for (int dim = 0; dim < this.outputRetina.getDim(); dim++) { tempRetina.setNeuron(row, col, dim, this.outputRetina.getPointasDoubleArray(row, col)[dim]); } } } EsomIO.writeWTSFile(folder + File.separator + this.getProperty(EsomMapper.PROPERTY_WTS_FILE), tempRetina); this.setProperty(EsomMapper.PROPERTY_WTS_RADIO_SELECTED, EsomMapper.RADIO_LOAD_SELECTED); } EsomMapper.instance++; }
|
00
|
Code Sample 1:
private void verifyAvailability() { for (int i = 0; i < servers.size(); i++) { String hostEntry = (String) servers.get(i); String hostString = hostEntry.substring(0, hostEntry.indexOf(":")); String portString = hostEntry.substring(hostEntry.indexOf(":") + 1); String urlLocation = "http://" + hostString + ":" + portString + "/"; String urlData = null; String urlMatch = null; long startTime = System.currentTimeMillis(); URL url = null; HttpURLConnection conn = null; InputStream istream = null; if (serverRequests.get(hostEntry) != null) { String requestData = (String) serverRequests.get(hostEntry); urlData = requestData.substring(0, requestData.indexOf("\t")); try { urlMatch = requestData.substring(requestData.indexOf("\t") + 1); } catch (Exception e) { urlMatch = null; } urlLocation = "http://" + hostString + ":" + portString + "/" + urlData; } try { url = new URL(urlLocation); conn = (HttpURLConnection) url.openConnection(); } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e.getMessage()); serverTimes.put(hostEntry, "0"); continue; } try { istream = conn.getInputStream(); } catch (Exception e) { try { if (conn.getResponseCode() != 401) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception ee) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': " + e); serverTimes.put(hostEntry, "0"); continue; } } int response = 501; try { response = conn.getResponseCode(); if (response != 200 && response != 401) { System.err.println("*** Warning: Connection to host '" + hostEntry + "' returns response: " + response); serverTimes.put(hostEntry, "0"); continue; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostString + "' on port '" + portString + "'"); serverTimes.put(hostEntry, "0"); continue; } if (response != 401) { int contentLength = conn.getContentLength(); if (contentLength == -1) { contentLength = 4096; } byte data[] = new byte[contentLength]; int curPos = 0; try { int dataRead = 0; while ((dataRead = istream.read(data, curPos, contentLength - curPos)) != -1) { if (dataRead == 0) { break; } curPos += dataRead; } } catch (Exception e) { System.err.println("*** Warning: Unable to contact host '" + hostEntry + "': Cannot read response from site."); serverTimes.put(hostEntry, "0"); continue; } if (urlMatch != null) { String urlContents = new String(data); data = null; if (urlContents.indexOf(urlMatch) == -1) { System.err.println("*** Warning: Host '" + hostEntry + "' does not match search string. Reports '" + urlContents + "'"); try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverTimes.put(hostEntry, "0"); continue; } } } try { istream.close(); conn.disconnect(); } catch (Exception e) { } serverStatus.put(hostEntry, "1"); String timeResponse = Long.toString(System.currentTimeMillis() - startTime); Debug.log("Response time for '" + hostEntry + "' is " + timeResponse + " ms."); serverTimes.put(hostEntry, timeResponse); } }
Code Sample 2:
public void gzip(File from, File to) { OutputStream out_zip = null; ArchiveOutputStream os = null; try { try { out_zip = new FileOutputStream(to); os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out_zip); os.putArchiveEntry(new ZipArchiveEntry(from.getName())); IOUtils.copy(new FileInputStream(from), os); os.closeArchiveEntry(); } finally { if (os != null) { os.close(); } } out_zip.close(); } catch (IOException ex) { fatal("IOException", ex); } catch (ArchiveException ex) { fatal("ArchiveException", ex); } }
|
00
|
Code Sample 1:
protected void givenGroupRepository(String repoId, String providerId, Repository... memberRepos) throws AuthenticationException, UnsupportedEncodingException, IOException, ClientProtocolException { HttpResponse response = executeDeleteWithResponse(format("/repo_groups/%s", repoId)); consume(response.getEntity()); final StringEntity content = new StringEntity(format("{data:{id: '%s', name: '%s', provider: '%s', exposed: true, repositories: [%s]}}", repoId, repoId, providerId, render(memberRepos))); response = executePost("/repo_groups", content, new BasicHeader("Content-Type", "application/json")); consume(response.getEntity()); assertThat(response.getStatusLine().getStatusCode(), is(201)); }
Code Sample 2:
public static String toMD5String(String plainText) { if (TextUtils.isEmpty(plainText)) { plainText = ""; } StringBuilder text = new StringBuilder(); for (int i = plainText.length() - 1; i >= 0; i--) { text.append(plainText.charAt(i)); } plainText = text.toString(); MessageDigest mDigest; try { mDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return plainText; } mDigest.update(plainText.getBytes()); byte d[] = mDigest.digest(); StringBuffer hash = new StringBuffer(); for (int i = 0; i < d.length; i++) { hash.append(Integer.toHexString(0xFF & d[i])); } return hash.toString(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.