label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
00
|
Code Sample 1:
public static void main(String args[]) { int summ = 0; int temp = 0; int[] a1 = { 0, 6, -7, -7, 61, 8, 20, 0, 8, 3, 6, 2, 7, 99, 0, 23, 12, 7, 9, 5, 33, 1, 3, 99, 99, 61, 99, 99, 99, 61, 61, 61, -3, -3, -3, -3 }; for (int j = 0; j < (a1.length * a1.length); j++) { for (int i = 0; i < a1.length - 1; i++) { if (a1[i] > a1[i + 1]) { temp = a1[i]; a1[i] = a1[i + 1]; a1[i + 1] = temp; } } } for (int i = 0; i < a1.length; i++) { System.out.print(" " + a1[i]); } int min = 0; int max = 0; summ = (a1[1]) + (a1[a1.length - 1]); for (int i = 0; i < a1.length; i++) { if (a1[i] > a1[0] && a1[i] != a1[0]) { min = a1[i]; break; } } for (int i = a1.length - 1; i > 0; i--) { if (a1[i] < a1[a1.length - 1] & a1[i] != a1[a1.length - 1]) { max = a1[i]; break; } } System.out.println(); System.out.print("summa 2 min N 2 max = " + summ); System.out.println(min); System.out.println(max); System.out.println("summa 2 min N 2 max = " + (min + max)); }
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(); } }
|
11
|
Code Sample 1:
private void sendFile(File file, HttpServletResponse response) throws IOException { response.setContentLength((int) file.length()); InputStream inputStream = null; try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, response.getOutputStream()); } finally { IOUtils.closeQuietly(inputStream); } }
Code Sample 2:
public static boolean copyFile(File sourceFile, File destFile) throws IOException { long flag = 0; if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); flag = destination.transferFrom(source, 0, source.size()); } catch (Exception e) { Logger.getLogger(FileUtils.class.getPackage().getName()).log(Level.WARNING, "ERROR: Problem copying file", e); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } if (flag == 0) return false; else return true; }
|
11
|
Code Sample 1:
@Override public void copy(final String fileName) throws FileIOException { final long savedCurrentPositionInFile = currentPositionInFile; if (opened) { closeImpl(); } final FileInputStream fis; try { fis = new FileInputStream(file); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + file, file, exception); } final File destinationFile = new File(fileName); final FileOutputStream fos; try { fos = new FileOutputStream(destinationFile); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + destinationFile, destinationFile, exception); } try { final byte[] buf = new byte[1024]; int readLength = 0; while ((readLength = fis.read(buf)) != -1) { fos.write(buf, 0, readLength); } } catch (IOException exception) { throw HELPER_FILE_UTIL.fileIOException("failed copy from " + file + " to " + destinationFile, null, exception); } finally { try { if (fis != null) { fis.close(); } } catch (Exception exception) { } try { if (fos != null) { fos.close(); } } catch (Exception exception) { } } if (opened) { openImpl(); seek(savedCurrentPositionInFile); } }
Code Sample 2:
private String sendMessage(HttpURLConnection connection, String reqMessage) throws IOException { if (msgLog.isTraceEnabled()) msgLog.trace("Outgoing SOAPMessage\n" + reqMessage); BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream()); out.write(reqMessage.getBytes("UTF-8")); out.close(); InputStream inputStream = null; if (connection.getResponseCode() < 400) inputStream = connection.getInputStream(); else inputStream = connection.getErrorStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); IOUtils.copyStream(baos, inputStream); inputStream.close(); String response = new String(baos.toByteArray(), "UTF-8"); if (msgLog.isTraceEnabled()) msgLog.trace("Incoming Response SOAPMessage\n" + response); return response; }
|
11
|
Code Sample 1:
private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } }
Code Sample 2:
public Object downloadFile(File destinationFile, URL[] urls, DownloadListener listener, Object checksum, long length, PRIORITY priority) throws DownloadException { URL url = urls[0]; if (!url.getProtocol().equalsIgnoreCase("http")) { throw new DownloadException(" Only HTTP is supported in this version "); } if (!destinationFile.exists()) { try { destinationFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); throw new DownloadException("Unable to download from URL : " + url.toString()); } } HeadMethod head = new HeadMethod(url.toString()); HttpClient httpClient = new HttpClient(); try { httpClient.executeMethod(head); Header[] headers = head.getResponseHeaders(); for (Header header : headers) { System.out.println(header); } Header header = head.getResponseHeader("Content-Length"); Object contentLength = header.getValue(); Long fileLength = Long.parseLong(contentLength.toString()); System.out.println(length + " : " + fileLength); GetMethod get = new GetMethod(url.toString()); httpClient.executeMethod(get); InputStream ins = get.getResponseBodyAsStream(); FileOutputStream fos = new FileOutputStream(destinationFile); IOUtils.copy(ins, fos); System.out.println(" DOWNLOADED FILE"); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public void test5() { try { SocketAddress proxyAddress = new InetSocketAddress("127.0.0.1", 8080); Proxy proxy = new Proxy(Type.HTTP, proxyAddress); URL url = new URL("http://woodstock.net.br:8443"); URLConnection connection = url.openConnection(proxy); InputStream inputStream = connection.getInputStream(); Scanner scanner = new Scanner(inputStream); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public static String genDigest(String info) { MessageDigest alga; byte[] digesta = null; try { alga = MessageDigest.getInstance("SHA-1"); alga.update(info.getBytes()); digesta = alga.digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return byte2hex(digesta); }
|
00
|
Code Sample 1:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); try { String content = ""; URL url = new URL(request.getParameter("url")); URLConnection connection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { content += line + "\n"; } in.close(); String result = getResult(content); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.println(result); } catch (Exception e) { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(getErrorPage(e)); } }
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 void retrieveAttachments(RemoteAttachment[] attachments, String id, String projectName, String key, SimpleDateFormat formatter, java.sql.Connection connect) { if (attachments.length != 0) { for (RemoteAttachment attachment : attachments) { attachmentAuthor = attachment.getAuthor(); if (attachment.getCreated() != null) { attachmentCreated = formatter.format(attachment.getCreated().getTime()); } attachmentFileName = attachment.getFilename(); attachmentFileSize = attachment.getFilesize(); attachmentId = attachment.getId(); attachmentMimeType = attachment.getMimetype(); if (attachmentMimeType.startsWith("text")) { URL attachmentUrl; try { attachmentUrl = new URL("https://issues.apache.org/jira/secure/attachment/" + attachmentId + "/" + attachmentFileName); urlConnection = (HttpURLConnection) attachmentUrl.openConnection(); urlConnection.connect(); serverCode = urlConnection.getResponseCode(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (serverCode == 200) { actual = new File("../attachments/" + projectName + "/" + key); if (!actual.exists()) { actual.mkdirs(); } attachmentPath = "../attachments/" + projectName + "/" + key + "/" + attachmentFileName; BufferedInputStream bis; try { bis = new BufferedInputStream(urlConnection.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(attachmentPath)); byte[] b = new byte[1024]; int len = -1; while ((len = bis.read(b)) != -1) { if (len == 1024) { bos.write(b); } else { bos.write(b, 0, len); } } bos.close(); bis.close(); insertAttachment(connect, id); } catch (IOException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } } } } }
Code Sample 2:
public static String crypt(String target) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(target.getBytes("UTF-16")); BigInteger res = new BigInteger(1, md.digest(key.getBytes())); return res.toString(16); }
|
11
|
Code Sample 1:
@Override public void doHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String directURL = request.getRequestURL().toString(); response.setCharacterEncoding("gbk"); PrintWriter out = response.getWriter(); try { directURL = urlTools.urlFilter(directURL, true); URL url = new URL(directURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "gbk")); String line; while ((line = in.readLine()) != null) { out.println(line); } in.close(); } catch (Exception e) { out.println("file not find"); } out.flush(); }
Code Sample 2:
public JythonWrapperAction(AActionBO.ActionDTO dto, URL url) throws IOException { super(dto); InputStream in = url.openStream(); InputStreamReader rin = new InputStreamReader(in); BufferedReader reader = new BufferedReader(rin); StringBuffer s = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { s.append(str); s.append("\n"); } in.close(); script = s.toString(); }
|
11
|
Code Sample 1:
@Override public CasAssembly build() { try { prepareForBuild(); File casWorkingDirectory = casFile.getParentFile(); DefaultCasFileReadIndexToContigLookup read2contigMap = new DefaultCasFileReadIndexToContigLookup(); AbstractDefaultCasFileLookup readIdLookup = new DefaultReadCasFileLookup(casWorkingDirectory); CasParser.parseOnlyMetaData(casFile, MultipleWrapper.createMultipleWrapper(CasFileVisitor.class, read2contigMap, readIdLookup)); ReadWriteDirectoryFileServer consedOut = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); long startTime = DateTimeUtils.currentTimeMillis(); int numberOfCasContigs = read2contigMap.getNumberOfContigs(); for (long i = 0; i < numberOfCasContigs; i++) { File outputDir = consedOut.createNewDir("" + i); Command aCommand = new Command(new File("fakeCommand")); aCommand.setOption("-casId", "" + i); aCommand.setOption("-cas", commandLine.getOptionValue("cas")); aCommand.setOption("-o", outputDir.getAbsolutePath()); aCommand.setOption("-tempDir", tempDir.getAbsolutePath()); aCommand.setOption("-prefix", "temp"); if (commandLine.hasOption("useIllumina")) { aCommand.addFlag("-useIllumina"); } if (commandLine.hasOption("useClosureTrimming")) { aCommand.addFlag("-useClosureTrimming"); } if (commandLine.hasOption("trim")) { aCommand.setOption("-trim", commandLine.getOptionValue("trim")); } if (commandLine.hasOption("trimMap")) { aCommand.setOption("-trimMap", commandLine.getOptionValue("trimMap")); } if (commandLine.hasOption("chromat_dir")) { aCommand.setOption("-chromat_dir", commandLine.getOptionValue("chromat_dir")); } submitSingleCasAssemblyConversion(aCommand); } waitForAllAssembliesToFinish(); int numContigs = 0; int numReads = 0; for (int i = 0; i < numberOfCasContigs; i++) { File countMap = consedOut.getFile(i + "/temp.counts"); Scanner scanner = new Scanner(countMap); if (!scanner.hasNextInt()) { throw new IllegalStateException("single assembly conversion # " + i + " did not complete"); } numContigs += scanner.nextInt(); numReads += scanner.nextInt(); scanner.close(); } System.out.println("num contigs =" + numContigs); System.out.println("num reads =" + numReads); consedOut.createNewDir("edit_dir"); consedOut.createNewDir("phd_dir"); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; OutputStream masterAceOut = new FileOutputStream(consedOut.createNewFile("edit_dir/" + prefix + ".ace.1")); OutputStream masterPhdOut = new FileOutputStream(consedOut.createNewFile("phd_dir/" + prefix + ".phd.ball")); OutputStream masterConsensusOut = new FileOutputStream(consedOut.createNewFile(prefix + ".consensus.fasta")); OutputStream logOut = new FileOutputStream(consedOut.createNewFile(prefix + ".log")); try { masterAceOut.write(String.format("AS %d %d%n", numContigs, numReads).getBytes()); for (int i = 0; i < numberOfCasContigs; i++) { InputStream aceIn = consedOut.getFileAsStream(i + "/temp.ace"); IOUtils.copy(aceIn, masterAceOut); InputStream phdIn = consedOut.getFileAsStream(i + "/temp.phd"); IOUtils.copy(phdIn, masterPhdOut); InputStream consensusIn = consedOut.getFileAsStream(i + "/temp.consensus.fasta"); IOUtils.copy(consensusIn, masterConsensusOut); IOUtil.closeAndIgnoreErrors(aceIn, phdIn, consensusIn); File tempDir = consedOut.getFile(i + ""); IOUtil.recursiveDelete(tempDir); } consedOut.createNewSymLink("../phd_dir/" + prefix + ".phd.ball", "edit_dir/phd.ball"); if (commandLine.hasOption("chromat_dir")) { consedOut.createNewDir("chromat_dir"); File originalChromatDir = new File(commandLine.getOptionValue("chromat_dir")); for (File chromat : originalChromatDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".scf"); } })) { File newChromatFile = consedOut.createNewFile("chromat_dir/" + FilenameUtils.getBaseName(chromat.getName())); FileOutputStream newChromat = new FileOutputStream(newChromatFile); InputStream in = new FileInputStream(chromat); IOUtils.copy(in, newChromat); IOUtil.closeAndIgnoreErrors(in, newChromat); } } System.out.println("finished making casAssemblies"); for (File traceFile : readIdLookup.getFiles()) { final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!consedOut.contains("solexa_dir")) { consedOut.createNewDir("solexa_dir"); } if (consedOut.contains("solexa_dir/" + name)) { IOUtil.delete(consedOut.getFile("solexa_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!consedOut.contains("sff_dir")) { consedOut.createNewDir("sff_dir"); } if (consedOut.contains("sff_dir/" + name)) { IOUtil.delete(consedOut.getFile("sff_dir/" + name)); } consedOut.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } long endTime = DateTimeUtils.currentTimeMillis(); logOut.write(String.format("took %s%n", new Period(endTime - startTime)).getBytes()); } finally { IOUtil.closeAndIgnoreErrors(masterAceOut, masterPhdOut, masterConsensusOut, logOut); } } catch (Exception e) { handleException(e); } finally { cleanup(); } return null; }
Code Sample 2:
@Override public void close() throws IOException { super.close(); byte[] signatureData = toByteArray(); ZipOutputStream zipOutputStream = new ZipOutputStream(this.targetOutputStream); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(this.originalZipFile)); ZipEntry zipEntry; while (null != (zipEntry = zipInputStream.getNextEntry())) { if (!zipEntry.getName().equals(ASiCUtil.SIGNATURE_FILE)) { ZipEntry newZipEntry = new ZipEntry(zipEntry.getName()); zipOutputStream.putNextEntry(newZipEntry); LOG.debug("copying " + zipEntry.getName()); IOUtils.copy(zipInputStream, zipOutputStream); } } zipInputStream.close(); zipEntry = new ZipEntry(ASiCUtil.SIGNATURE_FILE); LOG.debug("writing " + zipEntry.getName()); zipOutputStream.putNextEntry(zipEntry); IOUtils.write(signatureData, zipOutputStream); zipOutputStream.close(); }
|
11
|
Code Sample 1:
@Test public void testWriteAndReadBigger() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwrite.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[body.length()]; int readCount = in.read(buffer); in.close(); assertEquals(body.length(), readCount); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
Code Sample 2:
private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } }
|
00
|
Code Sample 1:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("Copy: no such source file: " + fromFileName); if (!fromFile.canRead()) throw new IOException("Copy: source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("Copy: destination file is unwriteable: " + toFileName); if (JOptionPane.showConfirmDialog(null, "Overwrite File ?", "Overwrite File", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) return; } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("Copy: destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("Copy: destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("Copy: destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
protected String doIt() throws java.lang.Exception { StringBuffer sql = null; int no = 0; String clientCheck = " AND AD_Client_ID=" + m_AD_Client_ID; String[] strFields = new String[] { "Value", "Name", "Description", "DocumentNote", "Help", "UPC", "SKU", "Classification", "ProductType", "Discontinued", "DiscontinuedBy", "ImageURL", "DescriptionURL" }; for (int i = 0; i < strFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFields[i]).append(" = (SELECT ").append(strFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + strFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFields[i] + " - default from existing Product=" + no); } } String[] numFields = new String[] { "C_UOM_ID", "M_Product_Category_ID", "Volume", "Weight", "ShelfWidth", "ShelfHeight", "ShelfDepth", "UnitsPerPallet", "M_Product_Family_ID" }; for (int i = 0; i < numFields.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFields[i]).append(" = (SELECT ").append(numFields[i]).append(" FROM M_Product p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product p WHERE " + numFields[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFields[i] + " default from existing Product=" + no); } } String[] strFieldsPO = new String[] { "UPC", "PriceEffective", "VendorProductNo", "VendorCategory", "Manufacturer", "Discontinued", "DiscontinuedBy" }; for (int i = 0; i < strFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(strFieldsPO[i]).append(" = (SELECT ").append(strFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + strFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + strFieldsPO[i] + " default from existing Product PO=" + no); } } String[] numFieldsPO = new String[] { "C_UOM_ID", "C_Currency_ID", "RoyaltyAmt", "Order_Min", "Order_Pack", "CostPerOrder", "DeliveryTime_Promised" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND EXISTS (SELECT * FROM M_Product_PO p WHERE " + numFieldsPO[i] + " IS NOT NULL AND p.M_Product_ID = i.M_Product_ID AND i.AD_Client_ID=p.AD_Client_ID)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } numFieldsPO = new String[] { "PriceList", "PricePO" }; for (int i = 0; i < numFieldsPO.length; i++) { sql = new StringBuffer("UPDATE I_PRODUCT i " + "SET ").append(numFieldsPO[i]).append(" = (SELECT ").append(numFieldsPO[i]).append(" FROM M_Product_PO p" + " WHERE i.M_Product_ID=p.M_Product_ID AND i.C_BPartner_ID=p.C_BPartner_ID AND i.AD_Client_ID=p.AD_Client_ID) " + "WHERE M_Product_ID IS NOT NULL AND C_BPartner_ID IS NOT NULL" + " AND (").append(numFieldsPO[i]).append(" IS NULL OR ").append(numFieldsPO[i]).append("=0)" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - " + numFieldsPO[i] + " default from existing Product PO=" + no); } } sql = new StringBuffer("UPDATE I_Product i " + "SET X12DE355 = " + "(SELECT X12DE355 FROM C_UOM u WHERE u.IsDefault='Y' AND u.AD_Client_ID IN (0,i.AD_Client_ID) AND ROWNUM=1) " + "WHERE X12DE355 IS NULL AND C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set UOM Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_UOM_ID = (SELECT C_UOM_ID FROM C_UOM u WHERE u.X12DE355=i.X12DE355 AND u.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set UOM=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid UOM, ' " + "WHERE C_UOM_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid UOM=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET ProductCategory_Value=(SELECT Value FROM M_Product_Category" + " WHERE IsDefault='Y' AND AD_Client_ID=").append(m_AD_Client_ID).append(" AND ROWNUM=1) " + "WHERE ProductCategory_Value IS NULL AND M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Category Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET M_Product_Category_ID=(SELECT M_Product_Category_ID FROM M_Product_Category c" + " WHERE i.ProductCategory_Value=c.Value AND i.AD_Client_ID=c.AD_Client_ID) " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - Set Category=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProdCategorty,' " + "WHERE M_Product_Category_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Category=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET ISO_Code=(SELECT ISO_Code FROM C_Currency c" + " INNER JOIN C_AcctSchema a ON (a.C_Currency_ID=c.C_Currency_ID)" + " INNER JOIN AD_ClientInfo fo ON (a.C_AcctSchema_ID=fo.C_AcctSchema1_ID)" + " WHERE fo.AD_Client_ID=i.AD_Client_ID) " + "WHERE C_Currency_ID IS NULL AND ISO_Code IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.fine("doIt - Set Currency Default=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET C_Currency_ID=(SELECT C_Currency_ID FROM C_Currency c" + " WHERE i.ISO_Code=c.ISO_Code AND c.AD_Client_ID IN (0,i.AD_Client_ID)) " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt- Set Currency=" + no); sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Currency,' " + "WHERE C_Currency_ID IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid Currency=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Invalid ProductType,' " + "WHERE ProductType NOT IN ('I','S')" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.fine("doIt - Invalid ProductType=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=Value not unique,' " + "WHERE I_IsImported<>'Y'" + " AND Value IN (SELECT Value FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY Value HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique Value=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=UPC not unique,' " + "WHERE I_IsImported<>'Y'" + " AND UPC IN (SELECT UPC FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY UPC HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique UPC=" + no); } sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Mandatory Value,' " + "WHERE Value IS NULL" + " AND I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - No Mandatory Value=" + no); } sql = new StringBuffer("UPDATE I_Product " + "SET VendorProductNo=Value " + "WHERE C_BPartner_ID IS NOT NULL AND VendorProductNo IS NULL" + " AND I_IsImported='N'").append(clientCheck); no = DB.executeUpdate(sql.toString()); log.info("doIt - VendorProductNo Set to Value=" + no); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=VendorProductNo not unique,' " + "WHERE I_IsImported<>'Y'" + " AND C_BPartner_ID IS NOT NULL" + " AND (C_BPartner_ID, VendorProductNo) IN " + " (SELECT C_BPartner_ID, VendorProductNo FROM I_Product pr WHERE i.AD_Client_ID=pr.AD_Client_ID GROUP BY C_BPartner_ID, VendorProductNo HAVING COUNT(*) > 1)").append(clientCheck); no = DB.executeUpdate(sql.toString()); if (no != 0) { log.warning("doIt - Not Unique VendorProductNo=" + no); } int C_TaxCategory_ID = 0; try { PreparedStatement pstmt = DB.prepareStatement("SELECT C_TaxCategory_ID FROM C_TaxCategory WHERE IsDefault='Y'" + clientCheck); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { C_TaxCategory_ID = rs.getInt(1); } rs.close(); pstmt.close(); } catch (SQLException e) { throw new Exception("doIt - TaxCategory", e); } log.fine("doIt - C_TaxCategory_ID=" + C_TaxCategory_ID); int noInsert = 0; int noUpdate = 0; int noInsertPO = 0; int noUpdatePO = 0; log.fine("doIt - start inserting/updating ..."); sql = new StringBuffer("SELECT I_Product_ID, M_Product_ID, C_BPartner_ID " + "FROM I_Product WHERE I_IsImported='N'").append(clientCheck); Connection conn = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED); try { PreparedStatement pstmt_insertProduct = conn.prepareStatement("INSERT INTO M_Product (M_Product_ID," + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,IsSummary,M_Product_Category_ID,C_TaxCategory_ID," + "ProductType,ImageURL,DescriptionURL,M_Product_Family_ID) " + "SELECT ?," + "AD_Client_ID,AD_Org_ID,'Y',CURRENT_TIMESTAMP,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "Value,Name,Description,DocumentNote,Help," + "UPC,SKU,C_UOM_ID,'N',M_Product_Category_ID," + C_TaxCategory_ID + "," + "ProductType,ImageURL,DescriptionURL,M_Product_Category_ID " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_updateProduct = conn.prepareStatement("UPDATE M_PRODUCT " + "SET Value=aux.value" + ",Name=aux.Name" + ",Description=aux.Description" + ",DocumentNote=aux.DocumentNote" + ",Help=aux.Help" + ",UPC=aux.UPC" + ",SKU=aux.SKU" + ",C_UOM_ID=aux.C_UOM_ID" + ",M_Product_Category_ID=aux.M_Product_Category_ID" + ",Classification=aux.Classification" + ",ProductType=aux.ProductType" + ",Volume=aux.Volume" + ",Weight=aux.Weight" + ",ShelfWidth=aux.ShelfWidth" + ",ShelfHeight=aux.ShelfHeight" + ",ShelfDepth=aux.ShelfDepth" + ",UnitsPerPallet=aux.UnitsPerPallet" + ",Discontinued=aux.Discontinued" + ",DiscontinuedBy=aux.DiscontinuedBy" + ",Updated=current_timestamp" + ",UpdatedBy=aux.UpdatedBy" + " from (SELECT Value,Name,Description,DocumentNote,Help,UPC,SKU,C_UOM_ID,M_Product_Category_ID,Classification,ProductType,Volume,Weight,ShelfWidth,ShelfHeight,ShelfDepth,UnitsPerPallet,Discontinued,DiscontinuedBy,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux" + " WHERE M_Product_ID=?"); PreparedStatement pstmt_updateProductPO = conn.prepareStatement("UPDATE M_Product_PO " + "SET IsCurrentVendor='Y'" + ",C_UOM_ID=aux1.C_UOM_ID" + ",C_Currency_ID=aux1.C_Currency_ID" + ",UPC=aux1.UPC" + ",PriceList=aux1.PriceList" + ",PricePO=aux1.PricePO" + ",RoyaltyAmt=aux1.RoyaltyAmt" + ",PriceEffective=aux1.PriceEffective" + ",VendorProductNo=aux1.VendorProductNo" + ",VendorCategory=aux1.VendorCategory" + ",Manufacturer=aux1.Manufacturer" + ",Discontinued=aux1.Discontinued" + ",DiscontinuedBy=aux1.DiscontinuedBy" + ",Order_Min=aux1.Order_Min" + ",Order_Pack=aux1.Order_Pack" + ",CostPerOrder=aux1.CostPerOrder" + ",DeliveryTime_Promised=aux1.DeliveryTime_Promised" + ",Updated=current_timestamp" + ",UpdatedBy=aux1.UpdatedBy" + " from (SELECT 'Y',C_UOM_ID,C_Currency_ID,UPC,PriceList,PricePO,RoyaltyAmt,PriceEffective,VendorProductNo,VendorCategory,Manufacturer,Discontinued,DiscontinuedBy,Order_Min,Order_Pack,CostPerOrder,DeliveryTime_Promised,UpdatedBy FROM I_Product WHERE I_Product_ID=?) as aux1" + " WHERE M_Product_ID=? AND C_BPartner_ID=?"); PreparedStatement pstmt_insertProductPO = conn.prepareStatement("INSERT INTO M_Product_PO (M_Product_ID,C_BPartner_ID, " + "AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy," + "IsCurrentVendor,C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised) " + "SELECT ?,?, " + "AD_Client_ID,AD_Org_ID,'Y',d,CreatedBy,CURRENT_TIMESTAMP,UpdatedBy," + "'Y',C_UOM_ID,C_Currency_ID,UPC," + "PriceList,PricePO,RoyaltyAmt,PriceEffective," + "VendorProductNo,VendorCategory,Manufacturer," + "Discontinued,DiscontinuedBy,Order_Min,Order_Pack," + "CostPerOrder,DeliveryTime_Promised " + "FROM I_Product " + "WHERE I_Product_ID=?"); PreparedStatement pstmt_setImported = conn.prepareStatement("UPDATE I_Product SET I_IsImported='Y', M_Product_ID=?, " + "Updated=CURRENT_TIMESTAMP, Processed='Y' WHERE I_Product_ID=?"); PreparedStatement pstmt = DB.prepareStatement(sql.toString()); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { int I_Product_ID = rs.getInt(1); int M_Product_ID = rs.getInt(2); int C_BPartner_ID = rs.getInt(3); boolean newProduct = M_Product_ID == 0; log.fine("I_Product_ID=" + I_Product_ID + ", M_Product_ID=" + M_Product_ID + ", C_BPartner_ID=" + C_BPartner_ID); if (newProduct) { M_Product_ID = DB.getNextID(m_AD_Client_ID, "M_Product", null); pstmt_insertProduct.setInt(1, M_Product_ID); pstmt_insertProduct.setInt(2, I_Product_ID); try { no = pstmt_insertProduct.executeUpdate(); log.finer("Insert Product = " + no); noInsert++; } catch (SQLException ex) { log.warning("Insert Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } else { pstmt_updateProduct.setInt(1, I_Product_ID); pstmt_updateProduct.setInt(2, M_Product_ID); try { no = pstmt_updateProduct.executeUpdate(); log.finer("Update Product = " + no); noUpdate++; } catch (SQLException ex) { log.warning("Update Product - " + ex.toString()); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (C_BPartner_ID != 0) { no = 0; if (!newProduct) { pstmt_updateProductPO.setInt(1, I_Product_ID); pstmt_updateProductPO.setInt(2, M_Product_ID); pstmt_updateProductPO.setInt(3, C_BPartner_ID); try { no = pstmt_updateProductPO.executeUpdate(); log.finer("Update Product_PO = " + no); noUpdatePO++; } catch (SQLException ex) { log.warning("Update Product_PO - " + ex.toString()); noUpdate--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Update Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } if (no == 0) { pstmt_insertProductPO.setInt(1, M_Product_ID); pstmt_insertProductPO.setInt(2, C_BPartner_ID); pstmt_insertProductPO.setInt(3, I_Product_ID); try { no = pstmt_insertProductPO.executeUpdate(); log.finer("Insert Product_PO = " + no); noInsertPO++; } catch (SQLException ex) { log.warning("Insert Product_PO - " + ex.toString()); noInsert--; conn.rollback(); sql = new StringBuffer("UPDATE I_Product i " + "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||").append(DB.TO_STRING("Insert Product_PO: " + ex.toString())).append("WHERE I_Product_ID=").append(I_Product_ID); DB.executeUpdate(sql.toString()); continue; } } } pstmt_setImported.setInt(1, M_Product_ID); pstmt_setImported.setInt(2, I_Product_ID); no = pstmt_setImported.executeUpdate(); conn.commit(); } rs.close(); pstmt.close(); pstmt_insertProduct.close(); pstmt_updateProduct.close(); pstmt_insertProductPO.close(); pstmt_updateProductPO.close(); pstmt_setImported.close(); conn.close(); conn = null; } catch (SQLException e) { try { if (conn != null) { conn.close(); } conn = null; } catch (SQLException ex) { } log.log(Level.SEVERE, "doIt", e); throw new Exception("doIt", e); } finally { if (conn != null) { conn.close(); } conn = null; } sql = new StringBuffer("UPDATE I_Product " + "SET I_IsImported='N', Updated=CURRENT_TIMESTAMP " + "WHERE I_IsImported<>'Y'").append(clientCheck); no = DB.executeUpdate(sql.toString()); StringBuffer infoReturn = new StringBuffer(""); infoReturn.append("<tr><td>@Errors@</td><td>").append(no).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Inserted@</td><td>").append(noInsert).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@: @Updated@</td><td>").append(noUpdate).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Inserted@</td><td>").append(noInsertPO).append("</td></tr>"); infoReturn.append("<tr><td>@M_Product_ID@ @Purchase@: @Updated@</td><td>").append(noUpdatePO).append("</td></tr>"); return infoReturn.toString(); }
|
00
|
Code Sample 1:
@Override public void actionPerformed(ActionEvent event) { if (event.getSource() == btnChange) { Error.log(7002, "Bot�o alterar pressionado por " + login + "."); if (new String(passwordUser1.getPassword()).compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo senha requerido"); passwordUser1.setFocusable(true); return; } String password1 = new String(passwordUser1.getPassword()); String password2 = new String(passwordUser2.getPassword()); if (password1.compareTo(password2) != 0) { JOptionPane.showMessageDialog(null, "Senhas n�o casam"); passwordUser1.setText(""); passwordUser2.setText(""); passwordUser1.setFocusable(true); return; } char c = passwordUser1.getPassword()[0]; int j = 1; for (j = 1; j < password1.length(); j++) { if (passwordUser1.getPassword()[j] != c) { break; } c = passwordUser1.getPassword()[j]; } if (j == password1.length()) { JOptionPane.showMessageDialog(null, "Senha fraca"); return; } if (password1.length() < 6) { JOptionPane.showMessageDialog(null, "Senha deve ter mais que 6 digitos"); return; } if (numPasswordOneUseUser.getText().compareTo("") == 0) { JOptionPane.showMessageDialog(null, "Campo n�mero de senhas de uso �nico requerido"); return; } if (!(Integer.parseInt(numPasswordOneUseUser.getText()) > 0 && Integer.parseInt(numPasswordOneUseUser.getText()) < 41)) { JOptionPane.showMessageDialog(null, "N�mero de senhas de uso �nico entre 1 e 40"); return; } String outputDigest = ""; try { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(password1.getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); outputDigest = bigInt.toString(16); } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } Statement stmt; String sql; sql = "update Usuarios set password = '" + outputDigest + "' where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } sql = "delete from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r; Vector<Integer> passwordVector = new Vector<Integer>(); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < Integer.parseInt(numPasswordOneUseUser.getText()); i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } JOptionPane.showMessageDialog(null, "Usu�rio " + login + " foi alterado com sucesso."); dispose(); } if (event.getSource() == btnCancel) { Error.log(7003, "Bot�o voltar de alterar para o menu principal pressionado por " + login + "."); dispose(); } }
Code Sample 2:
public void writeTo(OutputStream out) throws IOException { if (!closed) { throw new IOException("Stream not closed"); } if (isInMemory()) { memoryOutputStream.writeTo(out); } else { FileInputStream fis = new FileInputStream(outputFile); try { IOUtils.copy(fis, out); } finally { IOUtils.closeQuietly(fis); } } }
|
11
|
Code Sample 1:
public Object construct() { String fullName = lRegatta.getSaveDirectory() + lRegatta.getSaveName(); System.out.println(MessageFormat.format(res.getString("MainMessageBackingUp"), new Object[] { fullName + BAK })); try { FileInputStream fis = new FileInputStream(new File(fullName)); FileOutputStream fos = new FileOutputStream(new File(fullName + BAK)); int bufsize = 1024; byte[] buffer = new byte[bufsize]; int n = 0; while ((n = fis.read(buffer, 0, bufsize)) >= 0) fos.write(buffer, 0, n); fos.flush(); fos.close(); } catch (java.io.IOException ex) { Util.showError(ex, true); } return null; }
Code Sample 2:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.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) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
public static void copyFile(File source, File destination) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
00
|
Code Sample 1:
static void test() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; Savepoint sp = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); st = conn.createStatement(); String sql = "update user set money=money-10 where id=1"; st.executeUpdate(sql); sp = conn.setSavepoint(); sql = "update user set money=money-10 where id=3"; st.executeUpdate(sql); sql = "select money from user where id=2"; rs = st.executeQuery(sql); float money = 0.0f; if (rs.next()) { money = rs.getFloat("money"); } if (money > 300) throw new RuntimeException("�Ѿ��������ֵ��"); sql = "update user set money=money+10 where id=2"; st.executeUpdate(sql); conn.commit(); } catch (RuntimeException e) { if (conn != null && sp != null) { conn.rollback(sp); conn.commit(); } throw e; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { JdbcUtils.free(rs, st, conn); } }
Code Sample 2:
protected String getPostRequestContent(String urlText, String postParam) throws Exception { URL url = new URL(urlText); HttpURLConnection urlcon = (HttpURLConnection) url.openConnection(); urlcon.setRequestMethod("POST"); urlcon.setUseCaches(false); urlcon.setDoOutput(true); PrintStream ps = new PrintStream(urlcon.getOutputStream()); ps.print(postParam); ps.close(); urlcon.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlcon.getInputStream())); String line = reader.readLine(); reader.close(); urlcon.disconnect(); return line; }
|
00
|
Code Sample 1:
public QueryOutput run() throws Exception { boolean success = false; QueryOutput output = null; if (correlator != null || inMemMaster != null || customMatcher != null) { List<Object[]> rows = inMemMaster == null ? (correlator == null ? customMatcher.onCycleEnd() : correlator.onCycleEnd()) : inMemMaster.onCycleEnd(); if (rows.isEmpty()) { success = true; return null; } output = new DirectQueryOutput(rows); } else { connection = queryContext.createConnection(); try { connection.setAutoCommit(false); connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); thePreparedStatement = connection.prepareStatement(thePreparedStatementSQL); RowStatusHelper.setStatusValues(statusAndPositions, thePreparedStatement, queryContext.getRunCount()); long newResultIdsAfter = lastRowIdInsertedNow; int rows = thePreparedStatement.executeUpdate(); if (rows <= 0) { success = true; return null; } lastRowIdInsertedNow = getLastRowIdInResultTable(newResultIdsAfter, rows); output = new DBQueryOutput(newResultIdsAfter, lastRowIdInsertedNow, rows, timeKeeper.getTimeMsecs()); success = true; } finally { if (connection != null) { if (success) { connection.commit(); } else { connection.rollback(); } } } } return output; }
Code Sample 2:
public String getSource(String urlAdd) throws Exception { HttpURLConnection urlConnection = null; URL url = new URL(urlAdd); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(timeout); if (!urlConnection.getContentType().contains("text/html")) { throw new Exception(); } if (urlConnection.getResponseCode() != 200) { throw new Exception(); } encoding = getPageEncoding(urlConnection); if (encoding == null) { encoding = defaultEncoding; } InputStream in = url.openStream(); byte[] buffer = new byte[12288]; StringBuffer sb = new StringBuffer(); int bytesRead = 0; while ((bytesRead = in.read(buffer)) != -1) { String reads = new String(buffer, 0, bytesRead, encoding); sb.append(reads); } in.close(); return sb.toString(); }
|
00
|
Code Sample 1:
private static void copyFile(String src, String dest) { try { File inputFile = new File(src); File outputFile = new File(dest); FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); FileChannel inc = in.getChannel(); FileChannel outc = out.getChannel(); inc.transferTo(0, inc.size(), outc); inc.close(); outc.close(); in.close(); out.close(); } catch (Exception e) { } }
Code Sample 2:
public void doGet(HttpServletRequest request_, HttpServletResponse response) throws IOException, ServletException { Writer out = null; DatabaseAdapter dbDyn = null; PreparedStatement st = null; try { RenderRequest renderRequest = null; RenderResponse renderResponse = null; ContentTypeTools.setContentType(response, ContentTypeTools.CONTENT_TYPE_UTF8); out = response.getWriter(); AuthSession auth_ = (AuthSession) renderRequest.getUserPrincipal(); if (auth_ == null) { throw new IllegalStateException("You have not enough right to execute this operation"); } PortletSession session = renderRequest.getPortletSession(); dbDyn = DatabaseAdapter.getInstance(); String index_page = PortletService.url("mill.price.index", renderRequest, renderResponse); Long id_shop = null; if (renderRequest.getParameter(ShopPortlet.NAME_ID_SHOP_PARAM) != null) { id_shop = PortletService.getLong(renderRequest, ShopPortlet.NAME_ID_SHOP_PARAM); } else { Long id_ = (Long) session.getAttribute(ShopPortlet.ID_SHOP_SESSION); if (id_ == null) { response.sendRedirect(index_page); return; } id_shop = id_; } session.removeAttribute(ShopPortlet.ID_SHOP_SESSION); session.setAttribute(ShopPortlet.ID_SHOP_SESSION, id_shop); if (auth_.isUserInRole("webmill.edit_price_list")) { Long id_item = PortletService.getLong(renderRequest, "id_item"); if (id_item == null) throw new IllegalArgumentException("id_item not initialized"); if (RequestTools.getString(renderRequest, "action").equals("update")) { dbDyn.getConnection().setAutoCommit(false); String sql_ = "delete from WM_PRICE_ITEM_DESCRIPTION a " + "where exists " + " ( select null from WM_PRICE_LIST b " + " where b.id_shop = ? and b.id_item = ? and " + " a.id_item=b.id_item ) "; try { st = dbDyn.prepareStatement(sql_); RsetTools.setLong(st, 1, id_shop); RsetTools.setLong(st, 2, id_item); st.executeUpdate(); } catch (Exception e0001) { dbDyn.rollback(); out.write("Error #1 - " + ExceptionTools.getStackTrace(e0001, 20, "<br>")); return; } finally { DatabaseManager.close(st); st = null; } sql_ = "insert into WM_PRICE_ITEM_DESCRIPTION " + "(ID_PRICE_ITEM_DESCRIPTION, ID_ITEM, TEXT)" + "(select seq_WM_PRICE_ITEM_DESCRIPTION.nextval, ID_ITEM, ? " + " from WM_PRICE_LIST b where b.ID_SHOP = ? and b.ID_ITEM = ? )"; try { int idx = 0; int offset = 0; int j = 0; byte[] b = StringTools.getBytesUTF(RequestTools.getString(renderRequest, "n")); st = dbDyn.prepareStatement(sql_); while ((idx = StringTools.getStartUTF(b, 2000, offset)) != -1) { st.setString(1, new String(b, offset, idx - offset, "utf-8")); RsetTools.setLong(st, 2, id_shop); RsetTools.setLong(st, 3, id_item); st.addBatch(); offset = idx; if (j > 10) break; j++; } int[] updateCounts = st.executeBatch(); if (log.isDebugEnabled()) log.debug("Number of updated records - " + updateCounts); dbDyn.commit(); } catch (Exception e0) { dbDyn.rollback(); out.write("Error #2 - " + ExceptionTools.getStackTrace(e0, 20, "<br>")); return; } finally { dbDyn.getConnection().setAutoCommit(true); if (st != null) { DatabaseManager.close(st); st = null; } } } if (RequestTools.getString(renderRequest, "action").equals("new_image") && renderRequest.getParameter("id_image") != null) { Long id_image = PortletService.getLong(renderRequest, "id_image"); dbDyn.getConnection().setAutoCommit(false); String sql_ = "delete from WM_IMAGE_PRICE_ITEMS a " + "where exists " + " ( select null from WM_PRICE_LIST b " + "where b.id_shop = ? and b.id_item = ? and " + "a.id_item=b.id_item ) "; try { st = dbDyn.prepareStatement(sql_); RsetTools.setLong(st, 1, id_shop); RsetTools.setLong(st, 2, id_item); st.executeUpdate(); } catch (Exception e0001) { dbDyn.rollback(); out.write("Error #3 - " + ExceptionTools.getStackTrace(e0001, 20, "<br>")); return; } finally { DatabaseManager.close(st); st = null; } sql_ = "insert into WM_IMAGE_PRICE_ITEMS " + "(id_IMAGE_PRICE_ITEMS, id_item, ID_IMAGE_DIR)" + "(select seq_WM_IMAGE_PRICE_ITEMS.nextval, id_item, ? " + " from WM_PRICE_LIST b where b.id_shop = ? and b.id_item = ? )"; try { st = dbDyn.prepareStatement(sql_); RsetTools.setLong(st, 1, id_image); RsetTools.setLong(st, 2, id_shop); RsetTools.setLong(st, 3, id_item); int updateCounts = st.executeUpdate(); if (log.isDebugEnabled()) log.debug("Number of updated records - " + updateCounts); dbDyn.commit(); } catch (Exception e0) { dbDyn.rollback(); log.error("Error insert image", e0); out.write("Error #4 - " + ExceptionTools.getStackTrace(e0, 20, "<br>")); return; } finally { dbDyn.getConnection().setAutoCommit(true); DatabaseManager.close(st); st = null; } } if (true) throw new Exception("Need refactoring"); } } catch (Exception e) { log.error(e); out.write(ExceptionTools.getStackTrace(e, 20, "<br>")); } finally { DatabaseManager.close(dbDyn, st); st = null; dbDyn = null; } }
|
11
|
Code Sample 1:
private String getPlayerName(String id) throws UnsupportedEncodingException, IOException { String result = ""; Map<String, String> players = (Map<String, String>) sc.getAttribute("players"); if (players.containsKey(id)) { result = players.get(id); System.out.println("skip name:" + result); } else { String palyerURL = "http://goal.2010worldcup.163.com/player/" + id + ".html"; URL url = new URL(palyerURL); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "utf-8")); String line = null; String nameFrom = "英文名:"; String nameTo = "</dd>"; while ((line = reader.readLine()) != null) { if (line.indexOf(nameFrom) != -1) { result = line.substring(line.indexOf(nameFrom) + nameFrom.length(), line.indexOf(nameTo)); break; } } reader.close(); players.put(id, result); } return result; }
Code Sample 2:
@Override public void doHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String directURL = request.getRequestURL().toString(); response.setCharacterEncoding("gbk"); PrintWriter out = response.getWriter(); try { directURL = urlTools.urlFilter(directURL, true); URL url = new URL(directURL); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "gbk")); String line; while ((line = in.readLine()) != null) { out.println(line); } in.close(); } catch (Exception e) { out.println("file not find"); } out.flush(); }
|
00
|
Code Sample 1:
public static String getSHA1Hash(String plainText) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA1"); md.update(plainText.getBytes()); byte[] mdbytes = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < mdbytes.length; i++) { String hex = Integer.toHexString(0xFF & mdbytes[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString().toUpperCase(); }
Code Sample 2:
public JSONObject executeJSON(final String path, final JSONObject jsRequest) throws IOException, HttpException, JSONException { final HttpPost httpRequest = newHttpPost(path); httpRequest.setHeader("Content-Type", "application/json"); final String request = jsRequest.toString(); httpRequest.setEntity(new StringEntity(request)); final HttpResponse httpResponse = executeHttp(httpRequest); final String response = EntityUtils.toString(httpResponse.getEntity()); return new JSONObject(response); }
|
00
|
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 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(); }
|
11
|
Code Sample 1:
private static MapEntry<String, Properties> loadFpmConf() throws ConfigurationReadException { MapEntry<String, Properties> ret = null; Scanner sc = new Scanner(CONF_PATHS).useDelimiter(SEP_P); String prev = ""; while (sc.hasNext() && !hasLoaded) { Properties fpmConf = null; boolean relative = false; String path = sc.next(); if (path.startsWith(PREV_P)) { path = path.replace(PREV_P, prev.substring(0, prev.length() - 1)); } else if (path.startsWith(REL_P)) { path = path.replace(REL_P + FS, ""); relative = true; } else if (path.contains(HOME_P)) { path = path.replace(HOME_P, USER_HOME); } prev = path; path = path.concat(MAIN_CONF_FILE); try { InputStream is = null; if (relative) { is = ClassLoader.getSystemResourceAsStream(path); path = getSystemConfDir(); Strings.getOne().createPath(path); path += MAIN_CONF_FILE; FileOutputStream os = new FileOutputStream(path); IOUtils.copy(is, os); os.flush(); os.close(); os = null; } else { is = new FileInputStream(path); } fpmConf = new Properties(); fpmConf.load(is); if (fpmConf.isEmpty()) { throw new ConfigurationReadException(); } ret = new MapEntry<String, Properties>(path, fpmConf); hasLoaded = true; } catch (FileNotFoundException e) { fpmConf = null; singleton = null; hasLoaded = false; } catch (IOException e) { throw new ConfigurationReadException(); } } return ret; }
Code Sample 2:
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!"); }
|
00
|
Code Sample 1:
private void loadDBpediaOntology() { try { URL url = new URL("http://downloads.dbpedia.org/3.6/dbpedia_3.6.owl.bz2"); InputStream is = new BufferedInputStream(url.openStream()); CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is); dbPediaOntology = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(in); reasoner = PelletReasonerFactory.getInstance().createNonBufferingReasoner(dbPediaOntology); reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (CompressorException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
Code Sample 2:
public void afficherMetar(String oaci) { if (oaci.length() != 4) { System.out.println("un code METAR est composé de 4 caracteres"); } oaci.toUpperCase(); try { URL url = new URL("http://weather.noaa.gov/pub/data/observations/metar/stations/" + oaci + ".TXT"); System.out.println(url.toString()); Proxy acReunion = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.ac-reunion.fr", 8080)); HttpURLConnection con = (HttpURLConnection) url.openConnection(acReunion); InputStreamReader isr = new InputStreamReader(con.getInputStream()); BufferedReader in = new BufferedReader(isr); Vector vListe = new Vector(); String line; System.out.println("Affichage METAR"); System.out.println("--------"); while ((line = in.readLine()) != null) { System.out.println(line); vListe.add(line); } System.out.println("--------"); in.close(); } catch (java.io.FileNotFoundException e) { System.out.println("Impossible de trouver le METAR"); System.out.println(e); } catch (Exception e) { System.out.println(e.toString()); } }
|
11
|
Code Sample 1:
private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
private void handleSSI(HttpData data) throws HttpError, IOException { File tempFile = TempFileHandler.getTempFile(); FileOutputStream out = new FileOutputStream(tempFile); BufferedReader in = new BufferedReader(new FileReader(data.realPath)); String[] env = getEnvironmentVariables(data); if (ssi == null) { ssi = new BSssi(); } ssi.addEnvironment(env); if (data.resp == null) { SimpleResponse resp = new SimpleResponse(); resp.setHeader("Content-Type", "text/html"); moreHeaders(resp); resp.setHeader("Connection", "close"); data.resp = resp; resp.write(data.out); } String t; int start; Enumeration en; boolean anIfCondition = true; while ((t = in.readLine()) != null) { if ((start = t.indexOf("<!--#")) > -1) { if (anIfCondition) out.write(t.substring(0, start).getBytes()); try { en = ssi.parse(t.substring(start)).elements(); SSICommand command; while (en.hasMoreElements()) { command = (SSICommand) en.nextElement(); logger.fine("Command=" + command); switch(command.getCommand()) { case BSssi.CMD_IF_TRUE: anIfCondition = true; break; case BSssi.CMD_IF_FALSE: anIfCondition = false; break; case BSssi.CMD_CGI: out.flush(); if (command.getFileType() != null && command.getFileType().startsWith("shtm")) { HttpData d = newHttpData(data); d.out = out; d.realPath = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()); new SsiHandler(d, ssi).perform(); } else { String application = getExtension(command.getFileType()); if (application == null) { writePaused(new FileInputStream(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())), out, pause); } else { String parameter = ""; if (command.getMessage().indexOf("php") >= 0) { parameter = "-f "; } Process p = Runtime.getRuntime().exec(application + " " + parameter + HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl())); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); } } break; case BSssi.CMD_EXEC: Process p = Runtime.getRuntime().exec(command.getMessage()); BufferedReader pIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String aLine; while ((aLine = pIn.readLine()) != null) out.write((aLine + "\n").getBytes()); BufferedReader pErr = new BufferedReader(new InputStreamReader(p.getErrorStream())); while ((aLine = pErr.readLine()) != null) out.write((aLine + "\n").getBytes()); pIn.close(); pErr.close(); p.destroy(); break; case BSssi.CMD_INCLUDE: File incFile = HttpThread.getMappedFilename(command.getMessage()); if (incFile.exists() && incFile.canRead()) { writePaused(new FileInputStream(incFile), out, pause); } break; case BSssi.CMD_FILESIZE: long sizeBytes = HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).length(); double smartSize; String unit = "bytes"; if (command.getFileType().trim().equals("abbrev")) { if (sizeBytes > 1000000) { smartSize = sizeBytes / 1024000.0; unit = "M"; } else if (sizeBytes > 1000) { smartSize = sizeBytes / 1024.0; unit = "K"; } else { smartSize = sizeBytes; unit = "bytes"; } NumberFormat numberFormat = new DecimalFormat("#,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(smartSize) + "" + unit).getBytes()); } else { NumberFormat numberFormat = new DecimalFormat("#,###,##0", new DecimalFormatSymbols(Locale.ENGLISH)); out.write((numberFormat.format(sizeBytes) + " " + unit).getBytes()); } break; case BSssi.CMD_FLASTMOD: out.write(ssi.format(new Date(HttpThread.getMappedFilename(command.getMessage(), data.req.getUrl()).lastModified()), TimeZone.getTimeZone("GMT")).getBytes()); break; case BSssi.CMD_NOECHO: break; case BSssi.CMD_ECHO: default: out.write(command.getMessage().getBytes()); break; } } } catch (Exception e) { e.printStackTrace(); out.write((ssi.getErrorMessage() + " " + e.getMessage()).getBytes()); } if (anIfCondition) out.write("\n".getBytes()); } else { if (anIfCondition) out.write((t + "\n").getBytes()); } out.flush(); } in.close(); out.close(); data.fileData.setContentType("text/html"); data.fileData.setFile(tempFile); writePaused(new FileInputStream(tempFile), data.out, pause); logger.fine("HandleSSI done for " + data.resp); }
|
11
|
Code Sample 1:
public String md5(String phrase) { MessageDigest m; String coded = new String(); try { m = MessageDigest.getInstance("MD5"); m.update(phrase.getBytes(), 0, phrase.length()); coded = (new BigInteger(1, m.digest()).toString(16)).toString(); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } if (coded.length() < 32) { coded = "0" + coded; } return coded; }
Code Sample 2:
public static String md5(String word) { MessageDigest alg = null; try { alg = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(ServletUtils.class.getName()).log(Level.SEVERE, null, ex); } alg.reset(); alg.update(word.getBytes()); byte[] digest = alg.digest(); StringBuilder hashedWord = new StringBuilder(); String hx; for (int i = 0; i < digest.length; i++) { hx = Integer.toHexString(0xFF & digest[i]); if (hx.length() == 1) { hx = "0" + hx; } hashedWord.append(hx); } return hashedWord.toString(); }
|
11
|
Code Sample 1:
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); ServletContext ctx = getServletContext(); RequestDispatcher rd = ctx.getRequestDispatcher(SETUP_JSP); HttpSession session = request.getSession(false); if (session == null) { session = request.getSession(true); session.setAttribute(ERROR_TAG, "You need to have run the Sniffer before running " + "the Grinder. Go to <a href=\"/index.jsp\">the start page</a> " + " to run the Sniffer."); rd = ctx.getRequestDispatcher(ERROR_JSP); } else { session.setMaxInactiveInterval(-1); String pValue = request.getParameter(ACTION_TAG); if (pValue != null && pValue.equals(START_TAG)) { rd = ctx.getRequestDispatcher(WAIT_JSP); int p = 1; int t = 1; int c = 1; try { p = Integer.parseInt(request.getParameter("procs")); p = p > MAX_PROCS ? MAX_PROCS : p; } catch (NumberFormatException e) { } try { t = Integer.parseInt(request.getParameter("threads")); t = t > MAX_THREADS ? MAX_THREADS : t; } catch (NumberFormatException e) { } try { c = Integer.parseInt(request.getParameter("cycles")); c = c > MAX_CYCLES ? MAX_CYCLES : c; } catch (NumberFormatException e) { } try { String dirname = (String) session.getAttribute(OUTPUT_TAG); File workdir = new File(dirname); (new File(dirname + File.separator + LOG_DIR)).mkdir(); FileInputStream gpin = new FileInputStream(GPROPS); FileOutputStream gpout = new FileOutputStream(dirname + File.separator + GPROPS); copyBytes(gpin, gpout); gpin.close(); InitialContext ictx = new InitialContext(); Boolean isSecure = (Boolean) session.getAttribute(SECURE_TAG); if (isSecure.booleanValue()) { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpsPlugin" + "\n").getBytes()); String certificate = (String) ictx.lookup(CERTIFICATE); String password = (String) ictx.lookup(PASSWORD); gpout.write(("grinder.plugin.parameter.clientCert=" + certificate + "\n").getBytes()); gpout.write(("grinder.plugin.parameter.clientCertPassword=" + password + "\n").getBytes()); } else { gpout.write(("grinder.plugin=" + "net.grinder.plugin.http.HttpPlugin\n").getBytes()); } gpout.write(("grinder.processes=" + p + "\n").getBytes()); gpout.write(("grinder.threads=" + t + "\n").getBytes()); gpout.write(("grinder.cycles=" + c + "\n").getBytes()); gpin = new FileInputStream(dirname + File.separator + SNIFFOUT); copyBytes(gpin, gpout); gpin.close(); gpout.close(); String classpath = (String) ictx.lookup(CLASSPATH); String cmd[] = new String[JAVA_PROCESS.length + 1 + GRINDER_PROCESS.length]; int i = 0; int n = JAVA_PROCESS.length; System.arraycopy(JAVA_PROCESS, 0, cmd, i, n); cmd[n] = classpath; i = n + 1; n = GRINDER_PROCESS.length; System.arraycopy(GRINDER_PROCESS, 0, cmd, i, n); for (int j = 0; j < cmd.length; ++j) { System.out.print(cmd[j] + " "); } Process proc = Runtime.getRuntime().exec(cmd, null, workdir); session.setAttribute(PROCESS_TAG, proc); } catch (NamingException e) { e.printStackTrace(); session.setAttribute(ERROR_MSG_TAG, e.toString()); session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(ERROR_JSP); } catch (Throwable e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } else if (pValue != null && pValue.equals(CHECK_TAG)) { boolean finished = true; try { Process p = (Process) session.getAttribute(PROCESS_TAG); int result = p.exitValue(); } catch (IllegalThreadStateException e) { finished = false; } if (finished) { session.setMaxInactiveInterval(TIMEOUT); rd = ctx.getRequestDispatcher(RESULTS_JSP); } else { rd = ctx.getRequestDispatcher(WAIT_JSP); } } try { rd.forward(request, response); } catch (ServletException e) { e.printStackTrace(response.getWriter()); throw new IOException(e.getMessage()); } } }
Code Sample 2:
@Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; }
|
11
|
Code Sample 1:
public void run() { String s; s = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + word); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while (((str = in.readLine()) != null) && (!stopped)) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("Main Entry:.+?<br>(.+?)</td>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); java.io.StringWriter wr = new java.io.StringWriter(); HTMLDocument doc = null; HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit(); try { doc = (HTMLDocument) editor.getDocument(); } catch (Exception e) { } System.out.println(wr); editor.setContentType("text/html"); if (matcher.find()) try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR>" + matcher.group(1) + "<HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } else try { kit.insertHTML(doc, editor.getCaretPosition(), "<HR><FONT COLOR='RED'>NOT FOUND!!</FONT><HR>", 0, 0, null); } catch (Exception e) { System.out.println(e.getMessage()); } button.setEnabled(true); }
Code Sample 2:
public static double[][] getCurrency() throws IOException { URL url = new URL("http://hk.finance.yahoo.com/currency"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "big5")); double currency[][] = new double[11][11]; while (true) { String line = in.readLine(); String reg = "<td\\s((align=\"right\"\\sclass=\"yfnc_tabledata1\")" + "|(class=\"yfnc_tabledata1\"\\salign=\"right\"))>" + "([\\d|\\.]+)</td>"; Matcher m = Pattern.compile(reg).matcher(line); int i = 0, j = 0; boolean isfound = false; while (m.find()) { isfound = true; currency[i][j] = Double.parseDouble(m.group(4)); if (j == 10) { j = 0; i++; } else j++; } if (isfound) break; } return currency; }
|
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:
private void foundNewVersion() { updater = new UpdaterView(); updater.setLabelText("Initiating Updater..."); updater.setProgress(0); updater.setLocationRelativeTo(null); updater.setVisible(true); URL pathUrl = ClassLoader.getSystemResource("img/icon.png"); String path = pathUrl.toString(); path = path.substring(4, path.length() - 14); try { file = new File(new URI(path)); updaterFile = new File(new URI(path.substring(0, path.length() - 4) + "Updater.jar")); if (updaterFile.exists()) { updaterFile.delete(); } updater.setProgress(25); SwingUtilities.invokeLater(new Runnable() { public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } }); } catch (URISyntaxException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "Update error! Could not create Updater. Check folder permission.", "Error", JOptionPane.ERROR_MESSAGE); } }
|
00
|
Code Sample 1:
public static String recoverPassword(String token) { try { token = encryptGeneral1(token); String data = URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(token, "UTF-8"); URL url = new URL("https://mypasswords-server.appspot.com/recover_password"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder finalResult = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { finalResult.append(line); } wr.close(); rd.close(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(finalResult.toString()))); document.normalizeDocument(); Element root = document.getDocumentElement(); String password = root.getTextContent(); password = decryptGeneral1(password); return password; } catch (Exception e) { System.out.println(e.getMessage()); } return null; }
Code Sample 2:
protected void performInsertTest() throws Exception { Connection conn = connect(); EntityDescriptor ed = repository.getEntityDescriptor(User.class); User testUser = new User(); Date now = new Date(); conn.setAutoCommit(false); testUser.setUsername("rednose"); testUser.setUCreated("dbUtilTest"); testUser.setUModified("dbUtilTest"); testUser.setDtCreated(now); testUser.setDtModified(now); String sql = dbUtil.genInsert(ed, testUser); Statement st = conn.createStatement(); long id = 0; System.err.println("Insert: " + sql); int rv = st.executeUpdate(sql, dbUtil.supportsGeneratedKeyQuery() ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS); if (rv > 0) { if (dbUtil.supportsGeneratedKeyQuery()) { ResultSet rs = st.getGeneratedKeys(); if (rs.next()) id = rs.getLong(1); } else { id = queryId(ed, now, "dbUtilTest", conn, dbUtil); } if (id > 0) testUser.setId(id); else rv = 0; } conn.rollback(); assertTrue("oups, insert failed?", id != 0); System.err.println("successfully created user with id #" + id + " temporarily"); }
|
00
|
Code Sample 1:
public static Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; }
Code Sample 2:
public static String getFileContents(String path) { BufferedReader buffReader = null; InputStream stream = null; if (path.indexOf("://") != -1) { URL url = null; try { url = new URL(path); } catch (MalformedURLException e) { LOGGER.warn(String.format("Malformed URL: \"%s\"", path)); } if (url == null) { throw new DeveloperError(String.format("Cannot create URL from path: \"%s\"", path), new NullPointerException()); } try { String encoding = Characters.getDeclaredXMLEncoding(url); stream = url.openStream(); buffReader = new BufferedReader(new InputStreamReader(stream, encoding)); } catch (IOException e) { LOGGER.warn(String.format("I/O error trying to read \"%s\"", path)); } } else { File toRead = null; try { toRead = getExistingFile(path); } catch (FileNotFoundException e) { throw new UserError(new FileNotFoundException(path)); } if (toRead.isAbsolute()) { String parent = toRead.getParent(); try { workingDirectory.push(URLTools.createValidURL(parent)); } catch (FileNotFoundException e) { throw new DeveloperError(String.format("Created an invalid parent file: \"%s\".", parent), e); } } if (toRead.exists() && !toRead.isDirectory()) { String _path = toRead.getAbsolutePath(); try { String encoding = Characters.getDeclaredXMLEncoding(URLTools.createValidURL(_path)); stream = new FileInputStream(_path); buffReader = new BufferedReader(new InputStreamReader(stream, encoding)); } catch (IOException e) { LOGGER.warn(String.format("I/O error trying to read \"%s\"", _path)); return null; } } else { assert toRead.exists() : "getExistingFile() returned a non-existent file"; if (toRead.isDirectory()) { throw new UserError(new FileAlreadyExistsAsDirectoryException(toRead)); } } } StringBuilder result = new StringBuilder(); String line; if (buffReader != null && stream != null) { try { while ((line = buffReader.readLine()) != null) { result.append(line); } buffReader.close(); stream.close(); } catch (IOException e) { LOGGER.warn(String.format("I/O error trying to read \"%s\"", path)); return null; } } return result.toString(); }
|
00
|
Code Sample 1:
private RssEvent getLastEvent() throws DocumentException, IOException { Document document = new SAXReader().read(url.openStream()); Element item = document.getRootElement().element("channel").element("item"); Date date = new Date(); String dateStr = item.element("pubDate").getStringValue(); try { date = dateFormat.parse(dateStr); } catch (ParseException e) { String message = MessageFormat.format("Unable to parse string \"{0}\" with pattern \"{1}\".", dateStr, FORMAT); logger.warn(message, e); } RssEvent event = new RssEvent(this, item.element("title").getStringValue(), item.element("link").getStringValue(), item.element("description").getStringValue(), item.element("author").getStringValue(), date); return event; }
Code Sample 2:
private void sort() { boolean unsortiert = true; Datei tmp = null; while (unsortiert) { unsortiert = false; for (int i = 0; i < this.size - 1; i++) { if (dateien[i] != null && dateien[i + 1] != null) { if (dateien[i].compareTo(dateien[i + 1]) < 0) { tmp = dateien[i]; dateien[i] = dateien[i + 1]; dateien[i + 1] = tmp; unsortiert = true; } } } } }
|
00
|
Code Sample 1:
public void listgroups() throws Exception { String lapage = new String(""); Pattern pat; Matcher mat; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearAll(); System.out.print("http://groups.yahoo.com/mygroups : "); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("."); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<td class=\"grpname selected\"><a href=\"(.+?)\".*?><em>(.+?)</em></a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(mat.group(2), "", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<a href=\"(.+?)\">Next ></a>"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); System.out.println(""); }
Code Sample 2:
public CServletContextWrapper(final FileSystem fs, final String contextName) { this.fs = fs; this.name = contextName; CContext.getInstance().init(this); try { URL url = this.getResource("/WEB-INF/classes/log4j.properties"); boolean ok = false; InputStream in = null; try { in = url.openStream(); ok = true; } catch (Throwable e) { } finally { try { if (in != null) in.close(); } catch (Exception ignore) { } } if (ok) { PropertyConfigurator.configure(url); } } catch (final Throwable e) { if (!hasPrintedLog4JWarning) { hasPrintedLog4JWarning = true; System.err.println("!!! WARNING: /WEB-INF/classes/log4j.properties missing."); } } this.init(); this.loadServletContextListener(); this.log = LOGGERHelper.getLogger(this.getClass()); CJNDIContextSetup.init(this); JDBCPooler.init(this); CResourceBundle.registerBundles(this); this.fireInitEvent(); }
|
00
|
Code Sample 1:
protected File downloadFile(String href) { Map<String, File> currentDownloadDirMap = downloadedFiles.get(downloadDir); if (currentDownloadDirMap != null) { File downloadedFile = currentDownloadDirMap.get(href); if (downloadedFile != null) { return downloadedFile; } } else { downloadedFiles.put(downloadDir, new HashMap<String, File>()); currentDownloadDirMap = downloadedFiles.get(downloadDir); } URL url; File result; try { FilesystemUtils.forceMkdirIfNotExists(downloadDir); url = generateUrl(href); result = createUniqueFile(downloadDir, href); } catch (IOException e) { LOG.warn("Failed to create file for download", e); return null; } currentDownloadDirMap.put(href, result); LOG.info("Downloading " + url); try { IOUtils.copy(url.openStream(), new FileOutputStream(result)); } catch (IOException e) { LOG.warn("Failed to download file " + url); } return result; }
Code Sample 2:
public static boolean checkEncode(String origin, byte[] mDigest, String algorithm) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(origin.getBytes()); if (MessageDigest.isEqual(mDigest, md.digest())) { return true; } else { return false; } }
|
11
|
Code Sample 1:
public SukuData updatePerson(String usertext, SukuData req) { String insPers; String userid = Utils.toUsAscii(usertext); if (userid != null && userid.length() > 16) { userid = userid.substring(0, 16); } StringBuilder sb = new StringBuilder(); sb.append("insert into unit (pid,tag,privacy,groupid,sex,sourcetext,privatetext,userrefn"); if (userid != null) { sb.append(",createdby"); } sb.append(") values (?,?,?,?,?,?,?,? "); if (userid != null) { sb.append(",'" + userid + "'"); } sb.append(")"); insPers = sb.toString(); String updPers; sb = new StringBuilder(); sb.append("update unit set privacy=?,groupid=?,sex=?,sourcetext=?," + "privatetext=?,userrefn=?,Modified=now()"); if (userid != null) { sb.append(",modifiedby = '" + userid + "' where pid = ?"); } else { sb.append(" where pid = ?"); } updPers = sb.toString(); sb = new StringBuilder(); String updSql; sb.append("update unitnotice set "); sb.append("surety=?,Privacy=?,NoticeType=?,Description=?,"); sb.append("DatePrefix=?,FromDate=?,ToDate=?,Place=?,"); sb.append("Village=?,Farm=?,Croft=?,Address=?,"); sb.append("PostalCode=?,PostOffice=?,State=?,Country=?,Email=?,"); sb.append("NoteText=?,MediaFilename=?,MediaTitle=?,Prefix=?,"); sb.append("Surname=?,Givenname=?,Patronym=?,PostFix=?,"); sb.append("SourceText=?,PrivateText=?,RefNames=?,RefPlaces=?,Modified=now()"); if (userid != null) { sb.append(",modifiedby = '" + userid + "'"); } sb.append(" where pnid = ?"); updSql = sb.toString(); sb = new StringBuilder(); String insSql; sb.append("insert into unitnotice ("); sb.append("surety,Privacy,NoticeType,Description,"); sb.append("DatePrefix,FromDate,ToDate,Place,"); sb.append("Village,Farm,Croft,Address,"); sb.append("PostalCode,PostOffice,State,Country,Email,"); sb.append("NoteText,MediaFilename,MediaTitle,Prefix,"); sb.append("Surname,Givenname,Patronym,PostFix,"); sb.append("SourceText,PrivateText,RefNames,Refplaces,pnid,pid,tag"); if (userid != null) { sb.append(",createdby"); } sb.append(") values ("); sb.append("?,?,?,?,?,?,?,?," + "?,?,?,?,?,?,?,?," + "?,?,?,?,?,?,?,?,"); sb.append("?,?,?,?,?,?,?,?"); if (userid != null) { sb.append(",'" + userid + "'"); } sb.append(")"); insSql = sb.toString(); sb = new StringBuilder(); String updLangSql; sb.append("update unitlanguage set "); sb.append("NoticeType=?,Description=?," + "Place=?,"); sb.append("NoteText=?,MediaTitle=?,Modified=now() "); if (userid != null) { sb.append(",modifiedby = '" + userid + "'"); } sb.append("where pnid=? and langCode = ?"); updLangSql = sb.toString(); sb = new StringBuilder(); String insLangSql; sb.append("insert into unitlanguage (pnid,pid,tag,langcode,"); sb.append("NoticeType,Description,Place,"); sb.append("NoteText,MediaTitle"); if (userid != null) { sb.append(",createdby"); } sb.append(") values (?,?,?,?,?,?,?,?,?"); if (userid != null) { sb.append(",'" + userid + "'"); } sb.append(")"); insLangSql = sb.toString(); String delOneLangSql = "delete from unitlanguage where pnid = ? and langcode = ? "; String updRowSql = "update unitnotice set noticerow = ? where pnid = ? "; String delSql = "delete from unitnotice where pnid = ? "; String delAllLangSql = "delete from Unitlanguage where pnid = ? "; SukuData res = new SukuData(); UnitNotice[] nn = req.persLong.getNotices(); if (nn != null) { String prevName = ""; String prevOccu = ""; for (int i = 0; i < nn.length; i++) { if (nn[i].getTag().equals("NAME")) { String thisName = Utils.nv(nn[i].getGivenname()) + "/" + Utils.nv(nn[i].getPatronym()) + "/" + Utils.nv(nn[i].getPrefix()) + "/" + Utils.nv(nn[i].getSurname()) + "/" + Utils.nv(nn[i].getPostfix()); if (thisName.equals(prevName) && !prevName.equals("")) { if (nn[i].isToBeDeleted() == false) { String e = Resurses.getString("IDENTICAL_NAMES_ERROR") + " [" + req.persLong.getPid() + "] idx [" + i + "] = " + thisName; logger.warning(e); if (req.persLong.getPid() > 0) { res.resu = e; return res; } } } prevName = thisName; } else if (nn[i].getTag().equals("OCCU")) { String thisOccu = Utils.nv(nn[i].getDescription()); if (thisOccu.equals(prevOccu) && !prevOccu.equals("")) { if (nn[i].isToBeDeleted() == false) { String e = Resurses.getString("IDENTICAL_OCCU_ERROR") + " [" + req.persLong.getPid() + "] idx [" + i + "] = '" + thisOccu + "'"; logger.warning(e); if (req.persLong.getPid() > 0) { res.resu = e; return res; } } } prevOccu = thisOccu; } } } int pid = 0; try { con.setAutoCommit(false); Statement stm; PreparedStatement pst; if (req.persLong.getPid() > 0) { res.resultPid = req.persLong.getPid(); pid = req.persLong.getPid(); if (req.persLong.isMainModified()) { if (req.persLong.getModified() == null) { pst = con.prepareStatement(updPers + " and modified is null "); } else { pst = con.prepareStatement(updPers + " and modified = ?"); } pst.setString(1, req.persLong.getPrivacy()); pst.setString(2, req.persLong.getGroupId()); pst.setString(3, req.persLong.getSex()); pst.setString(4, req.persLong.getSource()); pst.setString(5, req.persLong.getPrivateText()); pst.setString(6, req.persLong.getRefn()); pst.setInt(7, req.persLong.getPid()); if (req.persLong.getModified() != null) { pst.setTimestamp(8, req.persLong.getModified()); } int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("Person update for pid " + pid + " failed [" + lukuri + "] (Should be 1)"); throw new SQLException("TRANSACTION_ERROR_1"); } String apara = null; String bpara = null; String cpara = null; String dpara = null; if (req.persLong.getSex().equals("M")) { apara = "FATH"; bpara = "MOTH"; cpara = "HUSB"; dpara = "WIFE"; } else if (req.persLong.getSex().equals("F")) { bpara = "FATH"; apara = "MOTH"; dpara = "HUSB"; cpara = "WIFE"; } if (apara != null) { String sqlParent = "update relation as b set tag=? " + "where b.rid in (select a.rid from relation as a " + "where a.pid = ? and a.pid <> b.rid and a.tag='CHIL') " + "and tag=?"; PreparedStatement ppare = con.prepareStatement(sqlParent); ppare.setString(1, apara); ppare.setInt(2, req.persLong.getPid()); ppare.setString(3, bpara); int resup = ppare.executeUpdate(); logger.fine("updated count for person parent= " + resup); String sqlSpouse = "update relation as b set tag=? " + "where b.rid in (select a.rid " + "from relation as a where a.pid = ? and a.pid <> b.pid " + "and a.tag in ('HUSB','WIFE')) and tag=?"; ppare = con.prepareStatement(sqlSpouse); ppare.setString(1, cpara); ppare.setInt(2, req.persLong.getPid()); ppare.setString(3, dpara); resup = ppare.executeUpdate(); logger.fine("updated count for person spouse= " + resup); } } } else { stm = con.createStatement(); ResultSet rs = stm.executeQuery("select nextval('unitseq')"); if (rs.next()) { pid = rs.getInt(1); res.resultPid = pid; } else { throw new SQLException("Sequence unitseq error"); } rs.close(); pst = con.prepareStatement(insPers); pst.setInt(1, pid); pst.setString(2, req.persLong.getTag()); pst.setString(3, req.persLong.getPrivacy()); pst.setString(4, req.persLong.getGroupId()); pst.setString(5, req.persLong.getSex()); pst.setString(6, req.persLong.getSource()); pst.setString(7, req.persLong.getPrivateText()); pst.setString(8, req.persLong.getRefn()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("Person created for pid " + pid + " gave result " + lukuri); } } PreparedStatement pstDel = con.prepareStatement(delSql); PreparedStatement pstDelLang = con.prepareStatement(delAllLangSql); PreparedStatement pstUpdRow = con.prepareStatement(updRowSql); if (nn != null) { for (int i = 0; i < nn.length; i++) { UnitNotice n = nn[i]; int pnid = 0; if (n.isToBeDeleted()) { pstDelLang.setInt(1, n.getPnid()); int landelcnt = pstDelLang.executeUpdate(); pstDel.setInt(1, n.getPnid()); int delcnt = pstDel.executeUpdate(); if (delcnt != 1) { logger.warning("Person notice [" + n.getTag() + "]delete for pid " + pid + " failed [" + delcnt + "] (Should be 1)"); throw new SQLException("TRANSACTION_ERROR_2"); } String text = "Poistettiin " + delcnt + " riviä [" + landelcnt + "] kieliversiota pid = " + n.getPid() + " tag=" + n.getTag(); logger.fine(text); } else if (n.getPnid() == 0 || n.isToBeUpdated()) { if (n.getPnid() == 0) { stm = con.createStatement(); ResultSet rs = stm.executeQuery("select nextval('unitnoticeseq')"); if (rs.next()) { pnid = rs.getInt(1); } else { throw new SQLException("Sequence unitnoticeseq error"); } rs.close(); pst = con.prepareStatement(insSql); } else { if (n.getModified() == null) { pst = con.prepareStatement(updSql + " and modified is null "); } else { pst = con.prepareStatement(updSql + " and modified = ?"); } pnid = n.getPnid(); } if (n.isToBeUpdated() || n.getPnid() == 0) { pst.setInt(1, n.getSurety()); pst.setString(2, n.getPrivacy()); pst.setString(3, n.getNoticeType()); pst.setString(4, n.getDescription()); pst.setString(5, n.getDatePrefix()); pst.setString(6, n.getFromDate()); pst.setString(7, n.getToDate()); pst.setString(8, n.getPlace()); pst.setString(9, n.getVillage()); pst.setString(10, n.getFarm()); pst.setString(11, n.getCroft()); pst.setString(12, n.getAddress()); pst.setString(13, n.getPostalCode()); pst.setString(14, n.getPostOffice()); pst.setString(15, n.getState()); pst.setString(16, n.getCountry()); pst.setString(17, n.getEmail()); pst.setString(18, n.getNoteText()); pst.setString(19, n.getMediaFilename()); pst.setString(20, n.getMediaTitle()); pst.setString(21, n.getPrefix()); pst.setString(22, n.getSurname()); pst.setString(23, n.getGivenname()); pst.setString(24, n.getPatronym()); pst.setString(25, n.getPostfix()); pst.setString(26, n.getSource()); pst.setString(27, n.getPrivateText()); if (n.getRefNames() == null) { pst.setNull(28, Types.ARRAY); } else { Array xx = con.createArrayOf("varchar", n.getRefNames()); pst.setArray(28, xx); } if (n.getRefPlaces() == null) { pst.setNull(29, Types.ARRAY); } else { Array xx = con.createArrayOf("varchar", n.getRefPlaces()); pst.setArray(29, xx); } } if (n.getPnid() > 0) { pst.setInt(30, n.getPnid()); if (n.getModified() != null) { pst.setTimestamp(31, n.getModified()); } int luku = pst.executeUpdate(); if (luku != 1) { logger.warning("Person notice [" + n.getTag() + "] update for pid " + pid + " failed [" + luku + "] (Should be 1)"); throw new SQLException("TRANSACTION_ERROR_3"); } logger.fine("Päivitettiin " + luku + " tietuetta pnid=[" + n.getPnid() + "]"); } else { pst.setInt(30, pnid); pst.setInt(31, pid); pst.setString(32, n.getTag()); int luku = pst.executeUpdate(); logger.fine("Luotiin " + luku + " tietue pnid=[" + pnid + "]"); } if (n.getMediaData() == null) { String sql = "update unitnotice set mediadata = null where pnid = ?"; pst = con.prepareStatement(sql); pst.setInt(1, pnid); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("media deleted for pnid " + n.getPnid() + " gave result " + lukuri); } } else { String UPDATE_IMAGE_DATA = "update UnitNotice set MediaData = ?," + "mediaWidth = ?,mediaheight = ? where PNID = ? "; PreparedStatement ps = this.con.prepareStatement(UPDATE_IMAGE_DATA); ps.setBytes(1, n.getMediaData()); Dimension d = n.getMediaSize(); ps.setInt(2, d.width); ps.setInt(3, d.height); ps.setInt(4, pnid); ps.executeUpdate(); } } if (n.getLanguages() != null) { for (int l = 0; l < n.getLanguages().length; l++) { UnitLanguage ll = n.getLanguages()[l]; if (ll.isToBeDeleted()) { if (ll.getPnid() > 0) { pst = con.prepareStatement(delOneLangSql); pst.setInt(1, ll.getPnid()); pst.setString(2, ll.getLangCode()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("language deleted for pnid " + n.getPnid() + " [" + ll.getLangCode() + "] gave result " + lukuri); } } } if (ll.isToBeUpdated()) { if (ll.getPnid() == 0) { pst = con.prepareStatement(insLangSql); pst.setInt(1, n.getPnid()); pst.setInt(2, pid); pst.setString(3, n.getTag()); pst.setString(4, ll.getLangCode()); pst.setString(5, ll.getNoticeType()); pst.setString(6, ll.getDescription()); pst.setString(7, ll.getPlace()); pst.setString(8, ll.getNoteText()); pst.setString(9, ll.getMediaTitle()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("language added for pnid " + n.getPnid() + " [" + ll.getLangCode() + "] gave result " + lukuri); } } else { pst = con.prepareStatement(updLangSql); pst.setString(1, ll.getNoticeType()); pst.setString(2, ll.getDescription()); pst.setString(3, ll.getPlace()); pst.setString(4, ll.getNoteText()); pst.setString(5, ll.getMediaTitle()); pst.setInt(6, ll.getPnid()); pst.setString(7, ll.getLangCode()); int lukuri = pst.executeUpdate(); if (lukuri != 1) { logger.warning("language for pnid " + ll.getPnid() + " [" + ll.getLangCode() + "] gave result " + lukuri); } pst.close(); } } } } if (n.getPnid() > 0) { pnid = n.getPnid(); } pstUpdRow.setInt(1, i + 1); pstUpdRow.setInt(2, pnid); pstUpdRow.executeUpdate(); } } if (req.relations != null) { if (req.persLong.getPid() == 0) { req.persLong.setPid(pid); for (int i = 0; i < req.relations.length; i++) { Relation r = req.relations[i]; if (r.getPid() == 0) { r.setPid(pid); } } } updateRelations(userid, req); } con.commit(); } catch (Exception e) { try { con.rollback(); } catch (SQLException e1) { logger.log(Level.WARNING, "Person update rollback failed", e1); } logger.log(Level.WARNING, "person update rolled back for [" + pid + "]", e); res.resu = e.getMessage(); return res; } finally { try { con.setAutoCommit(true); } catch (SQLException e) { logger.log(Level.WARNING, "set autocommit failed", e); } } return res; }
Code Sample 2:
public void testPreparedStatement0009() throws Exception { Connection cx = getConnection(); dropTable("#t0009"); Statement stmt = cx.createStatement(); stmt.executeUpdate("create table #t0009 " + " (i integer not null, " + " s char(10) not null) "); cx.setAutoCommit(false); PreparedStatement pStmt = cx.prepareStatement("insert into #t0009 values (?, ?)"); int rowsToAdd = 8; final String theString = "abcdefghijklmnopqrstuvwxyz"; int count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.rollback(); stmt = cx.createStatement(); ResultSet rs = stmt.executeQuery("select s, i from #t0009"); assertNotNull(rs); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == 0); cx.commit(); rowsToAdd = 6; count = 0; for (int i = 1; i <= rowsToAdd; i++) { pStmt.setInt(1, i); pStmt.setString(2, theString.substring(0, i)); count += pStmt.executeUpdate(); } assertTrue(count == rowsToAdd); cx.commit(); rs = stmt.executeQuery("select s, i from #t0009"); count = 0; while (rs.next()) { count++; assertTrue(rs.getString(1).trim().length() == rs.getInt(2)); } assertTrue(count == rowsToAdd); cx.commit(); cx.setAutoCommit(true); }
|
00
|
Code Sample 1:
public void alterar(Cliente cliente) throws Exception { Connection connection = criaConexao(false); String sql = "update cliente set nome = ?, sexo = ?, cod_cidade = ? where cod_cliente = ?"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.setString(1, cliente.getNome()); stmt.setString(2, cliente.getSexo()); stmt.setInt(3, cliente.getCidade().getCodCidade()); stmt.setLong(4, cliente.getId()); int retorno = stmt.executeUpdate(); if (retorno == 0) { connection.rollback(); throw new SQLException("Ocorreu um erro inesperado no momento de alterar dados de cliente no banco!"); } connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
Code Sample 2:
protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
|
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 copyNIO(File in, File out) throws IOException { FileInputStream inStream = null; FileOutputStream outStream = null; FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { inStream = new FileInputStream(in); outStream = new FileOutputStream(out); sourceChannel = inStream.getChannel(); destinationChannel = outStream.getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); if (inStream != null) inStream.close(); if (outStream != null) outStream.close(); } }
|
00
|
Code Sample 1:
public InputStream getParameterAsInputStream(String key) throws UndefinedParameterError, IOException { String urlString = getParameter(key); if (urlString == null) return null; try { URL url = new URL(urlString); InputStream stream = url.openStream(); return stream; } catch (MalformedURLException e) { File file = getParameterAsFile(key); if (file != null) { return new FileInputStream(file); } else { return null; } } }
Code Sample 2:
private void bokActionPerformed(java.awt.event.ActionEvent evt) { Vector vret = this.uniformtitlepanel.getEnteredValuesKeys(); String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveUniformTitleSH("2", vret, patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "UniformTitleSubjectHeadingServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } }
|
00
|
Code Sample 1:
private void loadDBpediaOntology() { try { URL url = new URL("http://downloads.dbpedia.org/3.6/dbpedia_3.6.owl.bz2"); InputStream is = new BufferedInputStream(url.openStream()); CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is); dbPediaOntology = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(in); reasoner = PelletReasonerFactory.getInstance().createNonBufferingReasoner(dbPediaOntology); reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (CompressorException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
Code Sample 2:
public void copyFile(File in, File out) throws Exception { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); }
|
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 static void copia(File nombreFuente, File nombreDestino) throws IOException { FileInputStream fis = new FileInputStream(nombreFuente); FileOutputStream fos = new FileOutputStream(nombreDestino); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); }
|
11
|
Code Sample 1:
public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); }
Code Sample 2:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameterValues(Constants.PARAM_UUID)[0]; String datastream = null; if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version.foxml\""); } else { datastream = req.getParameterValues(Constants.PARAM_DATASTREAM)[0]; resp.addHeader("Content-Disposition", "attachment; ContentType = \"text/xml\"; filename=\"" + uuid + "_server_version_" + datastream + ".xml\""); } ServletOutputStream os = resp.getOutputStream(); if (uuid != null && !"".equals(uuid)) { try { StringBuffer sb = new StringBuffer(); if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_FOXML_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/objectXML"); } else if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { sb.append(config.getFedoraHost()).append("/objects/").append(uuid).append("/datastreams/").append(datastream).append("/content"); } InputStream is = RESTHelper.get(sb.toString(), config.getFedoraLogin(), config.getFedoraPassword(), false); if (is == null) { return; } try { if (req.getRequestURI().contains(Constants.SERVLET_DOWNLOAD_DATASTREAMS_PREFIX)) { os.write(Constants.XML_HEADER_WITH_BACKSLASHES.getBytes()); } IOUtils.copyStreams(is, os); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); if (is != null) { try { is.close(); } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { is = null; } } } } catch (IOException e) { resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND); LOGGER.error("Problem with downloading foxml.", e); } finally { os.flush(); } } }
|
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 static Document convertHtmlToXml(final InputStream htmlInputStream, final String classpathXsltResource, final String encoding) { Parser p = new Parser(); javax.xml.parsers.DocumentBuilder db; try { db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("", e); throw new RuntimeException(); } Document document = db.newDocument(); InputStream is = htmlInputStream; if (log.isDebugEnabled()) { ByteArrayOutputStream baos; baos = new ByteArrayOutputStream(); try { IOUtils.copy(is, baos); } catch (IOException e) { log.error("Fail to make input stream copy.", e); } IOUtils.closeQuietly(is); ByteArrayInputStream byteArrayInputStream; byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray()); try { IOUtils.toString(new ByteArrayInputStream(baos.toByteArray()), "UTF-8"); } catch (IOException e) { log.error("", e); } IOUtils.closeQuietly(byteArrayInputStream); is = new ByteArrayInputStream(baos.toByteArray()); } try { InputSource iSource = new InputSource(is); iSource.setEncoding(encoding); Source transformerSource = new SAXSource(p, iSource); Result result = new DOMResult(document); Transformer xslTransformer = getTransformerByName(classpathXsltResource, false); try { xslTransformer.transform(transformerSource, result); } catch (TransformerException e) { throw new RuntimeException(e); } } finally { try { is.close(); } catch (Exception e) { log.warn("", e); } } return document; }
|
11
|
Code Sample 1:
private void add(Hashtable applicantInfo) throws Exception { String mode = "".equals(getParam("applicant_id_gen").trim()) ? "update" : "insert"; String applicant_id = getParam("applicant_id"); String password = getParam("password"); if ("".equals(applicant_id)) applicant_id = getParam("applicant_id_gen"); if ("".equals(getParam("applicant_name"))) throw new Exception("Can not have empty fields!"); applicantInfo.put("id", applicant_id); applicantInfo.put("password", password); applicantInfo.put("name", getParam("applicant_name")); applicantInfo.put("address1", getParam("address1")); applicantInfo.put("address2", getParam("address2")); applicantInfo.put("address3", getParam("address3")); applicantInfo.put("city", getParam("city")); applicantInfo.put("state", getParam("state")); applicantInfo.put("poscode", getParam("poscode")); applicantInfo.put("country_code", getParam("country_list")); applicantInfo.put("email", getParam("email")); applicantInfo.put("phone", getParam("phone")); String birth_year = getParam("birth_year"); String birth_month = getParam("birth_month"); String birth_day = getParam("birth_day"); applicantInfo.put("birth_year", birth_year); applicantInfo.put("birth_month", birth_month); applicantInfo.put("birth_day", birth_day); applicantInfo.put("gender", getParam("gender")); String birth_date = birth_year + "-" + fmt(birth_month) + "-" + fmt(birth_day); applicantInfo.put("birth_date", birth_date); Db db = null; String sql = ""; Connection conn = null; try { db = new Db(); conn = db.getConnection(); conn.setAutoCommit(false); Statement stmt = db.getStatement(); SQLRenderer r = new SQLRenderer(); boolean found = false; { r.add("applicant_id"); r.add("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLSelect("adm_applicant"); ResultSet rs = stmt.executeQuery(sql); if (rs.next()) found = true; else found = false; } if (found && !"update".equals(mode)) throw new Exception("Applicant Id was invalid!"); { r.clear(); r.add("password", (String) applicantInfo.get("password")); r.add("applicant_name", (String) applicantInfo.get("name")); r.add("address1", (String) applicantInfo.get("address1")); r.add("address2", (String) applicantInfo.get("address2")); r.add("address3", (String) applicantInfo.get("address3")); r.add("city", (String) applicantInfo.get("city")); r.add("state", (String) applicantInfo.get("state")); r.add("poscode", (String) applicantInfo.get("poscode")); r.add("country_code", (String) applicantInfo.get("country_code")); r.add("phone", (String) applicantInfo.get("phone")); r.add("birth_date", (String) applicantInfo.get("birth_date")); r.add("gender", (String) applicantInfo.get("gender")); } if (!found) { r.add("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLInsert("adm_applicant"); stmt.executeUpdate(sql); } else { r.update("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLUpdate("adm_applicant"); stmt.executeUpdate(sql); } conn.commit(); } catch (DbException dbex) { throw dbex; } catch (SQLException sqlex) { try { conn.rollback(); } catch (SQLException rollex) { } throw sqlex; } finally { if (db != null) db.close(); } }
Code Sample 2:
public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } }
|
00
|
Code Sample 1:
public SpreadSheetFrame(FileManager owner, File file, Delimiter delim) { super(owner, file.getPath()); JPanel pane = new JPanel(new BorderLayout()); super.contentPane.add(pane); this.tableModel = new BigTableModel(file, delim); this.table = new JTable(tableModel); this.table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.tableModel.setTable(this.table); pane.add(new JScrollPane(this.table)); addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { tableModel.close(); } }); JMenu menu = new JMenu("Tools"); getJMenuBar().add(menu); menu.add(new AbstractAction("NCBI") { @Override public void actionPerformed(ActionEvent e) { try { Pattern delim = Pattern.compile("[ ]"); BufferedReader r = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("/home/lindenb/jeter.txt.gz")))); String line = null; URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write("db=snp&retmode=xml"); while ((line = r.readLine()) != null) { String tokens[] = delim.split(line, 2); if (!tokens[0].startsWith("rs")) continue; wr.write("&id=" + tokens[0].substring(2).trim()); } wr.flush(); r.close(); InputStream in = conn.getInputStream(); IOUtils.copyTo(in, System.err); in.close(); wr.close(); } catch (IOException err) { err.printStackTrace(); } } }); }
Code Sample 2:
@Override public void doHandler(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getRequestURI().indexOf(".swf") != -1) { String fullUrl = (String) request.getAttribute("fullUrl"); fullUrl = urlTools.urlFilter(fullUrl, true); response.setCharacterEncoding("gbk"); response.setContentType("application/x-shockwave-flash"); PrintWriter out = response.getWriter(); try { URL url = new URL(fullUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "gbk")); fileEditor.pushStream(out, in, null, true); } catch (Exception e) { } out.flush(); } else if (request.getRequestURI().indexOf(".xml") != -1) { response.setContentType("text/xml"); PrintWriter out = response.getWriter(); try { URL url = new URL("http://" + configCenter.getUcoolOnlineIp() + request.getRequestURI()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); fileEditor.pushStream(out, in, null, true); } catch (Exception e) { } out.flush(); } }
|
00
|
Code Sample 1:
public List<String> extractUrlList(String url) throws IOException, XPathExpressionException { LinkedList<String> list = new LinkedList<String>(); HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); Tidy tidy = new Tidy(); tidy.setErrout(new NullPrintWriter()); Document doc = tidy.parseDOM(conn.getInputStream(), null); int len = conn.getContentLength(); if (len <= 0) len = 32000; ByteArrayOutputStream bout = new ByteArrayOutputStream(len); PrintStream ps = new PrintStream(bout); tidy.pprint(doc, ps); ps.flush(); String content = bout.toString(); Pattern p = Pattern.compile("(http://[\\w\\\\\\./=&?;-]+)"); Matcher m = p.matcher(content); while (m.find()) { list.add(m.group()); } return list; }
Code Sample 2:
public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Bill bill = (Bill) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_BILL")); pst.setDate(1, new java.sql.Date(bill.getDate().getTime())); pst.setInt(2, bill.getIdAccount()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from bill"); rs.next(); id = rs.getInt(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 id; }
|
00
|
Code Sample 1:
protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } }
Code Sample 2:
void openTextFile(String urlString, boolean install) { StringBuffer sb = null; try { URL url = new URL(urlString); InputStream in = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) sb.append(line + "\n"); in.close(); } catch (IOException e) { if (!(install && urlString.endsWith("StartupMacros.txt"))) IJ.error("URL Opener", "" + e); sb = null; } if (sb != null) { if (install) (new MacroInstaller()).install(new String(sb)); else { int index = urlString.lastIndexOf("/"); if (index != -1 && index <= urlString.length() - 1) urlString = urlString.substring(index + 1); (new Editor()).create(urlString, new String(sb)); } } }
|
11
|
Code Sample 1:
private File unzipArchive(File zipArchive, File outDir, String nameInZipArchive) throws IOException { File mainFile = null; ZipEntry entry = null; ZipInputStream zis = new ZipInputStream(new FileInputStream((zipArchive))); FileOutputStream fos = null; byte buffer[] = new byte[4096]; int bytesRead; while ((entry = zis.getNextEntry()) != null) { File outFile = new File(outDir, entry.getName()); if (entry.getName().equals(nameInZipArchive)) mainFile = outFile; fos = new FileOutputStream(outFile); while ((bytesRead = zis.read(buffer)) != -1) fos.write(buffer, 0, bytesRead); fos.close(); } zis.close(); return mainFile; }
Code Sample 2:
public static void copy(File file1, File file2) throws IOException { FileReader in = new FileReader(file1); FileWriter out = new FileWriter(file2); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
|
00
|
Code Sample 1:
public static String openldapDigestMd5(final String password) { String base64; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(password.getBytes()); base64 = fr.cnes.sitools.util.Base64.encodeBytes(digest.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return OPENLDAP_MD5_PREFIX + base64; }
Code Sample 2:
public Document getDocument(String urlString) { Document doc = null; URLConnection conn = null; InputStream in = null; try { SAXBuilder sxbuild = new SAXBuilder(); if (Osmolt.debug) { outputInterface.printDebugMessage("ProcessOSM", "url: " + urlString); in = new FileInputStream(new File(System.getProperty("user.home") + "/data.osm")); outputInterface.processSetStatus("getting data from " + System.getProperty("user.home") + "/data.osm"); } else { URL url = new URL(urlString); outputInterface.printDebugMessage("ProcessOSM", "url: " + urlString); outputInterface.processSetStatus("connecting Server"); conn = url.openConnection(); outputInterface.processSetStatus("loading Data"); in = conn.getInputStream(); } doc = sxbuild.build(in); } catch (java.net.UnknownHostException e) { outputInterface.printError("Unknown Host: " + urlString); } catch (java.net.SocketTimeoutException e) { outputInterface.printError("Timeout: Server does not response"); } catch (java.net.ConnectException e) { outputInterface.printError("Error Server response: " + e.getMessage()); } catch (java.net.SocketException e) { outputInterface.printError("Error Server response: " + e.getMessage()); } catch (JDOMException e) { outputInterface.printError(e.getMessage()); e.printStackTrace(); } catch (IOException e) { outputInterface.printError(e.getMessage()); e.printStackTrace(); } catch (Exception e) { outputInterface.printError(e.getMessage()); e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ioe) { } } return doc; }
|
11
|
Code Sample 1:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { if (System.getProperty("os.name").toUpperCase().indexOf("WIN") != -1) { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } else { inChannel.transferTo(0, inChannel.size(), outChannel); } } finally { if (inChannel != null) try { inChannel.close(); } catch (Exception e) { } ; if (outChannel != null) try { outChannel.close(); } catch (Exception e) { } ; } }
Code Sample 2:
private static void _checkConfigFile() throws Exception { try { String filePath = getUserManagerConfigPath() + "user_manager_config.properties"; boolean copy = false; File from = new java.io.File(filePath); if (!from.exists()) { Properties properties = new Properties(); properties.put(Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_MIDDLE_NAME_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_DATE_OF_BIRTH_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CELL_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CELL_VISIBILITY")); properties.put(Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_PROPNAME"), Config.getStringProperty("ADDITIONAL_INFO_CATEGORIES_VISIBILITY")); Company comp = PublicCompanyFactory.getDefaultCompany(); int numberGenericVariables = Config.getIntProperty("MAX_NUMBER_VARIABLES_TO_SHOW"); for (int i = 1; i <= numberGenericVariables; i++) { properties.put(LanguageUtil.get(comp.getCompanyId(), comp.getLocale(), "user.profile.var" + i).replace(" ", "_"), Config.getStringProperty("ADDITIONAL_INFO_DEFAULT_VISIBILITY")); } try { properties.store(new java.io.FileOutputStream(filePath), null); } catch (Exception e) { Logger.error(UserManagerPropertiesFactory.class, e.getMessage(), e); } from = new java.io.File(filePath); copy = true; } String tmpFilePath = UtilMethods.getTemporaryDirPath() + "user_manager_config_properties.tmp"; File to = new java.io.File(tmpFilePath); if (!to.exists()) { to.createNewFile(); copy = true; } if (copy) { FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } catch (IOException e) { Logger.error(UserManagerPropertiesFactory.class, "_checkLanguagesFiles:Property File Copy Failed " + e, e); } }
|
00
|
Code Sample 1:
public static String hash(String password) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(password.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(Hex.encodeHex(rawHash)); } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
private static boolean hardCopy(File sourceFile, File destinationFile, StringBuffer errorLog) { boolean result = true; try { notifyCopyStart(destinationFile); destinationFile.getParentFile().mkdirs(); byte[] buffer = new byte[4096]; int len = 0; FileInputStream in = new FileInputStream(sourceFile); FileOutputStream out = new FileOutputStream(destinationFile); while ((len = in.read(buffer)) != -1) out.write(buffer, 0, len); in.close(); out.close(); } catch (Exception e) { result = false; handleException("\n Error in method: copy!\n", e, errorLog); } finally { notifyCopyEnd(destinationFile); } return result; }
|
00
|
Code Sample 1:
public List<String> getFtpFileList(String serverIp, int port, String user, String password, String synchrnPath) throws Exception { List<String> list = new ArrayList<String>(); FTPClient ftpClient = new FTPClient(); ftpClient.setControlEncoding("euc-kr"); if (!EgovWebUtil.isIPAddress(serverIp)) { throw new RuntimeException("IP is needed. (" + serverIp + ")"); } InetAddress host = InetAddress.getByName(serverIp); ftpClient.connect(host, port); ftpClient.login(user, password); ftpClient.changeWorkingDirectory(synchrnPath); FTPFile[] fTPFile = ftpClient.listFiles(synchrnPath); for (int i = 0; i < fTPFile.length; i++) { list.add(fTPFile[i].getName()); } return list; }
Code Sample 2:
private static Object readFileOrUrl(String path, boolean convertToString) throws IOException { URL url = null; if (path.indexOf(':') >= 2) { try { url = new URL(path); } catch (MalformedURLException ex) { } } InputStream is = null; int capacityHint = 0; if (url == null) { File file = new File(path); capacityHint = (int) file.length(); try { is = new FileInputStream(file); } catch (IOException ex) { Context.reportError(getMessage("msg.couldnt.open", path)); throw ex; } } else { try { URLConnection uc = url.openConnection(); is = uc.getInputStream(); capacityHint = uc.getContentLength(); if (capacityHint > (1 << 20)) { capacityHint = -1; } } catch (IOException ex) { Context.reportError(getMessage("msg.couldnt.open.url", url.toString(), ex.toString())); throw ex; } } if (capacityHint <= 0) { capacityHint = 4096; } byte[] data; try { try { is = new BufferedInputStream(is); data = Kit.readStream(is, capacityHint); } finally { is.close(); } } catch (IOException ex) { Context.reportError(ex.toString()); throw ex; } Object result; if (convertToString) { result = new String(data); } else { result = data; } return result; }
|
00
|
Code Sample 1:
public static void copyFile(File src, File dst) throws IOException { LOGGER.info("Copying file '" + src.getAbsolutePath() + "' to '" + dst.getAbsolutePath() + "'"); FileChannel in = null; FileChannel out = null; try { FileInputStream fis = new FileInputStream(src); in = fis.getChannel(); FileOutputStream fos = new FileOutputStream(dst); out = fos.getChannel(); out.transferFrom(in, 0, in.size()); } finally { try { if (in != null) in.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } if (out != null) { try { out.close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } } }
Code Sample 2:
public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Currency curr = (Currency) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_CURRENCY")); pst.setString(1, curr.getName()); pst.setInt(2, curr.getIdBase()); pst.setDouble(3, curr.getValue()); insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from currency"); rs.next(); id = rs.getInt(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 id; }
|
00
|
Code Sample 1:
public synchronized String encrypt(String p_plainText) throws ServiceUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new ServiceUnavailableException(e.getMessage()); } try { md.update(p_plainText.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new ServiceUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public static void decompressGZIP(File gzip, File to, long skip) throws IOException { GZIPInputStream gis = null; BufferedOutputStream bos = null; try { bos = new BufferedOutputStream(new FileOutputStream(to)); FileInputStream fis = new FileInputStream(gzip); fis.skip(skip); gis = new GZIPInputStream(fis); final byte[] buffer = new byte[IO_BUFFER]; int read = -1; while ((read = gis.read(buffer)) != -1) { bos.write(buffer, 0, read); } } finally { try { gis.close(); } catch (Exception nope) { } try { bos.flush(); } catch (Exception nope) { } try { bos.close(); } catch (Exception nope) { } } }
|
00
|
Code Sample 1:
public static String md5Encode(String s) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(s.getBytes()); return toHexString(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return s; } }
Code Sample 2:
public static byte[] getbytes(String host, int port, String cmd) { String result = "GetHtmlFromServer no answer"; String tmp = ""; result = ""; try { tmp = "http://" + host + ":" + port + "/" + cmd; URL url = new URL(tmp); if (1 == 2) { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result += str; } in.close(); return result.getBytes(); } else { HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setConnectTimeout(2 * 1000); c.setRequestMethod("GET"); c.connect(); int amt = c.getContentLength(); InputStream in = c.getInputStream(); MojasiWriter writer = new MojasiWriter(); byte[] buff = new byte[256]; while (writer.size() < amt) { int got = in.read(buff); if (got < 0) break; writer.pushBytes(buff, got); } in.close(); c.disconnect(); return writer.getBytes(); } } catch (MalformedURLException e) { System.err.println(tmp + " " + e); } catch (IOException e) { ; } return null; }
|
11
|
Code Sample 1:
public static void copy(File src, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); }
Code Sample 2:
public static Image load(final InputStream input, String format, Point dimension) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = null; ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format); dotOutput.delete(); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); status.add(result); status.add(logInput(dotContents)); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); ImageLoader loader = new ImageLoader(); ImageData[] imageData = loader.load(dotOutput.getAbsolutePath()); return new Image(Display.getDefault(), imageData[0]); } } catch (SWTException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); dotOutput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
|
00
|
Code Sample 1:
public String FTPupload(String filepath) { String fileUrl = null; Long clicks = System.currentTimeMillis(); String currentDateTimeString = clicks.toString(); String[] tmpSplite = filepath.split("/"); String filename = currentDateTimeString + tmpSplite[tmpSplite.length - 1]; String host = "140.112.31.165:8080/sound/"; Log.d("test", "get in"); FTPClient ftp = new FTPClient(); Log.d("test", "initial ftp"); try { ftp.connect("140.112.31.165"); ftp.enterLocalPassiveMode(); Log.d("test", "we connected"); if (!ftp.login("tacowu", "4565686")) { ftp.logout(); return fileUrl; } int replyCode = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(replyCode)) { Log.d("test", "get in trouble"); ftp.disconnect(); return fileUrl; } Log.d("test", "we logged in"); ftp.setFileType(ftp.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); File file = new File(filepath); if (file == null) Log.d("test", "file open faild"); else Log.d("test", "file open sucess"); FileInputStream aInputStream = new FileInputStream(file); boolean aRtn = ftp.storeFile(filename, aInputStream); aInputStream.close(); ftp.disconnect(); } catch (Exception ex) { } fileUrl = host + filename; return fileUrl; }
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); } }
|
00
|
Code Sample 1:
private static void run(Display display, int x) { Shell shell = new Shell(display); shell.setBounds(0, 0, 350, 350); shell.setLayout(new FillLayout(SWT.VERTICAL)); ERDiagramEditPartFactory editPartFactory = new ERDiagramEditPartFactory(); GraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.setControl(new FigureCanvas(shell)); ScalableFreeformRootEditPart rootEditPart = new PagableFreeformRootEditPart(diagram); viewer.setRootEditPart(rootEditPart); viewer.setEditPartFactory(editPartFactory); viewer.setContents(diagram); viewer.getContents().refresh(); shell.pack(); shell.open(); int count = 0; while (count < x) { if (!display.readAndDispatch()) { try { Thread.sleep(1000); count++; } catch (InterruptedException e) { e.printStackTrace(); } } } viewer.getContents().deactivate(); }
Code Sample 2:
public void access() { Authenticator.setDefault(new MyAuthenticator()); try { URL url = new URL("http://localhost/ws/test"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
|
11
|
Code Sample 1:
public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (Exception e) { e.printStackTrace(); mDigest = null; } if (mDigest == null) return null; byte[] raw = mDigest.digest(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(raw); }
Code Sample 2:
private String endcodePassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); Base64 base64 = new Base64(); String hash = new String(base64.encode(raw)); return hash; }
|
11
|
Code Sample 1:
private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(this, "Property File save Failed " + e, e); } } SessionMessages.add(req, "message", "message.languagemanager.save"); }
Code Sample 2:
public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data.txt").getChannel(); fc.write(ByteBuffer.wrap("some text ".getBytes())); fc.close(); fc = new RandomAccessFile("data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("some more".getBytes())); fc.close(); fc = new FileInputStream("data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { PrintUtil.prt((char) buff.get()); } }
|
00
|
Code Sample 1:
private static HttpURLConnection _getConnection(HttpPrincipal httpPrincipal) throws IOException { if (httpPrincipal == null || httpPrincipal.getUrl() == null) { return null; } URL url = null; if ((httpPrincipal.getUserId() <= 0) || (httpPrincipal.getPassword() == null)) { url = new URL(httpPrincipal.getUrl() + "/tunnel-web/liferay/do"); } else { url = new URL(httpPrincipal.getUrl() + "/tunnel-web/secure/liferay/do"); } HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setDoInput(true); urlc.setDoOutput(true); urlc.setUseCaches(false); urlc.setRequestMethod("POST"); if ((httpPrincipal.getUserId() > 0) && (httpPrincipal.getPassword() != null)) { String userNameAndPassword = httpPrincipal.getUserId() + ":" + httpPrincipal.getPassword(); urlc.setRequestProperty("Authorization", "Basic " + Base64.encode(userNameAndPassword.getBytes())); } return urlc; }
Code Sample 2:
public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; }
|
11
|
Code Sample 1:
public int process(ProcessorContext context) throws InterruptedException, ProcessorException { logger.info("JAISaveTask:process"); final RenderedOp im = (RenderedOp) context.get("RenderedOp"); final String path = "s3://s3.amazonaws.com/rssfetch/" + (new Guid()); final PNGEncodeParam.RGB encPar = new PNGEncodeParam.RGB(); encPar.setTransparentRGB(new int[] { 0, 0, 0 }); File tmpFile = null; try { tmpFile = File.createTempFile("thmb", ".png"); OutputStream out = new FileOutputStream(tmpFile); final ParameterBlock pb = (new ParameterBlock()).addSource(im).add(out).add("png").add(encPar); JAI.create("encode", pb, null); out.flush(); out.close(); FileInputStream in = new FileInputStream(tmpFile); final XFile xfile = new XFile(path); final XFileOutputStream xout = new XFileOutputStream(xfile); final com.luzan.common.nfs.s3.XFileExtensionAccessor xfa = ((com.luzan.common.nfs.s3.XFileExtensionAccessor) xfile.getExtensionAccessor()); if (xfa != null) { xfa.setMimeType("image/png"); xfa.setContentLength(tmpFile.length()); } IOUtils.copy(in, xout); xout.flush(); xout.close(); in.close(); context.put("outputPath", path); } catch (IOException e) { logger.error(e); throw new ProcessorException(e); } catch (Throwable e) { logger.error(e); throw new ProcessorException(e); } finally { if (tmpFile != null && tmpFile.exists()) { tmpFile.delete(); } } return TaskState.STATE_MO_START + TaskState.STATE_ENCODE; }
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(); }
|
11
|
Code Sample 1:
public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
Code Sample 2:
@Override public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException, NotAuthorizedException, BadRequestException, NotFoundException { try { resolveFileAttachment(); } catch (NoFileByTheIdException e) { throw new NotFoundException(e.getLocalizedMessage()); } DefinableEntity owningEntity = fa.getOwner().getEntity(); InputStream in = getFileModule().readFile(owningEntity.getParentBinder(), owningEntity, fa); try { if (range != null) { if (logger.isDebugEnabled()) logger.debug("sendContent: ranged content: " + toString(fa)); PartialGetHelper.writeRange(in, range, out); } else { if (logger.isDebugEnabled()) logger.debug("sendContent: send whole file " + toString(fa)); IOUtils.copy(in, out); } out.flush(); } catch (ReadingException e) { throw new IOException(e); } catch (WritingException e) { throw new IOException(e); } finally { IOUtils.closeQuietly(in); } }
|
11
|
Code Sample 1:
public static String generateDigest(String password, String saltHex, String alg) { try { MessageDigest sha = MessageDigest.getInstance(alg); byte[] salt = new byte[0]; if (saltHex != null) { salt = fromHex(saltHex); } String label = null; if (alg.startsWith("SHA")) { label = (salt.length <= 0) ? "{SHA}" : "{SSHA}"; } else if (alg.startsWith("MD5")) { label = (salt.length <= 0) ? "{MD5}" : "{SMD5}"; } sha.reset(); sha.update(password.getBytes()); sha.update(salt); byte[] pwhash = sha.digest(); StringBuffer digest = new StringBuffer(label); digest.append(Base64.encode(concatenate(pwhash, salt)).toCharArray()); return digest.toString(); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException("failed to find " + "algorithm for password hashing.", nsae); } }
Code Sample 2:
private static String md5Encode(String pass) { String string; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); string = bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La libreria java.security no implemente MD5"); } return string; }
|
00
|
Code Sample 1:
public static boolean start(RootDoc root) { Logger log = Logger.getLogger("DocletGenerator"); if (destination == null) { try { ruleListenerDef = IOUtils.toString(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/RuleListenersFragment.xsd"), "UTF-8"); String fn = System.getenv("annocultor.xconverter.destination.file.name"); fn = (fn == null) ? "./../../../src/site/resources/schema/XConverterInclude.xsd" : fn; destination = new File(fn); if (destination.exists()) { destination.delete(); } FileOutputStream os; os = new FileOutputStream(new File(destination.getParentFile(), "XConverter.xsd")); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterTemplate.xsd")), os); os.close(); os = new FileOutputStream(destination); IOUtils.copy(new AutoCloseInputStream(GeneratorOfXmlSchemaForConvertersDoclet.class.getResourceAsStream("/XConverterInclude.xsd")), os); os.close(); } catch (Exception e) { try { throw new RuntimeException("On destination " + destination.getCanonicalPath(), e); } catch (IOException e1) { throw new RuntimeException(e1); } } } try { String s = Utils.loadFileToString(destination.getCanonicalPath(), "\n"); int breakPoint = s.indexOf(XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); if (breakPoint < 0) { throw new Exception("Signature not found in XSD: " + XSD_TEXT_TO_REPLACED_WITH_GENERATED_XML_SIGNATURES); } String preambula = s.substring(0, breakPoint); String appendix = s.substring(breakPoint); destination.delete(); PrintWriter schemaWriter = new PrintWriter(destination); schemaWriter.print(preambula); ClassDoc[] classes = root.classes(); for (int i = 0; i < classes.length; ++i) { ClassDoc cd = classes[i]; PrintWriter documentationWriter = null; if (getSuperClasses(cd).contains(Rule.class.getName())) { for (ConstructorDoc constructorDoc : cd.constructors()) { if (constructorDoc.isPublic()) { if (isMeantForXMLAccess(constructorDoc)) { if (documentationWriter == null) { File file = new File("./../../../src/site/xdoc/rules." + cd.name() + ".xml"); documentationWriter = new PrintWriter(file); log.info("Generating doc for rule " + file.getCanonicalPath()); printRuleDocStart(cd, documentationWriter); } boolean initFound = false; for (MethodDoc methodDoc : cd.methods()) { if ("init".equals(methodDoc.name())) { if (methodDoc.parameters().length == 0) { initFound = true; break; } } } if (!initFound) { } printConstructorSchema(constructorDoc, schemaWriter); if (documentationWriter != null) { printConstructorDoc(constructorDoc, documentationWriter); } } } } } if (documentationWriter != null) { printRuleDocEnd(documentationWriter); } } schemaWriter.print(appendix); schemaWriter.close(); log.info("Saved to " + destination.getCanonicalPath()); } catch (Exception e) { throw new RuntimeException(e); } return true; }
Code Sample 2:
public static String get(String strUrl) { try { URL url = new URL(strUrl); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String s = ""; String sRet = ""; while ((s = in.readLine()) != null) { sRet += s; } return sRet; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; }
|
11
|
Code Sample 1:
private String generateUniqueIdMD5(Run run, HttpServletRequest request, String groupIdString) { String portalUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); String uniqueportalUrl = portalUrl + "run:" + run.getId().toString() + "group:" + groupIdString; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(uniqueportalUrl.getBytes(), 0, uniqueportalUrl.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; }
Code Sample 2:
public void onItem(FeedParserState state, String title, String link, String description, String permalink) throws FeedParserException { if (counter >= MAX_FEEDS) { throw new FeedPollerCancelException("Maximum number of items reached"); } boolean canAnnounce = false; try { if (lastDigest == null) { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); lastDigest = md.digest(); canAnnounce = true; } else { MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(title.getBytes()); byte[] currentDigest = md.digest(); if (!MessageDigest.isEqual(currentDigest, lastDigest)) { lastDigest = currentDigest; canAnnounce = true; } } if (canAnnounce) { String shortTitle = title; if (shortTitle.length() > TITLE_MAX_LEN) { shortTitle = shortTitle.substring(0, TITLE_MAX_LEN) + " ..."; } String shortLink = IOUtil.getTinyUrl(link); Log.debug("Link:" + shortLink); for (Channel channel : channels) { channel.say(String.format("%s, %s", shortTitle, shortLink)); } } } catch (Exception e) { throw new FeedParserException(e); } counter++; }
|
00
|
Code Sample 1:
private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } }
Code Sample 2:
public void setPassword(String plaintext) throws java.security.NoSuchAlgorithmException { StringBuffer encrypted = new StringBuffer(); java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(plaintext.getBytes()); byte[] digestArray = digest.digest(); for (int i = 0; i < digestArray.length; i++) { encrypted.append(byte2hex(digestArray[i])); } setEncryptedPassword(encrypted.toString()); }
|
11
|
Code Sample 1:
public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } }
Code Sample 2:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final 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(); } } }
|
11
|
Code Sample 1:
private void copyFile(String file) { FileChannel inChannel = null; FileChannel outChannel = null; try { Date dt = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss "); File in = new File(file); String[] name = file.split("\\\\"); File out = new File(".\\xml_archiv\\" + df.format(dt) + name[name.length - 1]); inChannel = new FileInputStream(in).getChannel(); outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { System.err.println("Copy error!"); System.err.println("Error: " + e.getMessage()); } finally { if (inChannel != null) { try { inChannel.close(); } catch (IOException ex) { Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex); } } if (outChannel != null) { try { outChannel.close(); } catch (IOException ex) { Logger.getLogger(ImportIntoDb.class.getName()).log(Level.SEVERE, null, ex); } } } }
Code Sample 2:
private void copy(File source, File destination) throws PackageException { try { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(destination); byte[] buff = new byte[1024]; int len; while ((len = in.read(buff)) > 0) out.write(buff, 0, len); in.close(); out.close(); } catch (IOException e) { throw new PackageException("Unable to copy " + source.getPath() + " to " + destination.getPath() + " :: " + e.toString()); } }
|
00
|
Code Sample 1:
private void createNodes() { try { URL url = this.getClass().getResource("NodesFile.txt"); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); String s; while ((s = inNodes.readLine()) != null) { String label = inNodes.readLine(); String fullText = inNodes.readLine(); String type = inNodes.readLine(); Node n = new Node(s, type); n.label = label; n.fullText = fullText; node.add(n); } inNodes.close(); url = this.getClass().getResource("EdgesFile.txt"); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
void bubbleSort(int ids[]) { boolean flag = true; int temp; while (flag) { flag = false; for (int i = 0; i < ids.length - 1; i++) if (ids[i] < ids[i + 1]) { temp = ids[i]; ids[i] = ids[i + 1]; ids[i + 1] = temp; flag = true; } } }
|
00
|
Code Sample 1:
public void generate(String rootDir, RootModel root) throws Exception { IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("stylesheet.css"), new FileOutputStream(new File(rootDir, "stylesheet.css"))); Velocity.init(); VelocityContext context = new VelocityContext(); context.put("model", root); context.put("util", new VelocityUtils()); context.put("msg", messages); processTemplate("index.html", new File(rootDir, "index.html"), context); processTemplate("list.html", new File(rootDir, "list.html"), context); processTemplate("summary.html", new File(rootDir, "summary.html"), context); File imageDir = new File(rootDir, "images"); imageDir.mkdir(); IOUtils.copyStream(HTMLGenerator.class.getResourceAsStream("primarykey.gif"), new FileOutputStream(new File(imageDir, "primarykey.gif"))); File tableDir = new File(rootDir, "tables"); tableDir.mkdir(); for (TableModel table : root.getTables()) { context.put("table", table); processTemplate("table.html", new File(tableDir, table.getTableName() + ".html"), context); } }
Code Sample 2:
public static BufferedImage readDicom(final URL url, final SourceImage src) { assert url != null; assert src != null; BufferedImage bi = null; try { DicomInputStream dis = new DicomInputStream(new BufferedInputStream(url.openStream())); src.read(dis); dis.close(); bi = src.getBufferedImage(); } catch (Exception exc) { System.out.println("ImageFactory::readDicom(): exc=" + exc); } return bi; }
|
00
|
Code Sample 1:
public void init() { System.out.println("Init applet..."); int port = Integer.parseInt(getParameter("port")); int useUDP = Integer.parseInt(getParameter("udp")); boolean bUseUDP = false; if (useUDP > 0) bUseUDP = true; m_strWorld = getParameter("world"); m_strHost = this.getCodeBase().getHost(); try { new EnvironmentMap(getParameter("vrwmap")); } catch (Throwable t) { System.out.println(t.getMessage()); } URL urlExperiment = null; InputStream expStream = null; try { String strPathExperiment = getParameter("experiment"); if (strPathExperiment.length() > 0) { urlExperiment = new URL(getCodeBase(), strPathExperiment); expStream = urlExperiment.openStream(); } } catch (java.net.MalformedURLException e) { System.out.println("Couldn't open url experiment: badly specified URL " + e.getMessage()); } catch (Throwable t) { System.out.println("Couldn't open url experiment: " + t.getMessage()); } try { System.out.println("Creating client, logging to " + m_strWorld); m_VRWClient = new VRWClient(m_strHost, port, true, bUseUDP); m_VRWClient.setInApplet(true); m_VRWClient.login(m_strWorld); } catch (java.io.IOException e) { System.out.println("IOException creating the VRWClient"); } try { jsobj = JSObject.getWindow(this); } catch (Throwable t) { System.out.println("Exception getting Java Script Interface: " + t.getMessage()); } refApplet = this; m_frmVRWConsole = new VRWConsoleFrame(); m_frmVRWConsole.setTitle("VRW Client Console"); m_frmVRWConsole.pack(); m_frmVRWConsole.setSize(Math.max(300, m_frmVRWConsole.getSize().width), Math.max(200, m_frmVRWConsole.getSize().height)); if (expStream != null) { System.out.println("Passing experiment stream to VRWConsoleFrame"); m_frmVRWConsole.loadExperiment(expStream); } m_frmVRWConsole.setVisible(true); }
Code Sample 2:
void shutdown(final boolean unexpected) { if (unexpected) { log.warn("S H U T D O W N --- received unexpected shutdown request."); } else { log.info("S H U T D O W N --- start regular shutdown."); } if (this.uncaughtException != null) { log.warn("Shutdown probably caused by the following Exception.", this.uncaughtException); } log.error("check if we need the controler listener infrastructure"); if (this.dumpDataAtEnd) { new PopulationWriter(this.population, this.network).write(this.controlerIO.getOutputFilename(FILENAME_POPULATION)); new NetworkWriter(this.network).write(this.controlerIO.getOutputFilename(FILENAME_NETWORK)); new ConfigWriter(this.config).write(this.controlerIO.getOutputFilename(FILENAME_CONFIG)); if (!unexpected && this.getConfig().vspExperimental().isWritingOutputEvents()) { File toFile = new File(this.controlerIO.getOutputFilename("output_events.xml.gz")); File fromFile = new File(this.controlerIO.getIterationFilename(this.getLastIteration(), "events.xml.gz")); IOUtils.copyFile(fromFile, toFile); } } if (unexpected) { log.info("S H U T D O W N --- unexpected shutdown request completed."); } else { log.info("S H U T D O W N --- regular shutdown completed."); } try { Runtime.getRuntime().removeShutdownHook(this.shutdownHook); } catch (IllegalStateException e) { log.info("Cannot remove shutdown hook. " + e.getMessage()); } this.shutdownHook = null; this.collectLogMessagesAppender = null; IOUtils.closeOutputDirLogging(); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws Exception { if (args.length < 3) { usage(System.out); System.exit(1); } final File tmpFile = File.createTempFile("sej", null); tmpFile.deleteOnExit(); final FileOutputStream destination = new FileOutputStream(tmpFile); final String mainClass = args[1]; final Collection jars = new LinkedList(); for (int i = 2; i < args.length; i++) { String arg = args[i]; jars.add(arg); } JarInterpretted interpretted = new JarInterpretted(destination); JarCat rowr = new JarCat(destination, createManifest(mainClass), jars); interpretted.write(); rowr.write(); destination.close(); final File finalDestinationFile = new File(args[0]); final FileOutputStream finalDestination = new FileOutputStream(finalDestinationFile); IOUtils.copy(new FileInputStream(tmpFile), finalDestination); finalDestination.close(); Chmod chmod = new Chmod("a+rx", new File[] { finalDestinationFile }); chmod.invoke(); }
Code Sample 2:
private void copy(File from, File to) { if (from.isDirectory()) { File[] files = from.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { File newTo = new File(to.getPath() + File.separator + files[i].getName()); newTo.mkdirs(); copy(files[i], newTo); } else { copy(files[i], to); } } } else { try { to = new File(to.getPath() + File.separator + from.getName()); to.createNewFile(); FileChannel src = new FileInputStream(from).getChannel(); FileChannel dest = new FileOutputStream(to).getChannel(); dest.transferFrom(src, 0, src.size()); dest.close(); src.close(); } catch (FileNotFoundException e) { errorLog(e.toString()); e.printStackTrace(); } catch (IOException e) { errorLog(e.toString()); e.printStackTrace(); } } }
|
11
|
Code Sample 1:
private static void readIzvestiyaArticles() throws IOException { CsvReader reader = new CsvReader(new InputStreamReader(IzvestiyaUtil.class.getClassLoader().getResourceAsStream("mathnet_izvestiya.csv")), ';'); reader.setTrimWhitespace(true); try { while (reader.readRecord()) { String id = reader.get(0); String filename = reader.get(1); StringTokenizer st = new StringTokenizer(filename, "-."); String name = st.nextToken(); String volume = st.nextToken(); String year = st.nextToken(); String extension = st.nextToken(); String filepath = String.format("%s/%s/%s-%s.%s", year, volume.length() == 1 ? "0" + volume : volume, name, volume, extension); id2filename.put(id, filepath); } } finally { reader.close(); } for (Map.Entry<String, String> entry : id2filename.entrySet()) { String filepath = String.format("%s/%s", INPUT_DIR, entry.getValue()); filepath = new File(filepath).exists() ? filepath : filepath.replace(".tex", ".TEX"); if (new File(filepath).exists()) { InputStream in = new FileInputStream(filepath); FileOutputStream out = new FileOutputStream(String.format("%s/%s.tex", OUTPUT_DIR, entry.getKey()), false); try { org.apache.commons.io.IOUtils.copy(in, out); } catch (Exception e) { org.apache.commons.io.IOUtils.closeQuietly(in); org.apache.commons.io.IOUtils.closeQuietly(out); } } else { logger.log(Level.INFO, "File with the path=" + filepath + " doesn't exist"); } } }
Code Sample 2:
@Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { String resourceDir = System.getProperty("resourceDir"); File resource = new File(resourceDir, filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (resource.exists()) { in = new FileInputStream(resource); } else { in = LOADER.getResourceAsStream(RES_PKG + filename); } IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
|
00
|
Code Sample 1:
public URL rawGetURLfromWebID(String id) { try { System.out.println("Resolving id" + id); String resolve = "/webid/ResolverServlet?wpid=MeetingMachine&method=form&uri=" + id + "&href=_[text/url]"; String resolver = "http://webid.hpl.hp.com:5190"; URL url = new URL(resolve + resolver); URLConnection c = url.openConnection(); c.setDoOutput(true); c.setDoInput(true); c.setUseCaches(false); } catch (Exception e) { if (PropertyEventHeap.debug) { PropertyEventHeap.log("rawGetURLfromWebID " + e); } } return null; }
Code Sample 2:
public void saveAs(File f) throws CoverException { FileOutputStream fw = null; BufferedInputStream in = null; try { HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setDoInput(true); in = new BufferedInputStream(httpConn.getInputStream()); f.delete(); fw = new FileOutputStream(f); int b; while ((b = in.read()) != -1) fw.write(b); fw.close(); in.close(); } catch (IOException e) { throw new CoverException(e.getMessage()); } finally { try { if (fw != null) fw.close(); if (in != null) in.close(); } catch (IOException ex) { System.err.println("Glurps this is severe: " + ex.getMessage()); } } }
|
11
|
Code Sample 1:
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
11
|
Code Sample 1:
public JSONObject getTargetGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph tgt = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { tgt = manager.getTargetGraph(); if (tgt != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.ORANGES); factory.visit(tgt); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No target graph loaded."); } } catch (Exception e) { return JSONUtils.SimpleJSONError("Cannot load target graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); }
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 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 < 2) { System.out.println(" *** DDL (creates) and DML (inserts) script importer from DB ***"); System.out.println(" You must specify name of the file with script importing 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 sufficient priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have:"); System.out.println(" '}' before table to create,"); System.out.println(" '{' before schema to create tables in,"); System.out.println(" ')' before table to insert into,"); System.out.println(" '(' before schema to insert into tables in."); 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(" 2nd command line argument is name of output file;"); System.out.println(" if its extension is *.sql, its format is standard SQL"); System.out.println(" otherwize format is short one, understanded by SQLScript tool"); System.out.println(" Connection information remains unchanged in the last format"); System.out.println(" but in the first one it takes form 'connect user/password@URL'"); System.out.println(" where URL can be formed with different rools for different DBMSs"); System.out.println(" If file (with short format header) already exists and you specify"); System.out.println(" 3rd command line argument -db, we generate objects in the database"); System.out.println(" (known from the file header; must differ from 1st DB) but not in file"); System.out.println(" Note: when importing to a file of short format, line separators"); System.out.println(" in VARCHARS will be lost; LOBs will be empty for any file"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; Connection outConnection = null; try { for (int i = 0; i < info.length; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); int format = args[1].toLowerCase().endsWith("sql") ? SQL_FORMAT : SHORT_FORMAT; File file = new File(args[1]); if (format == SHORT_FORMAT) { if (file.exists() && args.length > 2 && args[2].equalsIgnoreCase("-db")) { String[] outInfo = new String[info.length]; BufferedReader outReader = new BufferedReader(new FileReader(file)); for (int i = 0; i < outInfo.length; i++) outInfo[i] = reader.readLine(); outReader.close(); if (!(outInfo[1].equals(info[1]) && outInfo[2].equals(info[2]))) { Class.forName(info[0]); outConnection = DriverManager.getConnection(outInfo[1], outInfo[2], outInfo[3]); format = SQL_FORMAT; } } } if (outConnection == null) writer = new BufferedWriter(new FileWriter(file)); SQLImporter script = new SQLImporter(outConnection, connection); script.setFormat(format); if (format == SQL_FORMAT) { writer.write("connect " + info[2] + "/" + info[3] + "@" + script.getDatabaseURL(info[1]) + script.statementTerminator); } else { for (int i = 0; i < info.length; i++) writer.write(info[i] + lineSep); writer.write(lineSep); } try { System.out.println(script.executeScript(reader, writer) + " operations with tables has been generated during import"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); else outConnection.close(); System.out.println(" Script generation 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"); } }
|
11
|
Code Sample 1:
public static void copyFile(IPath fromFileName, IPath toFileName) throws IOException { File fromFile = fromFileName.toFile(); File toFile = toFileName.toFile(); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } InputStream from = null; OutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(fromFile)); to = new BufferedOutputStream(new FileOutputStream(toFile)); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { } if (to != null) try { to.close(); } catch (IOException e) { } } }
Code Sample 2:
public DataRecord addRecord(InputStream input) throws DataStoreException { File temporary = null; try { temporary = newTemporaryFile(); DataIdentifier tempId = new DataIdentifier(temporary.getName()); usesIdentifier(tempId); long length = 0; MessageDigest digest = MessageDigest.getInstance(DIGEST); OutputStream output = new DigestOutputStream(new FileOutputStream(temporary), digest); try { length = IOUtils.copyLarge(input, output); } finally { output.close(); } DataIdentifier identifier = new DataIdentifier(digest.digest()); File file; synchronized (this) { usesIdentifier(identifier); file = getFile(identifier); System.out.println("new file name: " + file.getName()); File parent = file.getParentFile(); System.out.println("parent file: " + file.getParentFile().getName()); if (!parent.isDirectory()) { parent.mkdirs(); } if (!file.exists()) { temporary.renameTo(file); if (!file.exists()) { throw new IOException("Can not rename " + temporary.getAbsolutePath() + " to " + file.getAbsolutePath() + " (media read only?)"); } } else { long now = System.currentTimeMillis(); if (file.lastModified() < now) { file.setLastModified(now); } } if (!file.isFile()) { throw new IOException("Not a file: " + file); } if (file.length() != length) { throw new IOException(DIGEST + " collision: " + file); } } inUse.remove(tempId); return new FileDataRecord(identifier, file); } catch (NoSuchAlgorithmException e) { throw new DataStoreException(DIGEST + " not available", e); } catch (IOException e) { throw new DataStoreException("Could not add record", e); } finally { if (temporary != null) { temporary.delete(); } } }
|
11
|
Code Sample 1:
public boolean copy(File fromFile) throws IOException { FileUtility toFile = this; if (!fromFile.exists()) { abort("FileUtility: no such source file: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.isFile()) { abort("FileUtility: can't copy directory: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.canRead()) { abort("FileUtility: source file is unreadable: " + fromFile.getAbsolutePath()); return false; } if (this.isDirectory()) toFile = (FileUtility) (new File(this, fromFile.getName())); if (toFile.exists()) { if (!toFile.canWrite()) { abort("FileUtility: destination file is unwriteable: " + pathName); return false; } } else { String parent = toFile.getParent(); File dir = new File(parent); if (!dir.exists()) { abort("FileUtility: destination directory doesn't exist: " + parent); return false; } if (dir.isFile()) { abort("FileUtility: destination is not a directory: " + parent); return false; } if (!dir.canWrite()) { abort("FileUtility: destination directory is unwriteable: " + parent); return false; } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } return true; }
Code Sample 2:
public static void copyFile(File source, File destination) throws IOException { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = null; try { fos = new FileOutputStream(destination); FileChannel sourceChannel = fis.getChannel(); FileChannel destinationChannel = fos.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); destinationChannel.close(); sourceChannel.close(); } finally { if (fos != null) fos.close(); fis.close(); } }
|
00
|
Code Sample 1:
@Override public Object init() throws Exception { if (url != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); ClassLoader parent = getClass().getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); Class groovyClass = loader.parseClass(new File(url.getFile())); groovyObject = (GroovyObject) groovyClass.newInstance(); reader.close(); initDeclaredMethods(); return groovyObject; } else return null; }
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 String calculateMD5(String s) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(s.getBytes()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException e) { throw new UndeclaredThrowableException(e); } }
Code Sample 2:
public static void copy(File from, File to, int bufferSize) throws IOException { if (to.exists()) { logger.info("File " + to + " exists, will replace it."); to.delete(); } to.getParentFile().mkdirs(); to.createNewFile(); FileInputStream ois = null; FileOutputStream cos = null; try { ois = new FileInputStream(from); cos = new FileOutputStream(to); byte[] buf = new byte[bufferSize]; int read; while ((read = ois.read(buf, 0, bufferSize)) > 0) { cos.write(buf, 0, read); } cos.flush(); } finally { try { if (ois != null) ois.close(); } catch (IOException ignored) { logger.warn("Could not close file input stream " + from, ignored); } try { if (cos != null) { cos.close(); } } catch (IOException ignored) { logger.warn("Could not close file output stream " + to, ignored); } } }
|
00
|
Code Sample 1:
public static boolean URLExists(URL url) { int responseCode = -1; boolean exists = true; try { if (useHttpURLConnection && url.getProtocol().equals("http")) { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); responseCode = conn.getResponseCode(); if (!(responseCode >= 200 && responseCode < 400)) exists = false; conn.disconnect(); } else { InputStream testStream = url.openStream(); } } catch (IOException ioe) { exists = false; } return exists; }
Code Sample 2:
private void initBanner() { for (int k = 0; k < 3; k++) { if (bannerImg == null) { int i = getRandomId(); imageURL = NbBundle.getMessage(BottomContent.class, "URL_BannerImageLink", Integer.toString(i)); bannerURL = NbBundle.getMessage(BottomContent.class, "URL_BannerLink", Integer.toString(i)); HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet method = new HttpGet(imageURL); try { HttpResponse response = ProxyManager.httpClient.execute(method, context); HttpEntity entity = response.getEntity(); if (entity != null) { bannerImg = new ImageIcon(ImageIO.read(entity.getContent())); EntityUtils.consume(entity); } } catch (IOException ex) { bannerImg = null; } finally { method.abort(); } } else { break; } } if (bannerImg == null) { NotifyUtil.error("Banner Error", "Application could not get banner image. Please check your internet connection.", false); } }
|
11
|
Code Sample 1:
public static void copyTo(File inFile, File outFile) throws IOException { char[] cbuff = new char[32768]; BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile)); int readedBytes = 0; long absWrittenBytes = 0; while ((readedBytes = reader.read(cbuff, 0, cbuff.length)) != -1) { writer.write(cbuff, 0, readedBytes); absWrittenBytes += readedBytes; } reader.close(); writer.close(); }
Code Sample 2:
public static void copyFile(File src, File dest, boolean notifyUserOnError) { if (src.exists()) { try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(src)); byte[] read = new byte[128]; int len = 128; while ((len = in.read(read)) > 0) out.write(read, 0, len); out.flush(); out.close(); in.close(); } catch (IOException e) { String message = "Error while copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " : " + e.getMessage(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } } else { String message = "Unable to copy file: source does not exists: " + src.getAbsolutePath(); if (notifyUserOnError) { Log.getInstance(SystemUtils.class).warnWithUserNotification(message); } else { Log.getInstance(SystemUtils.class).warn(message); } } }
|
11
|
Code Sample 1:
public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
Code Sample 2:
public void readData(RowSetInternal caller) throws SQLException { Connection con = null; try { CachedRowSet crs = (CachedRowSet) caller; if (crs.getPageSize() == 0 && crs.size() > 0) { crs.close(); } writerCalls = 0; userCon = false; con = this.connect(caller); if (con == null || crs.getCommand() == null) throw new SQLException(resBundle.handleGetObject("crsreader.connecterr").toString()); try { con.setTransactionIsolation(crs.getTransactionIsolation()); } catch (Exception ex) { ; } PreparedStatement pstmt = con.prepareStatement(crs.getCommand()); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } if (crs.getCommand().toLowerCase().indexOf("select") != -1) { ResultSet rs = pstmt.executeQuery(); if (crs.getPageSize() == 0) { crs.populate(rs); } else { pstmt = con.prepareStatement(crs.getCommand(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); decodeParams(caller.getParams(), pstmt); try { pstmt.setMaxRows(crs.getMaxRows()); pstmt.setMaxFieldSize(crs.getMaxFieldSize()); pstmt.setEscapeProcessing(crs.getEscapeProcessing()); pstmt.setQueryTimeout(crs.getQueryTimeout()); } catch (Exception ex) { throw new SQLException(ex.getMessage()); } rs = pstmt.executeQuery(); crs.populate(rs, startPosition); } rs.close(); } else { pstmt.executeUpdate(); } pstmt.close(); try { con.commit(); } catch (SQLException ex) { ; } if (getCloseConnection() == true) con.close(); } catch (SQLException ex) { throw ex; } finally { try { if (con != null && getCloseConnection() == true) { try { if (!con.getAutoCommit()) { con.rollback(); } } catch (Exception dummy) { } con.close(); con = null; } } catch (SQLException e) { } } }
|
11
|
Code Sample 1:
public static String md5hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("MD5"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
Code Sample 2:
public static String hashClientPassword(String algorithm, String password, String salt) throws IllegalArgumentException, DruidSafeRuntimeException { if (algorithm == null) { throw new IllegalArgumentException("THE ALGORITHM MUST NOT BE NULL"); } if (password == null) { throw new IllegalArgumentException("THE PASSWORD MUST NOT BE NULL"); } if (salt == null) { salt = ""; } String result = null; try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(password.getBytes()); md.update(salt.getBytes()); result = SecurityHelper.byteArrayToHexString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new DruidSafeRuntimeException(e); } return result; }
|
00
|
Code Sample 1:
@Override public MapInfo getMap(int mapId) { MapInfo info = mapCache.get(mapId); if (info != null && info.getContent() == null) { if (info.getInfo().get("fileName") == null) { if (mapId != lastRequestedMap) { lastRequestedMap = mapId; System.out.println("MapLoaderClient::getMap:requesting map from server " + mapId); serverConnection.sendMessage(new MessageFetch(FetchType.map.name(), mapId)); } } else { try { System.out.println("MapLoaderClient::getMap:loading map from file " + info.getInfo().get("fileName")); BufferedReader bufferedreader; URL fetchUrl = new URL(localMapContextUrl, info.getInfo().get("fileName")); URLConnection urlconnection = fetchUrl.openConnection(); if (urlconnection.getContentEncoding() != null) { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), urlconnection.getContentEncoding())); } else { bufferedreader = new BufferedReader(new InputStreamReader(urlconnection.getInputStream(), "utf-8")); } String line; StringBuilder mapContent = new StringBuilder(); while ((line = bufferedreader.readLine()) != null) { mapContent.append(line); mapContent.append("\n"); } info.setContent(mapContent.toString()); fireMapChanged(info); } catch (IOException _ex) { System.err.println("MapLoaderClient::getMap:: Can't read from " + info.getInfo().get("fileName")); } } } return info; }
Code Sample 2:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
|
00
|
Code Sample 1:
public static void copyFile(File sourceFile, File targetFile) throws IOException { if (sourceFile == null || targetFile == null) { throw new NullPointerException("Source file and target file must not be null"); } File directory = targetFile.getParentFile(); if (!directory.exists() && !directory.mkdirs()) { throw new IOException("Could not create directory '" + directory + "'"); } InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); try { byte[] buffer = new byte[32768]; for (int readBytes = inputStream.read(buffer); readBytes > 0; readBytes = inputStream.read(buffer)) { outputStream.write(buffer, 0, readBytes); } } catch (IOException ex) { targetFile.delete(); throw ex; } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } }
Code Sample 2:
public static ByteBuffer readShaderBinary(Class context, String path) { try { URL url = Locator.getResource(context, path); if (url == null) { return null; } return StreamUtil.readAll2Buffer(new BufferedInputStream(url.openStream())); } catch (IOException e) { throw new RuntimeException(e); } }
|
00
|
Code Sample 1:
public void setPilot(PilotData pilotData) throws UsernameNotValidException { try { if (pilotData.username.trim().equals("") || pilotData.password.trim().equals("")) throw new UsernameNotValidException(1, "Username or password missing"); PreparedStatement psta; if (pilotData.id == 0) { psta = jdbc.prepareStatement("INSERT INTO pilot " + "(name, address1, address2, zip, city, state, country, birthdate, " + "pft_theory, pft, medical, passenger, instructor, loc_language, " + "loc_country, loc_variant, username, password, id) " + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); pilotData.id = Sequence.nextVal("pilot_id", jdbc); } else { psta = jdbc.prepareStatement("UPDATE pilot SET " + "name = ?, address1 = ?, address2 = ?, " + "zip = ?, city = ?, state = ?, country = ?, birthdate = ?, pft_theory = ?," + "pft = ?, medical = ?, passenger = ?, instructor = ?, loc_language = ?, " + "loc_country = ?, loc_variant = ?, username = ?, password = ? " + "WHERE id = ?"); } psta.setString(1, pilotData.name); psta.setString(2, pilotData.address1); psta.setString(3, pilotData.address2); psta.setString(4, pilotData.zip); psta.setString(5, pilotData.city); psta.setString(6, pilotData.state); psta.setString(7, pilotData.country); if (pilotData.birthdate != null) psta.setLong(8, pilotData.birthdate.getTime()); else psta.setNull(8, java.sql.Types.INTEGER); if (pilotData.pft_theory != null) psta.setLong(9, pilotData.pft_theory.getTime()); else psta.setNull(9, java.sql.Types.INTEGER); if (pilotData.pft != null) psta.setLong(10, pilotData.pft.getTime()); else psta.setNull(10, java.sql.Types.INTEGER); if (pilotData.medical != null) psta.setLong(11, pilotData.medical.getTime()); else psta.setNull(11, java.sql.Types.INTEGER); if (pilotData.passenger) psta.setString(12, "Y"); else psta.setString(12, "N"); if (pilotData.instructor) psta.setString(13, "Y"); else psta.setString(13, "N"); psta.setString(14, pilotData.loc_language); psta.setString(15, pilotData.loc_country); psta.setString(16, pilotData.loc_variant); psta.setString(17, pilotData.username); psta.setString(18, pilotData.password); psta.setInt(19, pilotData.id); psta.executeUpdate(); jdbc.commit(); } catch (SQLException sql) { jdbc.rollback(); sql.printStackTrace(); throw new UsernameNotValidException(2, "Username allready exist"); } }
Code Sample 2:
public static String getHash(String text) { if (text == null) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(text.getBytes()); byte[] hashedTextBytes = md.digest(); BigInteger hashedTextBigInteger = new BigInteger(1, hashedTextBytes); String hashedTextString = hashedTextBigInteger.toString(16); return hashedTextString; } catch (NoSuchAlgorithmException e) { LOG.warning(e.toString()); return null; } }
|
00
|
Code Sample 1:
private static URL getURL(String name) throws EfreetException { URL url = ClassLoader.getSystemResource(name + ".xml"); try { if (url == null) { try { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup("java:/comp/env"); String xmlFileDir = (String) envContext.lookup("xml/efreet"); url = new URL("file:" + xmlFileDir + "/" + name + ".xml"); } catch (NameNotFoundException nnfe) { logger.warn("Name not found on context "); } catch (NamingException e) { logger.error("Error retrieving Context : ", e); } } try { if (url != null) { url.openConnection(); } } catch (FileNotFoundException fnfe) { url = null; } if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(name + ".xml"); } } catch (IOException ioe) { logger.error("Error reading XML file", ioe); throw new EfreetException(ioe.getMessage()); } return url; }
Code Sample 2:
public static String getMD5(final String data) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.reset(); m.update(data.getBytes()); BigInteger bigInt = new BigInteger(1, m.digest()); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return e.getMessage(); } }
|
00
|
Code Sample 1:
protected PTask commit_result(Result r, SyrupConnection con) throws Exception { try { int logAction = LogEntry.ENDED; String kk = r.context().task().key(); if (r.in_1_consumed() && r.context().in_1_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, false, null, con); logAction = logAction | LogEntry.IN_1; } if (r.in_2_consumed() && r.context().in_2_link() != null) { sqlImpl().updateFunctions().updateInLink(kk, true, null, con); logAction = logAction | LogEntry.IN_2; } if (r.out_1_result() != null && r.context().out_1_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, false, r.out_1_result(), con); logAction = logAction | LogEntry.OUT_1; } if (r.out_2_result() != null && r.context().out_2_link() != null) { sqlImpl().updateFunctions().updateOutLink(kk, true, r.out_2_result(), con); logAction = logAction | LogEntry.OUT_2; } sqlImpl().loggingFunctions().log(r.context().task().key(), logAction, con); boolean isParent = r.context().task().isParent(); if (r instanceof Workflow) { Workflow w = (Workflow) r; Task[] tt = w.tasks(); Link[] ll = w.links(); Hashtable tkeyMap = new Hashtable(); for (int i = 0; i < tt.length; i++) { String key = sqlImpl().creationFunctions().newTask(tt[i], r.context().task(), con); tkeyMap.put(tt[i], key); } for (int j = 0; j < ll.length; j++) { sqlImpl().creationFunctions().newLink(ll[j], tkeyMap, con); } String in_link_1 = sqlImpl().queryFunctions().readInTask(kk, false, con); String in_link_2 = sqlImpl().queryFunctions().readInTask(kk, true, con); String out_link_1 = sqlImpl().queryFunctions().readOutTask(kk, false, con); String out_link_2 = sqlImpl().queryFunctions().readOutTask(kk, true, con); sqlImpl().updateFunctions().rewireInLink(kk, false, w.in_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireInLink(kk, true, w.in_2_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, false, w.out_1_binding(), tkeyMap, con); sqlImpl().updateFunctions().rewireOutLink(kk, true, w.out_2_binding(), tkeyMap, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateDone(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateDone(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateDone(out_link_2, con); for (int k = 0; k < tt.length; k++) { String kkey = (String) tkeyMap.get(tt[k]); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kkey, con); } sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(in_link_2, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_1, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(out_link_2, con); isParent = true; } sqlImpl().updateFunctions().checkAndUpdateDone(kk, con); sqlImpl().updateFunctions().checkAndUpdateTargetExecutable(kk, con); PreparedStatement s3 = null; s3 = con.prepareStatementFromCache(sqlImpl().sqlStatements().updateTaskModificationStatement()); java.util.Date dd = new java.util.Date(); s3.setLong(1, dd.getTime()); s3.setBoolean(2, isParent); s3.setString(3, r.context().task().key()); s3.executeUpdate(); sqlImpl().loggingFunctions().log(kk, LogEntry.ENDED, con); con.commit(); return sqlImpl().queryFunctions().readPTask(kk, con); } finally { con.rollback(); } }
Code Sample 2:
private void writeCard() { try { new URL(createURLStringExistRESTGetXQuery("update value //scheda[cata = \"" + cata + "\"] with " + "\"replaced from /schede/scheda-... by jEpi-Scheda-Applet\"")).openStream().close(); String urlString = "http://" + server + "/exist/rest/db/schede/" + "scheda-" + cata + ".xml"; HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(urlString).openConnection(); httpURLConnection.setDoOutput(true); httpURLConnection.setRequestMethod("PUT"); OutputStream outputStream = httpURLConnection.getOutputStream(); uiSchedaXml.write(outputStream); outputStream.close(); httpURLConnection.getInputStream().close(); httpURLConnection.disconnect(); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } }
|
00
|
Code Sample 1:
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()); } }
Code Sample 2:
@Override public Object getImage(String key) { if (key.indexOf("exhibition/") != -1) { InputStream inputStream = null; try { URL url = new URL(getBaseURL() + "icons/" + key + ".png"); inputStream = url.openStream(); return url; } catch (Exception e) { } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); } } } } return super.getImage(key); }
|
11
|
Code Sample 1:
@Before public void setUp() throws Exception { configureSslSocketConnector(); SecurityHandler securityHandler = createBasicAuthenticationSecurityHandler(); HandlerList handlerList = new HandlerList(); handlerList.addHandler(securityHandler); handlerList.addHandler(new AbstractHandler() { @Override public void handle(String s, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, int i) throws IOException, ServletException { expected = new StringBuilder(); System.out.println("uri: " + httpServletRequest.getRequestURI()); System.out.println("queryString: " + (queryString = httpServletRequest.getQueryString())); System.out.println("method: " + httpServletRequest.getMethod()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(httpServletRequest.getInputStream(), baos); System.out.println("body: " + (body = baos.toString())); PrintWriter writer = httpServletResponse.getWriter(); writer.append("testsvar"); expected.append("testsvar"); Random r = new Random(); for (int j = 0; j < 10; j++) { int value = r.nextInt(Integer.MAX_VALUE); writer.append(value + ""); expected.append(value); } System.out.println(); writer.close(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); } }); server.addHandler(handlerList); server.start(); }
Code Sample 2:
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; }
|
11
|
Code Sample 1:
private static void copy(File source, File target) throws IOException { FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target); byte[] buffer = new byte[4096]; int no = 0; try { while ((no = in.read(buffer)) != -1) out.write(buffer, 0, no); } finally { in.close(); out.close(); } }
Code Sample 2:
public static File jar(File in, String outArc, File tempDir, PatchConfigXML conf) { FileOutputStream arcFile = null; JarOutputStream jout = null; DirectoryScanner ds = null; ds = new DirectoryScanner(); ds.setCaseSensitive(true); ds.setBasedir(in); ds.scan(); ds.setCaseSensitive(true); String[] names = ds.getIncludedFiles(); ArrayList exName = new ArrayList(); if (names == null || names.length < 1) return null; File tempArc = new File(tempDir, outArc.substring(0, outArc.length())); try { Manifest mf = null; List v = new ArrayList(); for (int i = 0; i < names.length; i++) { if (names[i].toUpperCase().indexOf("MANIFEST.MF") > -1) { FileInputStream fis = new FileInputStream(in.getAbsolutePath() + "/" + names[i].replace('\\', '/')); mf = new Manifest(fis); } else v.add(names[i]); } String[] toJar = new String[v.size()]; v.toArray(toJar); tempArc.createNewFile(); arcFile = new FileOutputStream(tempArc); if (mf == null) jout = new JarOutputStream(arcFile); else jout = new JarOutputStream(arcFile, mf); byte[] buffer = new byte[1024]; for (int i = 0; i < toJar.length; i++) { if (conf != null) { if (!conf.allowFileAction(toJar[i], PatchConfigXML.OP_CREATE)) { exName.add(toJar[i]); continue; } } String currentPath = in.getAbsolutePath() + "/" + toJar[i]; String entryName = toJar[i].replace('\\', '/'); JarEntry currentEntry = new JarEntry(entryName); jout.putNextEntry(currentEntry); FileInputStream fis = new FileInputStream(currentPath); int len; while ((len = fis.read(buffer)) >= 0) jout.write(buffer, 0, len); fis.close(); jout.closeEntry(); } } catch (IOException e) { throw new RuntimeException(e); } finally { try { jout.close(); arcFile.close(); } catch (IOException e1) { throw new RuntimeException(e1); } } return tempArc; }
|
11
|
Code Sample 1:
void IconmenuItem5_actionPerformed(ActionEvent e) { JFileChooser jFileChooser1 = new JFileChooser(); String separator = ""; if (getPath() != null && !getPath().equals("")) { jFileChooser1.setCurrentDirectory(new File(getPath())); jFileChooser1.setSelectedFile(new File(getPath())); } if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this.getFatherFrame())) { setPath(jFileChooser1.getSelectedFile().getPath()); separator = jFileChooser1.getSelectedFile().separator; File dirImg = new File("." + separator + "images"); if (!dirImg.exists()) { dirImg.mkdir(); } int index = getPath().lastIndexOf(separator); String imgName = getPath().substring(index); String newPath = dirImg + imgName; try { File inputFile = new File(getPath()); File outputFile = new File(newPath); if (!inputFile.getCanonicalPath().equals(outputFile.getCanonicalPath())) { FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } } catch (Exception ex) { ex.printStackTrace(); LogHandler.log(ex.getMessage(), Level.INFO, "LOG_MSG", isLoggingEnabled()); JOptionPane.showMessageDialog(null, ex.getMessage().substring(0, Math.min(ex.getMessage().length(), getFatherPanel().MAX_DIALOG_MSG_SZ)) + "-" + getClass(), "", JOptionPane.ERROR_MESSAGE); } setPath(newPath); if (getDefaultPath() == null || getDefaultPath().equals("")) { String msgString = "E' stata selezionata un'immagine da associare all'IconShape, ma non e' " + "stata selezionata ancora nessun'immagine di default. Imposto quella scelta anche come " + "immagine di default?"; if (JOptionPane.showConfirmDialog(null, msgString.substring(0, Math.min(msgString.length(), getFatherPanel().MAX_DIALOG_MSG_SZ)), "choose one", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { setDefaultPath(newPath); createDefaultImage(); } } createImage(); } }
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 md5(String value) { String md5Value = "1"; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(value.getBytes()); md5Value = getHex(digest.digest()); } catch (Exception e) { e.printStackTrace(); } return md5Value; }
Code Sample 2:
public boolean downloadFile(String sourceFilename, String targetFilename) throws RQLException { checkFtpClient(); InputStream in = null; try { in = ftpClient.retrieveFileStream(sourceFilename); if (in == null) { return false; } FileOutputStream target = new FileOutputStream(targetFilename); IOUtils.copy(in, target); in.close(); target.close(); return ftpClient.completePendingCommand(); } catch (IOException ex) { throw new RQLException("Download of file with name " + sourceFilename + " via FTP from server " + server + " failed.", ex); } }
|
00
|
Code Sample 1:
private void copy(File srouceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(srouceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
static InputStream getUrlStream(String url) throws IOException { System.out.print("getting : " + url + " ... "); long start = System.currentTimeMillis(); URLConnection c = new URL(url).openConnection(); InputStream is = c.getInputStream(); System.out.print((System.currentTimeMillis() - start) + "ms\n"); return is; }
|
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:
public void readData() throws IOException { i = 0; j = 0; URL url = getClass().getResource("resources/tuneGridMaster.dat"); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); tune_x[i][j] = Double.parseDouble(st.nextToken()); gridmin = tune_x[i][j]; temp_prev = tune_x[i][j]; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); j++; int k = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } tune_x[i][j] = temp_new; tune_y[i][j] = Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; k++; } gridmax = tune_x[i][j - 1]; }
|
11
|
Code Sample 1:
public static String getMD5(String password) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); String salt = "UseTheForce4"; password = salt + password; md5.update(password.getBytes(), 0, password.length()); password = new BigInteger(1, md5.digest()).toString(16); } catch (Exception e) { } return password; }
Code Sample 2:
public static void main(String[] args) throws NoSuchAlgorithmException { String password = "root"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } String pwd = buf.toString(); System.out.println(pwd); }
|
00
|
Code Sample 1:
public Resource get(URL serviceUrl, String resourceId) throws Exception { Resource resource = new Resource(); String openurl = serviceUrl.toString() + "?url_ver=Z39.88-2004" + "&rft_id=" + URLEncoder.encode(resourceId, "UTF-8") + "&svc_id=" + SVCID_ADORE4; log.debug("OpenURL Request: " + openurl); URL url; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { InputStream is = huc.getInputStream(); resource.setBytes(StreamUtil.getByteArray(is)); resource.setContentType(huc.getContentType()); } else { log.error("An error of type " + code + " occurred for " + url.toString()); throw new Exception("Cannot get " + url.toString()); } } catch (MalformedURLException e) { throw new Exception("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new Exception("An IOException occurred attempting to connect to " + openurl); } return resource; }
Code Sample 2:
private void doUpload(UploadKind uploadKind, WriteKind writeKind) throws Exception { int n = 512 * 1024; AtomicInteger total = new AtomicInteger(0); ServerSocket ss = startSinkServer(total); URL url = new URL("http://localhost:" + ss.getLocalPort() + "/test1"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); if (uploadKind == UploadKind.CHUNKED) { conn.setChunkedStreamingMode(-1); } else { conn.setFixedLengthStreamingMode(n); } OutputStream out = conn.getOutputStream(); if (writeKind == WriteKind.BYTE_BY_BYTE) { for (int i = 0; i < n; ++i) { out.write('x'); } } else { byte[] buf = new byte[writeKind == WriteKind.SMALL_BUFFERS ? 256 : 64 * 1024]; Arrays.fill(buf, (byte) 'x'); for (int i = 0; i < n; i += buf.length) { out.write(buf, 0, Math.min(buf.length, n - i)); } } out.close(); assertTrue(conn.getResponseCode() > 0); assertEquals(uploadKind == UploadKind.CHUNKED ? -1 : n, total.get()); }
|
11
|
Code Sample 1:
private String fetch(String urlstring) { String content = ""; try { URL url = new URL(urlstring); InputStream is = url.openStream(); BufferedReader d = new BufferedReader(new InputStreamReader(is)); String s; while (null != (s = d.readLine())) { content = content + s + "\n"; } is.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return content; }
Code Sample 2:
private static List lookupForImplementations(final Class clazz, final ClassLoader loader, final String[] defaultImplementations, final boolean onlyFirst, final boolean returnInstances) throws ClassNotFoundException { if (clazz == null) { throw new IllegalArgumentException("Argument 'clazz' cannot be null!"); } ClassLoader classLoader = loader; if (classLoader == null) { classLoader = clazz.getClassLoader(); } String interfaceName = clazz.getName(); ArrayList tmp = new ArrayList(); ArrayList toRemove = new ArrayList(); String className = System.getProperty(interfaceName); if (className != null && className.trim().length() > 0) { tmp.add(className.trim()); } Enumeration en = null; try { en = classLoader.getResources("META-INF/services/" + clazz.getName()); } catch (IOException e) { e.printStackTrace(); } while (en != null && en.hasMoreElements()) { URL url = (URL) en.nextElement(); InputStream is = null; try { is = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; do { line = reader.readLine(); boolean remove = false; if (line != null) { if (line.startsWith("#-")) { remove = true; line = line.substring(2); } int pos = line.indexOf('#'); if (pos >= 0) { line = line.substring(0, pos); } line = line.trim(); if (line.length() > 0) { if (remove) { toRemove.add(line); } else { tmp.add(line); } } } } while (line != null); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } if (defaultImplementations != null) { for (int i = 0; i < defaultImplementations.length; i++) { tmp.add(defaultImplementations[i].trim()); } } if (!clazz.isInterface()) { int m = clazz.getModifiers(); if (!Modifier.isAbstract(m) && Modifier.isPublic(m) && !Modifier.isStatic(m)) { tmp.add(interfaceName); } } tmp.removeAll(toRemove); ArrayList res = new ArrayList(); for (Iterator it = tmp.iterator(); it.hasNext(); ) { className = (String) it.next(); try { Class c = Class.forName(className, false, classLoader); if (c != null) { if (clazz.isAssignableFrom(c)) { if (returnInstances) { Object o = null; try { o = c.newInstance(); } catch (Throwable e) { e.printStackTrace(); } if (o != null) { res.add(o); if (onlyFirst) { return res; } } } else { res.add(c); if (onlyFirst) { return res; } } } else { logger.warning("MetaInfLookup: Class '" + className + "' is not a subclass of class : " + interfaceName); } } } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Cannot create implementation of interface: " + interfaceName, e); } } if (res.size() == 0) { throw new ClassNotFoundException("Cannot find any implemnetation of class " + interfaceName); } return res; }
|
11
|
Code Sample 1:
protected String getHashCode(String value) { if (log.isDebugEnabled()) log.debug("getHashCode(...) -> begin"); String retVal = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(value.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; i++) { sb.append(this.toHexString(digest[i])); } retVal = sb.toString(); if (log.isDebugEnabled()) log.debug("getHashCode(...) -> hashcode = " + retVal); } catch (Exception e) { log.error("getHashCode(...) -> error occured generating hashcode ", e); } if (log.isDebugEnabled()) log.debug("getHashCode(...) -> end"); return retVal; }
Code Sample 2:
public String gen() { String plainText = this.password; MessageDigest mdAlgorithm; StringBuffer hexString = new StringBuffer(); try { mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) plainText = "0" + plainText; hexString.append(plainText); } } catch (NoSuchAlgorithmException ex) { } return hexString.toString(); }
|
11
|
Code Sample 1:
public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } try { String fichTable; if (sys) { fichTable = ConfigNat.getInstallFolder() + "/xsl/tablesEmbosseuse/" + tableBraille; } else { fichTable = ConfigNat.getUserEmbossTableFolder() + "/" + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(ConfigNat.getUserTempFolder() + "Table_pour_chaines.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
public static void DecodeMapFile(String mapFile, String outputFile) throws Exception { byte magicKey = 0; byte[] buffer = new byte[2048]; int nread; InputStream map; OutputStream output; try { map = new FileInputStream(mapFile); } catch (Exception e) { throw new Exception("Map file error", e); } try { output = new FileOutputStream(outputFile); } catch (Exception e) { throw new Exception("Map file error", e); } while ((nread = map.read(buffer, 0, 2048)) != 0) { for (int i = 0; i < nread; ++i) { buffer[i] ^= magicKey; magicKey += 43; } output.write(buffer, 0, nread); } map.close(); output.close(); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.