label
class label 2
classes | source_code
stringlengths 398
72.9k
|
---|---|
00
| 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 InputSource resolveEntity(String publicId, String systemId) { String resolved = null; if (systemId != null) { try { resolved = catalog.resolveSystem(systemId); } catch (MalformedURLException me) { debug(1, "Malformed URL exception trying to resolve", publicId); resolved = null; } catch (IOException ie) { debug(1, "I/O exception trying to resolve", publicId); resolved = null; } } if (resolved == null) { if (publicId != null) { try { resolved = catalog.resolvePublic(publicId, systemId); } catch (MalformedURLException me) { debug(1, "Malformed URL exception trying to resolve", publicId); } catch (IOException ie) { debug(1, "I/O exception trying to resolve", publicId); } } if (resolved != null) { debug(2, "Resolved", publicId, resolved); } } else { debug(2, "Resolved", systemId, resolved); } if (resolved == null && retryBadSystemIds && publicId != null && systemId != null) { URL systemURL = null; try { systemURL = new URL(systemId); } catch (MalformedURLException e) { try { systemURL = new URL("file:///" + systemId); } catch (MalformedURLException e2) { systemURL = null; } } if (systemURL != null) { try { InputStream iStream = systemURL.openStream(); InputSource iSource = new InputSource(systemId); iSource.setPublicId(publicId); iSource.setByteStream(iStream); return iSource; } catch (Exception e) { } } debug(2, "Failed to open", systemId); debug(2, "\tAttempting catalog lookup without system identifier."); return resolveEntity(publicId, null); } if (resolved != null) { try { InputSource iSource = new InputSource(resolved); iSource.setPublicId(publicId); URL url = new URL(resolved); InputStream iStream = url.openStream(); iSource.setByteStream(iStream); return iSource; } catch (Exception e) { debug(1, "Failed to create InputSource", resolved); return null; } } return null; } |
00
| Code Sample 1:
@RequestMapping(value = "/verdocumentoFisico.html", method = RequestMethod.GET) public String editFile(ModelMap model, @RequestParam("id") int idAnexo) { Anexo anexo = anexoService.selectById(idAnexo); model.addAttribute("path", anexo.getAnexoCaminho()); try { InputStream is = new FileInputStream(new File(config.baseDir + "/arquivos_upload_direto/" + anexo.getAnexoCaminho())); FileOutputStream fos = new FileOutputStream(new File(config.baseDir + "/temp/" + anexo.getAnexoCaminho())); IOUtils.copy(is, fos); Runtime.getRuntime().exec("chmod 777 " + config.tempDir + anexo.getAnexoCaminho()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "verdocumentoFisico"; }
Code Sample 2:
private byte[] pullMapBytes(String directoryLocation) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { URL url = new URL(directoryLocation); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); InputStream is = httpURLConnection.getInputStream(); int nRead; byte[] data = new byte[1024]; while ((nRead = is.read(data, 0, data.length)) != -1) { buffer.write(data, 0, nRead); } buffer.flush(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return buffer.toByteArray(); } |
00
| Code Sample 1:
public boolean login(URL strUrl, String loginName, String loginPwd, String sessionID) throws Exception { String starter = "-----------------------------"; String returnChar = "\r\n"; String lineEnd = "--"; URL urlString = strUrl; String input = null; List txtList = new ArrayList(); List fileList = new ArrayList(); String targetFile = null; String actionStatus = null; StringBuffer returnMessage = new StringBuffer(); List head = new ArrayList(); final String boundary = String.valueOf(System.currentTimeMillis()); URL url = null; URLConnection conn = null; BufferedReader br = null; DataOutputStream dos = null; boolean isLogin = false; txtList.add(new HtmlFormText("loginName", loginName)); txtList.add(new HtmlFormText("loginPwd", loginPwd)); txtList.add(new HtmlFormText("navMode", "I")); txtList.add(new HtmlFormText("action", "login")); try { url = new URL(urlString, "/" + projectName + "/Login.do"); conn = url.openConnection(); ((HttpURLConnection) conn).setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "multipart/form-data, boundary=" + "---------------------------" + boundary); if (input != null) { String auth = "Basic " + new sun.misc.BASE64Encoder().encode(input.getBytes()); conn.setRequestProperty("Authorization", auth); } dos = new DataOutputStream(conn.getOutputStream()); dos.write((starter + boundary + returnChar).getBytes()); for (int i = 0; i < txtList.size(); i++) { HtmlFormText htmltext = (HtmlFormText) txtList.get(i); dos.write(htmltext.getTranslated()); if (i + 1 < txtList.size()) { dos.write((starter + boundary + returnChar).getBytes()); } else if (fileList.size() > 0) { dos.write((starter + boundary + returnChar).getBytes()); } } dos.write((starter + boundary + "--" + returnChar).getBytes()); dos.flush(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String key; String header; int i = 1; key = conn.getHeaderFieldKey(i); header = conn.getHeaderField(i); System.out.println(header); if (Utility.isEmpty(header) || header.indexOf("JSESSIONID") < 0) { header = "JSESSIONID=" + sessionID + "; Path=/" + projectName; } while (key != null) { head.add(header); i++; key = conn.getHeaderFieldKey(i); header = conn.getHeaderField(i); } String tempstr; int line = 0; while (null != ((tempstr = br.readLine()))) { if (!tempstr.equals("")) { if ("window.location.replace(\"/eip/Home.do\");".indexOf(returnMessage.append(formatLine(tempstr)).toString()) != -1) { isLogin = true; break; } line++; } } txtList.clear(); fileList.clear(); } catch (Exception e) { e.printStackTrace(); } finally { try { dos.close(); } catch (Exception e) { } try { br.close(); } catch (Exception e) { } } this.setHeadList(head); return isLogin; }
Code Sample 2:
private void extractByParsingHtml(String refererURL, String requestURL) throws MalformedURLException, IOException { URL url = new URL(refererURL); InputStream is = url.openStream(); mRefererURL = refererURL; if (requestURL.startsWith("http://www.")) { mRequestURLWWW = requestURL; mRequestURL = "http://" + mRequestURLWWW.substring(11); } else { mRequestURL = requestURL; mRequestURLWWW = "http://www." + mRequestURL.substring(7); } Parser parser = (new HTMLEditorKit() { public Parser getParser() { return super.getParser(); } }).getParser(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } StringReader sr = new StringReader(sb.toString()); parser.parse(sr, new LinkbackCallback(), true); if (mStart != 0 && mEnd != 0 && mEnd > mStart) { mExcerpt = sb.toString().substring(mStart, mEnd); mExcerpt = Utilities.removeHTML(mExcerpt); if (mExcerpt.length() > mMaxExcerpt) { mExcerpt = mExcerpt.substring(0, mMaxExcerpt) + "..."; } } if (mTitle.startsWith(">") && mTitle.length() > 1) { mTitle = mTitle.substring(1); } } |
11
| Code Sample 1:
public void generate(FileObject outputDirectory, FileObject generatedOutputDirectory, List<Library> libraryModels, String tapdocXml) throws FileSystemException { if (!outputDirectory.exists()) { outputDirectory.createFolder(); } ZipUtils.extractZip(new ClasspathResource(classResolver, "/com/erinors/tapestry/tapdoc/standalone/resources.zip"), outputDirectory); for (Library library : libraryModels) { String libraryName = library.getName(); String libraryLocation = library.getLocation(); outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).createFolder(); try { { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Library.xsl"), "libraryName", libraryName); FileObject index = outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("index.html"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("ComponentIndex.xsl"), "libraryName", libraryName); FileObject index = outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("components.html"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } } catch (Exception e) { throw new RuntimeException(e); } for (Component component : library.getComponents()) { String componentName = component.getName(); System.out.println("Generating " + libraryName + ":" + componentName + "..."); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("libraryName", libraryName); parameters.put("componentName", componentName); String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Component.xsl"), parameters); Writer out = null; try { FileObject index = outputDirectory.resolveFile(fileNameGenerator.getComponentIndexFile(libraryLocation, componentName, true)); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); Resource specificationLocation = component.getSpecificationLocation(); if (specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL() != null) { File srcResourcesDirectory = new File(specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL().toURI()); FileObject dstResourcesFileObject = outputDirectory.resolveFile(fileNameGenerator.getComponentDirectory(libraryLocation, componentName)).resolveFile("resource"); if (srcResourcesDirectory.exists() && srcResourcesDirectory.isDirectory()) { File[] files = srcResourcesDirectory.listFiles(); if (files != null) { for (File resource : files) { if (resource.isFile() && !resource.isHidden()) { FileObject resourceFileObject = dstResourcesFileObject.resolveFile(resource.getName()); resourceFileObject.createFile(); InputStream inResource = null; OutputStream outResource = null; try { inResource = new FileInputStream(resource); outResource = resourceFileObject.getContent().getOutputStream(); IOUtils.copy(inResource, outResource); } finally { IOUtils.closeQuietly(inResource); IOUtils.closeQuietly(outResource); } } } } } } } catch (Exception e) { throw new RuntimeException(e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } } { Writer out = null; try { { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("LibraryIndex.xsl")); FileObject index = outputDirectory.resolveFile("libraries.html"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Overview.xsl")); FileObject index = outputDirectory.resolveFile("overview.html"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("AllComponents.xsl")); FileObject index = outputDirectory.resolveFile("allcomponents.html"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } }
Code Sample 2:
private void copyEntries() { if (zipFile != null) { Enumeration<? extends ZipEntry> enumerator = zipFile.entries(); while (enumerator.hasMoreElements()) { ZipEntry entry = enumerator.nextElement(); if (!entry.isDirectory() && !toIgnore.contains(normalizePath(entry.getName()))) { ZipEntry originalEntry = new ZipEntry(entry.getName()); try { zipOutput.putNextEntry(originalEntry); IOUtils.copy(getInputStream(entry.getName()), zipOutput); zipOutput.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } } } } |
11
| Code Sample 1:
private static String readStreamToString(InputStream is, boolean passInVelocity, String tplName, Map<String, Object> templateVarsMap) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); if (passInVelocity) { return tpl.formatStr(sw.toString(), templateVarsMap, tplName); } return sw.toString(); }
Code Sample 2:
public void copy(File s, File t) throws IOException { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } |
00
| Code Sample 1:
public static void copy(File src, File dst) { try { InputStream is = null; OutputStream os = null; try { is = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); os = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = is.read(buffer)) > 0) os.write(buffer, 0, len); } finally { if (null != is) is.close(); if (null != os) os.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private BufferedReader getReader(final String fileUrl) throws IOException { InputStreamReader reader; try { reader = new FileReader(fileUrl); } catch (FileNotFoundException e) { URL url = new URL(fileUrl); reader = new InputStreamReader(url.openStream()); } return new BufferedReader(reader); } |
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 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!"); } |
11
| Code Sample 1:
private void copyImage(ProjectElement e) throws Exception { String fn = e.getName(); if (!fn.toLowerCase().endsWith(".png")) { if (fn.contains(".")) { fn = fn.substring(0, fn.lastIndexOf('.')) + ".png"; } else { fn += ".png"; } } File img = new File(resFolder, fn); File imgz = new File(resoutFolder.getAbsolutePath(), fn + ".zlib"); boolean copy = true; if (img.exists() && config.containsKey(img.getName())) { long modified = Long.parseLong(config.get(img.getName())); if (modified >= img.lastModified()) { copy = false; } } if (copy) { convertImage(e.getFile(), img); config.put(img.getName(), String.valueOf(img.lastModified())); } DeflaterOutputStream out = new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream(imgz))); BufferedInputStream in = new BufferedInputStream(new FileInputStream(img)); int read; while ((read = in.read()) != -1) { out.write(read); } out.close(); in.close(); imageFiles.add(imgz); imageNames.put(imgz, e.getName()); }
Code Sample 2:
public static void rewrite(String[] args) throws IOException, CodeCheckException { ClassWriter writer = new ClassWriter(); writer.readClass(new FileInputStream(args[0])); for (Iterator i = writer.getMethods().iterator(); i.hasNext(); ) { MethodInfo method = (MethodInfo) i.next(); CodeAttribute attribute = method.getCodeAttribute(); int origStack = attribute.getMaxStack(); System.out.print(method.getName()); attribute.codeCheck(); System.out.println(" " + origStack + " " + attribute.getMaxStack()); } BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(args[1])); writer.writeClass(outStream); outStream.close(); } |
00
| Code Sample 1:
public void downloadQFromMinibix(int ticketNo) { String minibixDomain = Preferences.userRoot().node("Spectatus").get("MBAddr", "http://mathassess.caret.cam.ac.uk"); String minibixPort = Preferences.userRoot().node("Spectatus").get("MBPort", "80"); String url = minibixDomain + ":" + minibixPort + "/qtibank-webserv/deposits/all/" + ticketNo; File file = new File(tempdir + sep + "minibix.zip"); try { BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file)); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); int l; byte[] tmp = new byte[2048]; while ((l = instream.read(tmp)) != -1) { out.write(tmp, 0, l); } out.close(); instream.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public LocalizationSolver(String name, String serverIP, int portNum, String workDir) { this.info = new HashMap<String, Object>(); this.workDir = workDir; try { Socket solverSocket = new Socket(serverIP, portNum); this.fromServer = new Scanner(solverSocket.getInputStream()); this.toServer = new PrintWriter(solverSocket.getOutputStream(), true); this.toServer.println("login client abc"); this.toServer.println("solver " + name); System.out.println(this.fromServer.nextLine()); } catch (IOException e) { System.err.println(e); e.printStackTrace(); System.exit(1); } System.out.println("Localization Solver started with name: " + name); } |
11
| Code Sample 1:
private static String doHash(String frase, String algorithm) { try { String ret; MessageDigest md = MessageDigest.getInstance(algorithm); md.update(frase.getBytes()); BigInteger bigInt = new BigInteger(1, md.digest()); ret = bigInt.toString(16); return ret; } catch (NoSuchAlgorithmException e) { return null; } }
Code Sample 2:
private static String getUnsaltedHash(String algorithm, String input) throws NoSuchAlgorithmException { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); messageDigest.reset(); messageDigest.update(input.getBytes(Main.DEFAULT_CHARSET)); byte[] digest = messageDigest.digest(); return String.format(Main.DEFAULT_LOCALE, "%0" + (digest.length << 1) + "x", new BigInteger(1, digest)); } |
00
| Code Sample 1:
public static File downloadFile(Proxy proxy, URL url, File path) throws IOException { URLConnection conn = null; if (null == proxy) { conn = url.openConnection(); } else { conn = url.openConnection(proxy); } conn.connect(); File destFile = null; if (conn instanceof HttpURLConnection) { HttpURLConnection hc = (HttpURLConnection) conn; String filename = null; String hv = hc.getHeaderField("Content-Disposition"); if (null == hv) { String str = url.toString(); int index = str.lastIndexOf("/"); filename = str.substring(index + 1); } else { int index = hv.indexOf("filename="); filename = hv.substring(index).replace("\"", "").trim(); } destFile = new File(path, filename); } else { destFile = new File(path, "downloadfile" + url.toString().hashCode()); } if (destFile.exists()) { return destFile; } FileOutputStream fos = new FileOutputStream(destFile); byte[] buffer = new byte[2048]; try { while (true) { int len = conn.getInputStream().read(buffer); if (len < 0) { break; } else { fos.write(buffer, 0, len); } } fos.close(); } catch (IOException e) { destFile.delete(); throw e; } return destFile; }
Code Sample 2:
public byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; } |
00
| Code Sample 1:
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
Code Sample 2:
public Configuration load(URL url) throws ConfigurationException { LOG.info("Configuring from url : " + url.toString()); try { return load(url.openStream(), url.toString()); } catch (IOException ioe) { throw new ConfigurationException("Could not configure from URL : " + url, ioe); } } |
11
| Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public void 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 List importSymbols(List symbols) throws ImportExportException { List quotes = new ArrayList(); String URLString = constructURL(symbols); IDQuoteFilter filter = new YahooIDQuoteFilter(); PreferencesManager.ProxyPreferences proxyPreferences = PreferencesManager.loadProxySettings(); try { URL url = new URL(URLString); InputStreamReader input = new InputStreamReader(url.openStream()); BufferedReader bufferedInput = new BufferedReader(input); String line; do { line = bufferedInput.readLine(); if (line != null) { try { IDQuote quote = filter.toIDQuote(line); quote.verify(); quotes.add(quote); } catch (QuoteFormatException e) { } } } while (line != null); bufferedInput.close(); } catch (BindException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (ConnectException e) { throw new ImportExportException(Locale.getString("UNABLE_TO_CONNECT_ERROR", e.getMessage())); } catch (UnknownHostException e) { throw new ImportExportException(Locale.getString("UNKNOWN_HOST_ERROR", e.getMessage())); } catch (NoRouteToHostException e) { throw new ImportExportException(Locale.getString("DESTINATION_UNREACHABLE_ERROR", e.getMessage())); } catch (MalformedURLException e) { throw new ImportExportException(Locale.getString("INVALID_PROXY_ERROR", proxyPreferences.host, proxyPreferences.port)); } catch (FileNotFoundException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } catch (IOException e) { throw new ImportExportException(Locale.getString("ERROR_DOWNLOADING_QUOTES")); } return quotes; }
Code Sample 2:
public String doGet() throws MalformedURLException, IOException { uc = (HttpURLConnection) url.openConnection(); BufferedInputStream buffer = new BufferedInputStream(uc.getInputStream()); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int c; while ((c = buffer.read()) != -1) { bos.write(c); } bos.close(); headers = uc.getHeaderFields(); status = uc.getResponseCode(); return bos.toString(); } |
11
| Code Sample 1:
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } }
Code Sample 2:
public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } } |
11
| Code Sample 1:
private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } |
00
| Code Sample 1:
protected boolean hasOsmTileETag(String eTag) throws IOException { URL url; url = new URL(tile.getUrl()); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); prepareHttpUrlConnection(urlConn); urlConn.setRequestMethod("HEAD"); urlConn.setReadTimeout(30000); String osmETag = urlConn.getHeaderField("ETag"); if (osmETag == null) return true; return (osmETag.equals(eTag)); }
Code Sample 2:
private static final BufferedInputStream createInputStreamFromRemoteUrl(String uri, ClientConnectionManager connectionManager) { InputStream contentInput = null; if (connectionManager == null) { try { URL url = new URI(uri).toURL(); URLConnection conn = url.openConnection(); conn.connect(); contentInput = conn.getInputStream(); } catch (Exception e) { Log.w(TAG, "Request failed: " + uri); e.printStackTrace(); return null; } } else { final DefaultHttpClient mHttpClient = new DefaultHttpClient(connectionManager, HTTP_PARAMS); HttpUriRequest request = new HttpGet(uri); HttpResponse httpResponse = null; try { httpResponse = mHttpClient.execute(request); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { contentInput = entity.getContent(); } } catch (Exception e) { Log.w(TAG, "Request failed: " + request.getURI()); return null; } } if (contentInput != null) { return new BufferedInputStream(contentInput, 4096); } else { return null; } } |
00
| Code Sample 1:
public static boolean copyFile(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; boolean retour = false; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); retour = true; } catch (IOException e) { System.err.println("File : " + fileIn); e.printStackTrace(); } return retour; }
Code Sample 2:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } } |
11
| Code Sample 1:
public static String sendGetRequest(String endpoint, String requestParameters) { String result = null; if (endpoint.startsWith("http://")) { try { StringBuffer data = new StringBuffer(); String urlStr = endpoint; if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line + "\n"); } rd.close(); result = sb.toString(); } catch (Exception e) { } } return result; }
Code Sample 2:
public void run() { try { URL url = new URL("http://pokedev.org/time.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); StringTokenizer s = new StringTokenizer(in.readLine()); m_day = Integer.parseInt(s.nextToken()); m_hour = Integer.parseInt(s.nextToken()); m_minutes = Integer.parseInt(s.nextToken()); in.close(); } catch (Exception e) { System.out.println("ERROR: Cannot reach time server, reverting to local time"); Calendar cal = Calendar.getInstance(); m_hour = cal.get(Calendar.HOUR_OF_DAY); m_minutes = 0; m_day = 0; } while (m_isRunning) { m_minutes = m_minutes == 59 ? 0 : m_minutes + 1; if (m_minutes == 0) { if (m_hour == 23) { incrementDay(); m_hour = 0; } else { m_hour += 1; } } m_hour = m_hour == 23 ? 0 : m_hour + 1; if (System.currentTimeMillis() - m_lastWeatherUpdate >= 3600000) { generateWeather(); m_lastWeatherUpdate = System.currentTimeMillis(); } try { Thread.sleep(60000); } catch (Exception e) { } } System.out.println("INFO: Time Service stopped"); } |
11
| Code Sample 1:
public void runDynusT() { final String[] exeFiles = new String[] { "DynusT.exe", "DLL_ramp.dll", "Ramp_Meter_Fixed_CDLL.dll", "Ramp_Meter_Feedback_CDLL.dll", "Ramp_Meter_Feedback_FDLL.dll", "libifcoremd.dll", "libmmd.dll", "Ramp_Meter_Fixed_FDLL.dll", "libiomp5md.dll" }; final String[] modelFiles = new String[] { "network.dat", "scenario.dat", "control.dat", "ramp.dat", "incident.dat", "movement.dat", "vms.dat", "origin.dat", "destination.dat", "StopCap4Way.dat", "StopCap2Way.dat", "YieldCap.dat", "WorkZone.dat", "GradeLengthPCE.dat", "leftcap.dat", "system.dat", "output_option.dat", "bg_demand_adjust.dat", "xy.dat", "TrafficFlowModel.dat", "parameter.dat" }; log.info("Creating iteration-directory..."); File iterDir = new File(this.tmpDir); if (!iterDir.exists()) { iterDir.mkdir(); } log.info("Copying application files to iteration-directory..."); for (String filename : exeFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.dynusTDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } log.info("Copying model files to iteration-directory..."); for (String filename : modelFiles) { log.info(" Copying " + filename); IOUtils.copyFile(new File(this.modelDir + "/" + filename), new File(this.tmpDir + "/" + filename)); } String logfileName = this.tmpDir + "/dynus-t.log"; String cmd = this.tmpDir + "/DynusT.exe"; log.info("running command: " + cmd); int timeout = 14400; int exitcode = ExeRunner.run(cmd, logfileName, timeout); if (exitcode != 0) { throw new RuntimeException("There was a problem running Dynus-T. exit code: " + exitcode); } }
Code Sample 2:
private static void copyFile(File source, File destination) throws IOException, SecurityException { if (!destination.exists()) destination.createNewFile(); FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); destinationChannel = new FileOutputStream(destination).getChannel(); long count = 0; long size = sourceChannel.size(); while ((count += destinationChannel.transferFrom(sourceChannel, 0, size - count)) < size) ; } finally { if (sourceChannel != null) sourceChannel.close(); if (destinationChannel != null) destinationChannel.close(); } } |
00
| Code Sample 1:
public Object downloadObject() throws CommunicationException, FileNotFoundException, InvalidClassException, ClassNotFoundException { Object returnObject = null; String requestStr = new String(); HttpURLConnection connection = null; try { URL url = new URL(urlString); for (java.util.Iterator i = parameters.entrySet().iterator(); i.hasNext(); ) { java.util.Map.Entry e = (java.util.Map.Entry) i.next(); requestStr += URLEncoder.encode((String) e.getKey(), "UTF-8") + "=" + URLEncoder.encode((String) e.getValue(), "UTF-8") + "&"; } connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println(requestStr); out.close(); System.out.println("HTTPCommunication.downloadObject() - Response:" + connection.getResponseCode() + " : " + connection.getResponseMessage()); if (connection.getResponseCode() == connection.HTTP_OK) { GZIPInputStream gzipIn = new GZIPInputStream(connection.getInputStream()); ObjectInputStream objectIn = new ObjectInputStream(gzipIn); returnObject = objectIn.readObject(); objectIn.close(); } else if (connection.getResponseCode() == connection.HTTP_NOT_FOUND) { throw new FileNotFoundException(connection.getResponseMessage()); } else { throw new CommunicationException(connection.getResponseMessage(), connection.getResponseCode()); } } catch (java.net.ConnectException ce) { throw new CommunicationException("Cannot connect to " + urlString + ".\n" + "Server is not responding!", ce); } catch (java.net.MalformedURLException mfue) { throw new CommunicationException("Cannot connect to " + urlString + ".\n" + "Bad url string!", mfue); } catch (ClassNotFoundException cnfe) { throw cnfe; } catch (InvalidClassException ice) { throw ice; } catch (java.io.FileNotFoundException fnfe) { throw fnfe; } catch (java.io.InterruptedIOException iioe) { this.parentWorkflow.getMenuButtonEventHandler().stopAutomaticRefresh(); throw new CommunicationException("Communication is timeouted", iioe); } catch (java.io.IOException ioe) { throw new CommunicationException("Error while trying to communicate the server: \n" + ioe.getMessage(), ioe); } finally { if (connection != null) { connection.disconnect(); } } return returnObject; }
Code Sample 2:
@Provides @Singleton Properties provideCfg() { InputStream propStream = null; URL url = Thread.currentThread().getContextClassLoader().getResource(PROPERTY_FILE); Properties cfg = new Properties(); if (url != null) { try { log.info("Loading app config from properties: " + url.toURI()); propStream = url.openStream(); cfg.load(propStream); return cfg; } catch (Exception e) { log.warn(e); } } if (cfg.size() < 1) { log.info(PROPERTY_FILE + " doesnt contain any configuration for application properties."); } return cfg; } |
00
| Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
@Override public DataTable generateDataTable(Query query, HttpServletRequest request) throws DataSourceException { String url = request.getParameter(URL_PARAM_NAME); if (StringUtils.isEmpty(url)) { log.error("url parameter not provided."); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url parameter not provided"); } Reader reader; try { reader = new BufferedReader(new InputStreamReader(new URL(url).openStream())); } catch (MalformedURLException e) { log.error("url is malformed: " + url); throw new DataSourceException(ReasonType.INVALID_REQUEST, "url is malformed: " + url); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } DataTable dataTable = null; ULocale requestLocale = DataSourceHelper.getLocaleFromRequest(request); try { dataTable = CsvDataSourceHelper.read(reader, null, true, requestLocale); } catch (IOException e) { log.error("Couldn't read from url: " + url, e); throw new DataSourceException(ReasonType.INVALID_REQUEST, "Couldn't read from url: " + url); } return dataTable; } |
00
| Code Sample 1:
public static void writeDataResourceText(GenericValue dataResource, String mimeTypeId, Locale locale, Map templateContext, GenericDelegator delegator, Writer out, boolean cache) throws IOException, GeneralException { Map context = (Map) templateContext.get("context"); if (context == null) { context = FastMap.newInstance(); } String webSiteId = (String) templateContext.get("webSiteId"); if (UtilValidate.isEmpty(webSiteId)) { if (context != null) webSiteId = (String) context.get("webSiteId"); } String https = (String) templateContext.get("https"); if (UtilValidate.isEmpty(https)) { if (context != null) https = (String) context.get("https"); } String dataResourceId = dataResource.getString("dataResourceId"); String dataResourceTypeId = dataResource.getString("dataResourceTypeId"); if (UtilValidate.isEmpty(dataResourceTypeId)) { dataResourceTypeId = "SHORT_TEXT"; } if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) { String text = dataResource.getString("objectInfo"); writeText(dataResource, text, templateContext, mimeTypeId, locale, out); } else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) { GenericValue electronicText; if (cache) { electronicText = delegator.findByPrimaryKeyCache("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } else { electronicText = delegator.findByPrimaryKey("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId)); } String text = electronicText.getString("textData"); writeText(dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_OBJECT")) { String text = (String) dataResource.get("dataResourceId"); writeText(dataResource, text, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.equals("URL_RESOURCE")) { String text = null; URL url = FlexibleLocation.resolveLocation(dataResource.getString("objectInfo")); if (url.getHost() != null) { InputStream in = url.openStream(); int c; StringWriter sw = new StringWriter(); while ((c = in.read()) != -1) { sw.write(c); } sw.close(); text = sw.toString(); } else { String prefix = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https); String sep = ""; if (url.toString().indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) { sep = "/"; } String fixedUrlStr = prefix + sep + url.toString(); URL fixedUrl = new URL(fixedUrlStr); text = (String) fixedUrl.getContent(); } out.write(text); } else if (dataResourceTypeId.endsWith("_FILE_BIN")) { writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } else if (dataResourceTypeId.endsWith("_FILE")) { String dataResourceMimeTypeId = dataResource.getString("mimeTypeId"); String objectInfo = dataResource.getString("objectInfo"); String rootDir = (String) context.get("rootDir"); if (dataResourceMimeTypeId == null || dataResourceMimeTypeId.startsWith("text")) { renderFile(dataResourceTypeId, objectInfo, rootDir, out); } else { writeText(dataResource, dataResourceId, templateContext, mimeTypeId, locale, out); } } else { throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in renderDataResourceAsText"); } }
Code Sample 2:
public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == submitButton) { SubmissionProfile profile = (SubmissionProfile) destinationCombo.getSelectedItem(); String uri = profile.endpoint; String authPoint = profile.authenticationPoint; String user = userIDField.getText(); String passwd = new String(passwordField.getPassword()); try { URL url = new URL(authPoint + "?username=" + user + "&password=" + passwd); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = ""; String text = ""; while ((line = reader.readLine()) != null) { text = text + line; } reader.close(); submit(uri, user); JOptionPane.showMessageDialog(null, "Submission accepted", "Success", JOptionPane.INFORMATION_MESSAGE); this.setVisible(false); this.dispose(); } catch (Exception ex) { ex.printStackTrace(); if (ex instanceof java.io.IOException) { String msg = ex.getMessage(); if (msg.indexOf("HTTP response code: 401") != -1) JOptionPane.showMessageDialog(null, "Invalid Username/Password", "Invalid Username/Password", JOptionPane.ERROR_MESSAGE); else if (msg.indexOf("HTTP response code: 404") != -1) { try { submit(uri, user); JOptionPane.showMessageDialog(null, "Submission accepted", "Success", JOptionPane.INFORMATION_MESSAGE); } catch (Exception exc) { exc.printStackTrace(); } } } } } else if (src == cancelButton) { this.setVisible(false); this.dispose(); } } |
11
| Code Sample 1:
private static byte[] tryLoadFile(String path) throws IOException { InputStream in = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); return out.toByteArray(); }
Code Sample 2:
public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } } |
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:
@Override public void download(String remoteFilePath, String localFilePath) { InputStream remoteStream = null; try { remoteStream = client.get(remoteFilePath); } catch (IOException e) { e.printStackTrace(); } OutputStream localStream = null; try { localStream = new FileOutputStream(new File(localFilePath)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { IOUtils.copy(remoteStream, localStream); } catch (IOException e) { e.printStackTrace(); } } |
11
| Code Sample 1:
private long generateUnixInstallShell(File unixShellFile, String instTemplate, File instClassFile) throws IOException { FileOutputStream byteWriter = new FileOutputStream(unixShellFile); InputStream is = getClass().getResourceAsStream("/" + instTemplate); InputStreamReader isr = new InputStreamReader(is); LineNumberReader reader = new LineNumberReader(isr); String content = ""; String installClassStartStr = "000000000000"; NumberFormat nf = NumberFormat.getInstance(Locale.US); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(installClassStartStr.length()); int installClassStartPos = 0; long installClassOffset = 0; System.out.println(VAGlobals.i18n("VAArchiver_GenerateInstallShell")); String line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassStart"))) { content += line + "\n"; line = reader.readLine(); } content += "InstallClassStart=" + installClassStartStr + "\n"; installClassStartPos = content.length() - 1 - 1 - installClassStartStr.length(); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassSize"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassSize=" + instClassFile.length() + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# InstallClassName"))) { content += line + "\n"; line = reader.readLine(); } content += new String("InstallClassName=" + instClassName_ + "\n"); line = reader.readLine(); while ((line != null) && (!line.startsWith("# Install class"))) { content += line + "\n"; line = reader.readLine(); } if (line != null) content += line + "\n"; byteWriter.write(content.substring(0, installClassStartPos + 1).getBytes()); byteWriter.write(nf.format(content.length()).getBytes()); byteWriter.write(content.substring(installClassStartPos + 1 + installClassStartStr.length()).getBytes()); installClassOffset = content.length(); content = null; FileInputStream classStream = new FileInputStream(instClassFile); byte[] buf = new byte[2048]; int read = classStream.read(buf); while (read > 0) { byteWriter.write(buf, 0, read); read = classStream.read(buf); } classStream.close(); reader.close(); byteWriter.close(); return installClassOffset; }
Code Sample 2:
@Test @Ignore public void testToJson() throws IOException { JsonSerializer js = new StreamingJsonSerializer(new ObjectMapper()); BulkOperation op = js.createBulkOperation(createTestData(10000), false); IOUtils.copy(op.getData(), System.out); } |
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 { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
Code Sample 2:
public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); int i; Vector images = new Vector(); images = dataBase.allImageSearch(); lengthOfTask = images.size() * 2; String directory = directoryPath + "Images" + myDirectory.separator; File newDirectoryFolder = new File(directory); newDirectoryFolder.mkdirs(); try { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); doc = domBuilder.newDocument(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Element dbElement = doc.createElement("dataBase"); for (i = 0; ((i < images.size()) && !stop); i++) { current = i; String element = (String) images.elementAt(i); String pathSrc = "Images" + File.separator + element.substring(0, 1).toUpperCase() + File.separator + element; String name = pathSrc.substring(pathSrc.lastIndexOf(myDirectory.separator) + 1, pathSrc.length()); String pathDst = directory + name; try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } Vector keyWords = new Vector(); keyWords = dataBase.asociatedConceptSearch((String) images.elementAt(i)); Element imageElement = doc.createElement("image"); Element imageNameElement = doc.createElement("name"); imageNameElement.appendChild(doc.createTextNode(name)); imageElement.appendChild(imageNameElement); for (int j = 0; j < keyWords.size(); j++) { Element keyWordElement = doc.createElement("keyWord"); keyWordElement.appendChild(doc.createTextNode((String) keyWords.elementAt(j))); imageElement.appendChild(keyWordElement); } dbElement.appendChild(imageElement); } try { doc.appendChild(dbElement); File dst = new File(directory.concat("Images")); BufferedWriter bufferWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "UTF-8")); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(bufferWriter); transformer.transform(source, result); bufferWriter.close(); } catch (Exception exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } current = lengthOfTask; } |
00
| Code Sample 1:
private void readChildrenData() throws Exception { URL url; URLConnection connect; BufferedInputStream in; try { url = getURL("CHILDREN.TAB"); connect = url.openConnection(); InputStream ois = connect.getInputStream(); if (ois == null) { concepts3 = new IntegerArray(1); return; } in = new BufferedInputStream(ois); int k1 = in.read(); concepts3 = new IntegerArray(4096); StreamDecompressor sddocs = new StreamDecompressor(in); sddocs.ascDecode(k1, concepts3); int k2 = in.read(); offsets3 = new IntegerArray(concepts3.cardinality() + 1); offsets3.add(0); StreamDecompressor sdoffsets = new StreamDecompressor(in); sdoffsets.ascDecode(k2, offsets3); in.close(); url = getURL("CHILDREN"); connect = url.openConnection(); ois = connect.getInputStream(); if (ois == null) { concepts3 = new IntegerArray(1); return; } in = new BufferedInputStream(ois); int length = connect.getContentLength(); allChildren = new byte[length]; in.read(allChildren); in.close(); } catch (MalformedURLException e) { concepts3 = new IntegerArray(1); } catch (FileNotFoundException e2) { concepts3 = new IntegerArray(1); } catch (IOException e2) { concepts3 = new IntegerArray(1); } }
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:
public Transaction() throws Exception { Connection Conn = null; Statement Stmt = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Conn = DriverManager.getConnection(DBUrl); Conn.setAutoCommit(true); Stmt = Conn.createStatement(); try { Stmt.executeUpdate("DROP TABLE trans_test"); } catch (SQLException sqlEx) { } Stmt.executeUpdate("CREATE TABLE trans_test (id int not null primary key, decdata double) type=BDB"); Conn.setAutoCommit(false); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.0)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Conn.rollback(); System.out.println("Roll Ok"); ResultSet RS = Stmt.executeQuery("SELECT * from trans_test"); if (!RS.next()) { System.out.println("Ok"); } else { System.out.println("Rollback failed"); } Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (2, 23.485115)"); Stmt.executeUpdate("INSERT INTO trans_test (id, decdata) VALUES (1, 21.485115)"); Conn.commit(); RS = Stmt.executeQuery("SELECT * from trans_test where id=2"); if (RS.next()) { System.out.println(RS.getDouble(2)); System.out.println("Ok"); } else { System.out.println("Rollback failed"); } } catch (Exception ex) { throw ex; } finally { if (Stmt != null) { try { Stmt.close(); } catch (SQLException SQLEx) { } } if (Conn != null) { try { Conn.close(); } catch (SQLException SQLEx) { } } } }
Code Sample 2:
public void removeRoom(int thisRoom) { DBConnection con = null; try { con = DBServiceManager.allocateConnection(); con.setAutoCommit(false); String query = "DELETE FROM cafe_Chat_Category WHERE cafe_Chat_Category_id=? "; PreparedStatement ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); query = "DELETE FROM cafe_Chatroom WHERE cafe_chatroom_category=? "; ps = con.prepareStatement(query); ps.setInt(1, thisRoom); ps.executeUpdate(); con.commit(); con.setAutoCommit(true); } catch (SQLException e) { try { con.rollback(); } catch (SQLException sqle) { } } finally { if (con != null) con.release(); } } |
00
| Code Sample 1:
private List _getWeathersFromYahoo(String city) { System.out.println("== get weather information of " + city + " from yahoo =="); try { URL url = new URL(URL + cities.get(city).toString()); InputStream input = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); SAXParser parser = factory.newSAXParser(); YahooHandler yh = new YahooHandler(); yh.setCity(city); parser.parse(input, yh); return yh.getWeathers(); } catch (MalformedURLException e) { throw new WeatherException("MalformedURLException"); } catch (IOException e) { throw new WeatherException("无法读取数据。"); } catch (ParserConfigurationException e) { throw new WeatherException("ParserConfigurationException"); } catch (SAXException e) { throw new WeatherException("数据格式错误,无法解析。"); } }
Code Sample 2:
public String encryptStringWithKey(String to_be_encrypted, String aKey) { String encrypted_value = ""; char xdigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException exc) { globalErrorDictionary.takeValueForKey(("Security package does not contain appropriate algorithm"), ("Security package does not contain appropriate algorithm")); log.error("Security package does not contain appropriate algorithm"); return encrypted_value; } if (to_be_encrypted != null) { byte digest[]; byte fudge_constant[]; try { fudge_constant = ("X#@!").getBytes("UTF8"); } catch (UnsupportedEncodingException uee) { fudge_constant = ("X#@!").getBytes(); } byte fudgetoo_part[] = { (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)], (byte) xdigit[(int) (MSiteConfig.myrand() % 16)] }; int i = 0; if (aKey != null) { try { fudgetoo_part = aKey.getBytes("UTF8"); } catch (UnsupportedEncodingException uee) { fudgetoo_part = aKey.getBytes(); } } messageDigest.update(fudge_constant); try { messageDigest.update(to_be_encrypted.getBytes("UTF8")); } catch (UnsupportedEncodingException uee) { messageDigest.update(to_be_encrypted.getBytes()); } messageDigest.update(fudgetoo_part); digest = messageDigest.digest(); encrypted_value = new String(fudgetoo_part); for (i = 0; i < digest.length; i++) { int mashed; char temp[] = new char[2]; if (digest[i] < 0) { mashed = 127 + (-1 * digest[i]); } else { mashed = digest[i]; } temp[0] = xdigit[mashed / 16]; temp[1] = xdigit[mashed % 16]; encrypted_value = encrypted_value + (new String(temp)); } } return encrypted_value; } |
00
| Code Sample 1:
public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; }
Code Sample 2:
public void upgradeSingleFileModelToDirectory(File modelFile) throws IOException { byte[] buf = new byte[8192]; int bytesRead = 0; File backupModelFile = new File(modelFile.getPath() + ".bak"); FileInputStream oldModelIn = new FileInputStream(modelFile); FileOutputStream backupModelOut = new FileOutputStream(backupModelFile); while ((bytesRead = oldModelIn.read(buf)) >= 0) { backupModelOut.write(buf, 0, bytesRead); } backupModelOut.close(); oldModelIn.close(); buf = null; modelFile.delete(); modelFile.mkdir(); BufferedReader oldModelsBuff = new BomStrippingInputStreamReader(new FileInputStream(backupModelFile), "UTF-8"); File metaDataFile = new File(modelFile, ConstantParameters.FILENAMEOFModelMetaData); BufferedWriter metaDataBuff = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaDataFile), "UTF-8")); for (int i = 0; i < 8; i++) { metaDataBuff.write(oldModelsBuff.readLine()); metaDataBuff.write('\n'); } metaDataBuff.close(); int classIndex = 1; BufferedWriter modelWriter = null; String line = null; while ((line = oldModelsBuff.readLine()) != null) { if (line.startsWith("Class=") && line.contains("numTraining=") && line.contains("numPos=")) { if (modelWriter != null) { modelWriter.close(); } File nextModel = new File(modelFile, String.format(ConstantParameters.FILENAMEOFPerClassModel, Integer.valueOf(classIndex++))); modelWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(nextModel), "UTF-8")); } modelWriter.write(line); modelWriter.write('\n'); } if (modelWriter != null) { modelWriter.close(); } } |
00
| Code Sample 1:
public void executeAction(JobContext context) throws Exception { HttpClient httpClient = (HttpClient) context.resolve("httpClient"); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); Iterator<String> keySet = params.keySet().iterator(); while (keySet.hasNext()) { String key = keySet.next(); String value = params.get(key); qparams.add(new BasicNameValuePair(key, value)); } String paramString = URLEncodedUtils.format(qparams, "UTF-8"); if (this.url.endsWith("/")) { this.url = this.url.substring(0, this.url.length() - 1); } String url = this.url + paramString; URI uri = URI.create(url); HttpGet httpget = new HttpGet(uri); if (!(this.referer == null || this.referer.equals(""))) httpget.setHeader(this.referer, url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); String content = ""; if (entity != null) { content = EntityUtils.toString(entity, "UTF-8"); } }
Code Sample 2:
public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } } |
00
| Code Sample 1:
public boolean ponerRivalxRonda(int idJugadorDiv, int idRonda, int dato) { int intResult = 0; String sql = "UPDATE jugadorxdivxronda " + " SET idPareoRival = " + dato + " WHERE jugadorxDivision_idJugadorxDivision = " + idJugadorDiv + " AND ronda_numeroRonda = " + idRonda; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); intResult = ps.executeUpdate(); connection.commit(); } catch (SQLException ex) { ex.printStackTrace(); try { connection.rollback(); } catch (SQLException exe) { exe.printStackTrace(); } } finally { conexionBD.close(ps); conexionBD.close(connection); } return (intResult > 0); }
Code Sample 2:
public static Map<String, List<String>> getResponseHeader(String address) { System.out.println(address); URLConnection conn = null; Map<String, List<String>> responseHeader = null; try { URL url = new URL(address); conn = url.openConnection(); responseHeader = conn.getHeaderFields(); } catch (Exception e) { e.printStackTrace(); } return responseHeader; } |
00
| Code Sample 1:
private void callbackWS(String xmlControl, String ws_results, long docId) { SimpleProvider config; Service service; Object ret; Call call; Object[] parameter; String method; String wsurl; URL url; NodeList delegateNodes; Node actualNode; InputSource xmlcontrolstream; try { xmlcontrolstream = new InputSource(new StringReader(xmlControl)); delegateNodes = SimpleXMLParser.parseDocument(xmlcontrolstream, AgentBehaviour.XML_CALLBACK); actualNode = delegateNodes.item(0); wsurl = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_URL); method = SimpleXMLParser.findChildEntry(actualNode, AgentBehaviour.XML_METHOD); if (wsurl == null || method == null) { System.out.println("----- Did not get method or wsurl from the properties! -----"); return; } url = new java.net.URL(wsurl); try { url.openConnection().connect(); } catch (IOException ex) { System.out.println("----- Could not connect to the webservice! -----"); } Vector v_param = new Vector(); v_param.add(ws_results); v_param.add(new Long(docId)); parameter = v_param.toArray(); config = new SimpleProvider(); config.deployTransport("http", new HTTPSender()); service = new Service(config); call = (Call) service.createCall(); call.setTargetEndpointAddress(url); call.setOperationName(new QName("http://schemas.xmlsoap.org/soap/encoding/", method)); try { ret = call.invoke(parameter); if (ret == null) { ret = new String("No response from callback function!"); } System.out.println("Callback function returned: " + ret); } catch (RemoteException ex) { System.out.println("----- Could not invoke the method! -----"); } } catch (Exception ex) { ex.printStackTrace(System.err); } }
Code Sample 2:
public boolean check(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(realm.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(password.getBytes("ISO-8859-1")); byte[] ha1 = md.digest(); String hexHa1 = new String(Hex.encodeHex(ha1)); md.reset(); md.update(method.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(uri.getBytes("ISO-8859-1")); byte[] ha2 = md.digest(); String hexHa2 = new String(Hex.encodeHex(ha2)); md.reset(); md.update(hexHa1.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(nc.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(cnonce.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(qop.getBytes("ISO-8859-1")); md.update((byte) ':'); md.update(hexHa2.getBytes("ISO-8859-1")); byte[] digest = md.digest(); String hexDigest = new String(Hex.encodeHex(digest)); return (hexDigest.equalsIgnoreCase(response)); } |
00
| Code Sample 1:
public static String hash(String value) { MessageDigest md = null; try { md = MessageDigest.getInstance(HASH_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } try { md.update(value.getBytes(INPUT_ENCODING)); } catch (UnsupportedEncodingException e) { throw new CryptoException(e); } return new BASE64Encoder().encode(md.digest()); }
Code Sample 2:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } |
11
| Code Sample 1:
public static void fileCopy(String src, String dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); int read = -1; byte[] buf = new byte[8192]; while ((read = fis.read(buf)) != -1) { fos.write(buf, 0, read); } fos.flush(); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
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:
public static void fileCopy(String src, String dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); int read = -1; byte[] buf = new byte[8192]; while ((read = fis.read(buf)) != -1) { fos.write(buf, 0, read); } fos.flush(); fos.close(); fis.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public String getContentAsString(String url) { StringBuffer sb = new StringBuffer(""); try { URL urlmy = new URL(url); HttpURLConnection con = (HttpURLConnection) urlmy.openConnection(); HttpURLConnection.setFollowRedirects(true); con.setInstanceFollowRedirects(false); con.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); String s = ""; while ((s = br.readLine()) != null) { sb.append(s + "\r\n"); } con.disconnect(); } catch (Exception ex) { this.logException(ex); } return sb.toString(); } |
00
| Code Sample 1:
@Override protected DefaultHttpClient doInBackground(Account... params) { AccountManager accountManager = AccountManager.get(mainActivity); Account account = params[0]; try { Bundle bundle = accountManager.getAuthToken(account, "ah", false, null, null).getResult(); Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT); if (intent != null) { mainActivity.startActivity(intent); } else { String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN); http_client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); HttpGet http_get = new HttpGet("http://3dforandroid.appspot.com/_ah" + "/login?continue=http://localhost/&auth=" + auth_token); HttpResponse response = http_client.execute(http_get); if (response.getStatusLine().getStatusCode() != 302) return null; for (Cookie cookie : http_client.getCookieStore().getCookies()) { if (cookie.getName().equals("ACSID")) { authClient = http_client; String json = createJsonFile(Kind); initializeSQLite(); initializeServer(json); } } } } catch (OperationCanceledException e) { e.printStackTrace(); } catch (AuthenticatorException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return http_client; }
Code Sample 2:
public void test1() throws Exception { String senha = "minhaSenha"; MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(senha.getBytes()); byte[] bytes = digest.digest(); BASE64Encoder encoder = new BASE64Encoder(); String senhaCodificada = encoder.encode(bytes); System.out.println("Senha : " + senha); System.out.println("Senha SHA1: " + senhaCodificada); } |
00
| Code Sample 1:
public static StringBuffer readURLText(URL url, StringBuffer errorText) { StringBuffer page = new StringBuffer(""); String thisLine; try { BufferedReader source = new BufferedReader(new InputStreamReader(url.openStream())); while ((thisLine = source.readLine()) != null) { page.append(thisLine + "\n"); } return page; } catch (Exception e) { return errorText; } }
Code Sample 2:
private FTPClient getClient() throws SocketException, IOException { FTPClient ftp = new FTPClient(); ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out))); ftp.setDefaultPort(getPort()); ftp.connect(getIp()); int reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { log.warn("FTP server refused connection: {}", getIp()); ftp.disconnect(); return null; } if (!ftp.login(getUsername(), getPassword())) { log.warn("FTP server refused login: {}, user: {}", getIp(), getUsername()); ftp.logout(); ftp.disconnect(); return null; } ftp.setControlEncoding(getEncoding()); ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); return ftp; } |
00
| Code Sample 1:
public static String getURLContent(String href) throws BuildException { URL url = null; String content; try { URL context = new URL("file:" + System.getProperty("user.dir") + "/"); url = new URL(context, href); InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); StringBuffer stringBuffer = new StringBuffer(); char[] buffer = new char[1024]; int len; while ((len = isr.read(buffer, 0, 1024)) > 0) stringBuffer.append(buffer, 0, len); content = stringBuffer.toString(); isr.close(); } catch (Exception ex) { throw new BuildException("Cannot get content of URL " + href + ": " + ex); } return content; }
Code Sample 2:
private boolean write(File file) { String filename = file.getPath(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); PrintStream out = new PrintStream(byteArrayOutputStream); try { StringBuffer xml = null; if (MainFrame.getInstance().getAnimation() != null) { MainFrame.getInstance().getAnimation().xml(out, "\t"); } else { xml = MainFrame.getInstance().getModel().xml("\t"); } if (file.exists()) { BufferedReader reader = new BufferedReader(new FileReader(filename)); BufferedWriter writer = new BufferedWriter(new FileWriter(filename + "~")); char[] buffer = new char[65536]; int charsRead = 0; while ((charsRead = reader.read(buffer)) > 0) writer.write(buffer, 0, charsRead); reader.close(); writer.close(); } BufferedWriter writer = new BufferedWriter(new FileWriter(filename)); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("<jpatch version=\"" + VersionInfo.ver + "\">\n"); if (xml != null) writer.write(xml.toString()); else writer.write(byteArrayOutputStream.toString()); writer.write("</jpatch>\n"); writer.close(); MainFrame.getInstance().getUndoManager().setChange(false); if (MainFrame.getInstance().getAnimation() != null) MainFrame.getInstance().getAnimation().setFile(file); else MainFrame.getInstance().getModel().setFile(file); MainFrame.getInstance().setFilename(file.getName()); return true; } catch (IOException ioException) { JOptionPane.showMessageDialog(MainFrame.getInstance(), "Unable to save file \"" + filename + "\"\n" + ioException, "Error", JOptionPane.ERROR_MESSAGE); return false; } } |
11
| Code Sample 1:
public static boolean copyFile(File from, File to, byte[] buf) { if (buf == null) buf = new byte[BUFFER_SIZE]; FileInputStream from_s = null; FileOutputStream to_s = null; try { from_s = new FileInputStream(from); to_s = new FileOutputStream(to); for (int bytesRead = from_s.read(buf); bytesRead != -1; bytesRead = from_s.read(buf)) to_s.write(buf, 0, bytesRead); from_s.close(); from_s = null; to_s.getFD().sync(); to_s.close(); to_s = null; } catch (IOException ioe) { return false; } finally { if (from_s != null) { try { from_s.close(); } catch (IOException ioe) { } } if (to_s != null) { try { to_s.close(); } catch (IOException ioe) { } } } return true; }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } |
00
| Code Sample 1:
protected EntailmentType invokeHttp(String stuff) { String data = encode("theory") + "=" + encode(stuff); URL url; EntailmentType result = EntailmentType.unkown; try { url = new URL(httpAddress); } catch (MalformedURLException e) { throw new RuntimeException("FOL Reasoner not correclty configured: '" + httpAddress + "' is not an URL"); } log.debug("sending theory to endpoint: " + url); try { 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())); String line; while ((line = rd.readLine()) != null) { log.debug("resultline: " + line); if (line.contains("Proof found")) { result = EntailmentType.entailed; } if (line.contains("Ran out of time")) { result = EntailmentType.unkown; } if (line.contains("Completion found")) { result = EntailmentType.notEntailed; } } wr.close(); rd.close(); } catch (IOException io) { throw new RuntimeException("the remote reasoner did not respond:" + io, io); } return result; }
Code Sample 2:
public static HttpURLConnection getHttpConn(String urlStr, String Method) throws IOException { URL url = null; HttpURLConnection connection = null; url = new URL(urlStr); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod(Method); connection.setUseCaches(false); connection.connect(); return connection; } |
00
| Code Sample 1:
private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); SiteResponse response = getSiteResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
Code Sample 2:
private void checkSettings() throws ConfigurationException { List serverList = getConfiguration().getServerList(); for (Object aServerList : serverList) { JiraServerDetails jiraServerDetails = (JiraServerDetails) aServerList; URL url = null; try { if (jiraServerDetails.getBaseurl() == null || "".equals(jiraServerDetails.getBaseurl())) { throw new ConfigurationException("BaseURL is empty."); } url = new URL(jiraServerDetails.getBaseurl()); String content = getURLContent(url.openConnection().getInputStream()); if (content.indexOf("Atlassian JIRA") == -1) { throw new ConfigurationException("URL (" + url.toString() + ") Doesn't put to an installation of Atlassian JIRA"); } try { jiraServerDetails.getRpcClient(true).login(); } catch (JiraException e) { throw new ConfigurationException("Jira Server ( " + url.toString() + " ) is earlier than 2.6 or has RPC disabled."); } } catch (MalformedURLException e) { throw new ConfigurationException("Malformed URL: " + url); } catch (IOException e) { throw new ConfigurationException("Unable to contact server: " + url); } try { MyIssuesFeedBuilder feed = new MyIssuesFeedBuilder(new JiraServerDetails[] { jiraServerDetails }); feed.buildFeedData(); } catch (FeedException feedException) { throw new ConfigurationException(feedException.getMessage()); } } } |
11
| Code Sample 1:
protected static void copyDeleting(File source, File dest) throws ErrorCodeException { byte[] buf = new byte[8 * 1024]; FileInputStream in = null; try { in = new FileInputStream(source); try { FileOutputStream out = new FileOutputStream(dest); try { int count; while ((count = in.read(buf)) >= 0) out.write(buf, 0, count); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new ErrorCodeException(e); } }
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:
private String fetchCompareContent() throws IOException { URL url = new URL(compareTo); StringWriter sw = new StringWriter(); IOUtils.copy(url.openStream(), sw); return sw.getBuffer().toString(); }
Code Sample 2:
private void appendArchive(File instClass) throws IOException { FileOutputStream out = new FileOutputStream(instClass.getName(), true); FileInputStream zipStream = new FileInputStream("install.jar"); byte[] buf = new byte[2048]; int read = zipStream.read(buf); while (read > 0) { out.write(buf, 0, read); read = zipStream.read(buf); } zipStream.close(); out.close(); } |
11
| Code Sample 1:
public String downloadToSdCard(String localFileName, String suffixFromHeader, String extension) { InputStream in = null; FileOutputStream fos = null; String absolutePath = null; try { Log.i(TAG, "Opening URL: " + url); StreamAndHeader inAndHeader = HTTPUtils.openWithHeader(url, suffixFromHeader); if (inAndHeader == null || inAndHeader.mStream == null) { return null; } in = inAndHeader.mStream; String sdcardpath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); String headerValue = suffixFromHeader == null || inAndHeader.mHeaderValue == null ? "" : inAndHeader.mHeaderValue; headerValue = headerValue.replaceAll("[-:]*\\s*", ""); String filename = sdcardpath + "/" + localFileName + headerValue + (extension == null ? "" : extension); mSize = in.available(); Log.i(TAG, "Downloading " + filename + ", size: " + mSize); fos = new FileOutputStream(new File(filename)); int buffersize = 1024; byte[] buffer = new byte[buffersize]; int readsize = buffersize; mCount = 0; while (readsize != -1) { readsize = in.read(buffer, 0, buffersize); if (readsize > 0) { Log.i(TAG, "Read " + readsize + " bytes..."); fos.write(buffer, 0, readsize); mCount += readsize; } } fos.flush(); fos.close(); FileInputStream controlIn = new FileInputStream(filename); mSavedSize = controlIn.available(); Log.v(TAG, "saved size: " + mSavedSize); mAbsolutePath = filename; done(); } catch (Exception e) { Log.e(TAG, "LoadingWorker.run", e); } finally { HTTPUtils.close(in); } return mAbsolutePath; }
Code Sample 2:
protected byte[] readGZippedBytes(TupleInput in) { final boolean is_compressed = in.readBoolean(); byte array[] = readBytes(in); if (array == null) return null; if (!is_compressed) { return array; } try { ByteArrayInputStream bais = new ByteArrayInputStream(array); GZIPInputStream gzin = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream(array.length); IOUtils.copyTo(gzin, baos); gzin.close(); bais.close(); return baos.toByteArray(); } catch (IOException err) { throw new RuntimeException(err); } } |
00
| Code Sample 1:
public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); }
Code Sample 2:
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } |
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 static List<String> getServers() throws Exception { List<String> servers = new ArrayList<String>(); URL url = new URL("http://tfast.org/en/servers.php"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = in.readLine()) != null) { if (line.contains("serv=")) { int i = line.indexOf("serv="); servers.add(line.substring(i + 5, line.indexOf("\"", i))); } } in.close(); return servers; } |
00
| 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 static void main(String[] args) throws Exception { String codecClassname = args[0]; Class<?> codecClass = Class.forName(codecClassname); Configuration conf = new Configuration(); CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf); Compressor compressor = null; try { compressor = CodecPool.getCompressor(codec); CompressionOutputStream out = codec.createOutputStream(System.out, compressor); IOUtils.copyBytes(System.in, out, 4096, false); out.finish(); } finally { CodecPool.returnCompressor(compressor); } } |
00
| Code Sample 1:
public static RecordResponse loadRecord(RecordRequest recordRequest) { RecordResponse recordResponse = new RecordResponse(); try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(recordRequest.isContact() ? URL_RECORD_CONTACT : URL_RECORD_COMPANY); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("token", recordRequest.getToken())); nameValuePairs.add(new BasicNameValuePair("id", recordRequest.getId())); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); String line = EntityUtils.toString(response.getEntity()); Document document = XMLfunctions.XMLfromString(line); NodeList nodes = document.getElementsByTagName("response"); Element e = (Element) nodes.item(0); String Name__Last__First_ = XMLfunctions.getValue(e, recordRequest.isContact() ? "Name__Last__First_" : "Name"); String phone = ""; if (!recordRequest.isContact()) phone = XMLfunctions.getValue(e, "Phone"); String Email1 = XMLfunctions.getValue(e, recordRequest.isContact() ? "Personal_Email" : "Email"); String Home_Fax = XMLfunctions.getValue(e, recordRequest.isContact() ? "Home_Fax" : "Fax1"); String Address1 = XMLfunctions.getValue(e, "Address1"); String Address2 = XMLfunctions.getValue(e, "Address2"); String City = XMLfunctions.getValue(e, "City"); String State = XMLfunctions.getValue(e, "State"); String Zip = XMLfunctions.getValue(e, "Zip"); String Country = XMLfunctions.getValue(e, "Country"); String Profile = XMLfunctions.getValue(e, "Profile"); String success = XMLfunctions.getValue(e, "success"); String error = XMLfunctions.getValue(e, "error"); recordResponse.setName(Name__Last__First_); recordResponse.setPhone(phone); recordResponse.setEmail(Email1); recordResponse.setHomeFax(Home_Fax); recordResponse.setAddress1(Address1); recordResponse.setAddress2(Address2); recordResponse.setCity(City); recordResponse.setState(State); recordResponse.setZip(Zip); recordResponse.setProfile(Profile); recordResponse.setCountry(Country); recordResponse.setSuccess(success); recordResponse.setError(error); } catch (Exception e) { } return recordResponse; }
Code Sample 2:
public static void notify(String msg) throws Exception { String url = "http://api.clickatell.com/http/sendmsg?"; url = add(url, "user", user); url = add(url, "password", password); url = add(url, "api_id", apiId); url = add(url, "to", to); url = add(url, "text", msg); URL u = new URL(url); URLConnection c = u.openConnection(); InputStream is = c.getInputStream(); IOUtils.copy(is, System.out); IOUtils.closeQuietly(is); System.out.println(); } |
11
| Code Sample 1:
private static URL downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } URL localURL = destFile.toURI().toURL(); return localURL; } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
Code Sample 2:
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } |
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 copyFile(File in, File out) throws Exception { Permissions before = getFilePermissons(in); FileChannel inFile = new FileInputStream(in).getChannel(); FileChannel outFile = new FileOutputStream(out).getChannel(); inFile.transferTo(0, inFile.size(), outFile); inFile.close(); outFile.close(); setFilePermissions(out, before); } |
00
| Code Sample 1:
public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }
Code Sample 2:
public static byte[] MD5(String... strings) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); for (String string : strings) { digest.update(string.getBytes("UTF-8")); } return digest.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.toString(), e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.toString(), e); } } |
11
| Code Sample 1:
public RobotList<Percentage> sort_incr_Percentage(RobotList<Percentage> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i).percent); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value > distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Percentage> sol = new RobotList<Percentage>(Percentage.class); for (int i = 0; i < length; i++) { sol.addLast(new Percentage(distri[i].value)); } return sol; }
Code Sample 2:
public static int[] bubbleSort(int[] source) { if (source != null && source.length > 0) { boolean flag = true; while (flag) { flag = false; for (int i = 0; i < source.length - 1; i++) { if (source[i] > source[i + 1]) { int temp = source[i]; source[i] = source[i + 1]; source[i + 1] = temp; flag = true; } } } } return source; } |
00
| Code Sample 1:
private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); if (login) { postURL = "http://upload.badongo.com/mpu_upload.php"; } HttpPost httppost = new HttpPost(postURL); file = new File("g:/S2SClient.7z"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("Filename", new StringBody(file.getName())); if (login) { mpEntity.addPart("PHPSESSID", new StringBody(dataid)); } mpEntity.addPart("Filedata", cbFile); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into badongo.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println("Upload response : " + uploadresponse); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } System.out.println("res " + uploadresponse); httpclient.getConnectionManager().shutdown(); }
Code Sample 2:
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } |
00
| Code Sample 1:
public TwilioRestResponse request(String path, String method, Map<String, String> vars) throws TwilioRestException { String encoded = ""; if (vars != null) { for (String key : vars.keySet()) { try { encoded += "&" + key + "=" + URLEncoder.encode(vars.get(key), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } if (encoded.length() > 0) { encoded = encoded.substring(1); } } String url = this.endpoint + path; if (method.toUpperCase().equals("GET")) url += ((path.indexOf('?') == -1) ? "?" : "&") + encoded; try { URL resturl = new URL(url); HttpURLConnection con = (HttpURLConnection) resturl.openConnection(); String userpass = this.accountSid + ":" + this.authToken; String encodeuserpass = new String(Base64.encodeToByte(userpass.getBytes(), false)); con.setRequestProperty("Authorization", "Basic " + encodeuserpass); con.setDoOutput(true); if (method.toUpperCase().equals("GET")) { con.setRequestMethod("GET"); } else if (method.toUpperCase().equals("POST")) { con.setRequestMethod("POST"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("PUT")) { con.setRequestMethod("PUT"); OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream()); out.write(encoded); out.close(); } else if (method.toUpperCase().equals("DELETE")) { con.setRequestMethod("DELETE"); } else { throw new TwilioRestException("Unknown method " + method); } BufferedReader in = null; try { if (con.getInputStream() != null) { in = new BufferedReader(new InputStreamReader(con.getInputStream())); } } catch (IOException e) { if (con.getErrorStream() != null) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); } } if (in == null) { throw new TwilioRestException("Unable to read response from server"); } StringBuffer decodedString = new StringBuffer(); String line; while ((line = in.readLine()) != null) { decodedString.append(line); } in.close(); int responseCode = con.getResponseCode(); return new TwilioRestResponse(url, decodedString.toString(), responseCode); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
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:
public void service(TranslationRequest request, TranslationResponse response) { try { Thread.sleep((long) Math.random() * 250); } catch (InterruptedException e1) { } hits.incrementAndGet(); String key = getKey(request); RequestResponse cachedResponse = cache.get(key); if (cachedResponse == null) { response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key)); return; } response.addHeaders(cachedResponse.getExpectedResponse().getHeaders()); response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount()); response.setFailCount(cachedResponse.getExpectedResponse().getFailCount()); if (cachedResponse.getExpectedResponse().getLastModified() != -1) { response.setLastModified(cachedResponse.getExpectedResponse().getLastModified()); } try { OutputStream output = response.getOutputStream(); InputStream input = cachedResponse.getExpectedResponse().getInputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException e) { response.setEndState(new ResponseStateException(e)); return; } response.setEndState(cachedResponse.getExpectedResponse().getEndState()); }
Code Sample 2:
public PropertiesImpl(URL url) { this(); InputStream in = null; lock.lock(); try { in = url.openStream(); PropertiesLexer lexer = new PropertiesLexer(in); lexer.lex(); List<PropertiesToken> list = lexer.getList(); new PropertiesParser(list, this).parse(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { } lock.unlock(); } } |
11
| Code Sample 1:
@Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; File localFile = this.file; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { final String localName = UUID.randomUUID().toString(); List<String> encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } this.currentMessage = m; this.file = new File(Play.tmpDir, localName); this.out = new FileOutputStream(file, true); } else { ctx.sendUpstream(e); } } else { final HttpChunk chunk = (HttpChunk) msg; if (maxContentLength != -1 && (localFile.length() > (maxContentLength - chunk.getContent().readableBytes()))) { currentMessage.setHeader(HttpHeaders.Names.WARNING, "play.netty.content.length.exceeded"); } else { IOUtils.copyLarge(new ChannelBufferInputStream(chunk.getContent()), this.out); if (chunk.isLast()) { this.out.flush(); this.out.close(); currentMessage.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(localFile.length())); currentMessage.setContent(new FileChannelBuffer(localFile)); this.out = null; this.currentMessage = null; this.file = null; Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } }
Code Sample 2:
public void copyFile(String source_name, String dest_name) throws IOException { File source_file = new File(source_name); File destination_file = new File(dest_name); Reader source = null; Writer destination = null; char[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("FileCopy: no such source file: " + source_name); if (!source_file.canRead()) throw new FileCopyException("FileCopy: source file " + "is unreadable: " + source_name); if (destination_file.exists()) { if (destination_file.isFile()) { DataInputStream in = new DataInputStream(System.in); String response; if (!destination_file.canWrite()) throw new FileCopyException("FileCopy: destination " + "file is unwriteable: " + dest_name); } else { throw new FileCopyException("FileCopy: destination " + "is not a file: " + dest_name); } } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("FileCopy: destination " + "directory doesn't exist: " + dest_name); if (!parentdir.canWrite()) throw new FileCopyException("FileCopy: destination " + "directory is unwriteable: " + dest_name); } source = new BufferedReader(new FileReader(source_file)); destination = new BufferedWriter(new FileWriter(destination_file)); buffer = new char[1024]; while (true) { bytes_read = source.read(buffer, 0, 1024); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } finally { if (source != null) { try { source.close(); } catch (IOException e) { ; } } if (destination != null) { try { destination.close(); } catch (IOException e) { ; } } } } |
11
| Code Sample 1:
@RequestMapping(value = "/privatefiles/{file_name}") public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response, Principal principal) { try { Boolean validUser = false; final String currentUser = principal.getName(); Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (!auth.getPrincipal().equals(new String("anonymousUser"))) { MetabolightsUser metabolightsUser = (MetabolightsUser) auth.getPrincipal(); if (metabolightsUser != null && metabolightsUser.isCurator()) validUser = true; } if (currentUser != null) { Study study = studyService.getBiiStudy(fileName, true); Collection<User> users = study.getUsers(); Iterator<User> iter = users.iterator(); while (iter.hasNext()) { User user = iter.next(); if (user.getUserName().equals(currentUser)) { validUser = true; break; } } } if (!validUser) throw new RuntimeException(PropertyLookup.getMessage("Entry.notAuthorised")); try { InputStream is = new FileInputStream(privateFtpDirectory + fileName + ".zip"); response.setContentType("application/zip"); IOUtils.copy(is, response.getOutputStream()); } catch (Exception e) { throw new RuntimeException(PropertyLookup.getMessage("Entry.fileMissing")); } response.flushBuffer(); } catch (IOException ex) { logger.info("Error writing file to output stream. Filename was '" + fileName + "'"); throw new RuntimeException("IOError writing file to output stream"); } }
Code Sample 2:
public static boolean copyFile(File source, File dest) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(source).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } catch (IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (IOException e) { } try { if (dstChannel != null) { dstChannel.close(); } } catch (IOException e) { } } return true; } |
11
| Code Sample 1:
public static String md(String passwd) { MessageDigest md5 = null; String digest = passwd; try { md5 = MessageDigest.getInstance("MD5"); md5.update(passwd.getBytes()); byte[] digestData = md5.digest(); digest = byteArrayToHex(digestData); } catch (NoSuchAlgorithmException e) { LOG.warn("MD5 not supported. Using plain string as password!"); } catch (Exception e) { LOG.warn("Digest creation failed. Using plain string as password!"); } return digest; }
Code Sample 2:
public static String encryptPass2(String pass) throws UnsupportedEncodingException { String passEncrypt; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } md5.update(pass.getBytes()); String dis = new String(md5.digest(), 10); passEncrypt = dis.toString(); return passEncrypt; } |
00
| Code Sample 1:
protected URLConnection openConnection(URL url) throws IOException { log.log(Level.FINE, url.toString()); MSServletRequest urlManager = new MSServletRequest(url); MicroServlet servlet = getServlet(urlManager); return (new MSConnection(url, servlet, urlManager)); }
Code Sample 2:
public void importarHistoricoDoPIB(Andamento pAndamento) throws FileNotFoundException, SQLException, Exception { pAndamento.delimitarIntervaloDeVariacao(0, 49); PIB[] valoresPendentesDoPIB = obterValoresPendentesDoPIB(pAndamento); pAndamento.delimitarIntervaloDeVariacao(50, 100); if (valoresPendentesDoPIB != null && valoresPendentesDoPIB.length > 0) { String sql = "INSERT INTO tmp_TB_PIB(ULTIMO_DIA_DO_MES, PIB_ACUM_12MESES_REAL, PIB_ACUM_12MESES_DOLAR) VALUES(:ULTIMO_DIA_DO_MES, :PIB_ACUM_12MESES_REAL, :PIB_ACUM_12MESES_DOLAR)"; OraclePreparedStatement stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosASeremImportados = valoresPendentesDoPIB.length; try { int quantidadeDeRegistrosImportados = 0; int numeroDoRegistro = 0; final BigDecimal MILHAO = new BigDecimal("1000000"); for (PIB valorPendenteDoPIB : valoresPendentesDoPIB) { ++numeroDoRegistro; stmtDestino.clearParameters(); java.sql.Date vULTIMO_DIA_DO_MES = new java.sql.Date(obterUltimoDiaDoMes(valorPendenteDoPIB.mesEAno).getTime()); BigDecimal vPIB_ACUM_12MESES_REAL = valorPendenteDoPIB.valorDoPIBEmReais.multiply(MILHAO).setScale(0, RoundingMode.DOWN); BigDecimal vPIB_ACUM_12MESES_DOLAR = valorPendenteDoPIB.valorDoPIBEmDolares.multiply(MILHAO).setScale(0, RoundingMode.DOWN); stmtDestino.setDateAtName("ULTIMO_DIA_DO_MES", vULTIMO_DIA_DO_MES); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_REAL", vPIB_ACUM_12MESES_REAL); stmtDestino.setBigDecimalAtName("PIB_ACUM_12MESES_DOLAR", vPIB_ACUM_12MESES_DOLAR); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosASeremImportados * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); throw ex; } finally { if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.close(); } } } pAndamento.setPercentualCompleto(100); } |
00
| Code Sample 1:
private HttpURLConnection setUpHttpConnection(URL url, int length) throws IOException, ProtocolException { URLConnection connection = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) connection; httpConn.setRequestProperty("Content-Length", String.valueOf(length)); httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpConn.setRequestProperty("SOAPAction", "\"http://www.webserviceX.NET/GetQuote\""); httpConn.setRequestMethod("POST"); httpConn.setDoOutput(true); httpConn.setDoInput(true); return httpConn; }
Code Sample 2:
@Override public void sendData(String serverUrl, String fileName, String type, InputStream is) throws IOException { ClientSession clientSession = null; try { if (logger.isDebugEnabled()) { logger.debug("Connecting to " + serverUrl); } clientSession = (ClientSession) Connector.open(serverUrl); HeaderSet hsConnectReply = clientSession.connect(clientSession.createHeaderSet()); if (hsConnectReply.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Connect Error " + hsConnectReply.getResponseCode()); } HeaderSet hsOperation = clientSession.createHeaderSet(); hsOperation.setHeader(HeaderSet.NAME, fileName); if (type != null) { hsOperation.setHeader(HeaderSet.TYPE, type); } hsOperation.setHeader(HeaderSet.LENGTH, new Long(is.available())); Operation po = clientSession.put(hsOperation); OutputStream os = po.openOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); if (logger.isDebugEnabled()) { logger.debug("put responseCode " + po.getResponseCode()); } po.close(); HeaderSet hsDisconnect = clientSession.disconnect(null); if (logger.isDebugEnabled()) { logger.debug("disconnect responseCode " + hsDisconnect.getResponseCode()); } if (hsDisconnect.getResponseCode() != ResponseCodes.OBEX_HTTP_OK) { throw new IOException("Send Error " + hsConnectReply.getResponseCode()); } } finally { if (clientSession != null) { try { clientSession.close(); } catch (IOException ignore) { if (logger.isDebugEnabled()) { logger.debug("IOException during clientSession.close()", ignore); } } } clientSession = null; } } |
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 copyFile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } catch (FileNotFoundException ex) { System.out.println("Error copying " + srFile + " to " + dtFile); System.out.println(ex.getMessage() + " in the specified directory."); } catch (IOException e) { System.out.println(e.getMessage()); } } |
11
| Code Sample 1:
public static String cryptSha(String target) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(target.getBytes("UTF-16")); BigInteger res = new BigInteger(1, md.digest(key.getBytes())); return res.toString(16); }
Code Sample 2:
public static final synchronized String md5(final String data) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(data.getBytes()); final byte[] b = md.digest(); return toHexString(b); } catch (final Exception e) { } return ""; } |
00
| Code Sample 1:
@Test public void testCopy_inputStreamToWriter_Encoding_nullEncoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, null); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
Code Sample 2:
public Scene load(URL url) throws FileNotFoundException, IncorrectFormatException, ParsingErrorException { BufferedReader reader; if (baseUrl == null) setBaseUrlFromUrl(url); try { reader = new BufferedReader(new InputStreamReader(url.openStream())); } catch (IOException e) { throw new FileNotFoundException(e.getMessage()); } fromUrl = true; return load(reader); } |
00
| Code Sample 1:
public int addPermissionsForUserAndAgenda(Integer userId, Integer agendaId, String permissions) throws TechnicalException { if (permissions == null) { throw new TechnicalException(new Exception(new Exception("Column 'permissions' cannot be null"))); } Session session = null; Transaction transaction = null; try { session = HibernateUtil.getCurrentSession(); transaction = session.beginTransaction(); String query = "INSERT INTO j_user_agenda (userId, agendaId, permissions) VALUES(" + userId + "," + agendaId + ",\"" + permissions + "\")"; Statement statement = session.connection().createStatement(); int rowsUpdated = statement.executeUpdate(query); transaction.commit(); return rowsUpdated; } catch (HibernateException ex) { if (transaction != null) transaction.rollback(); throw new TechnicalException(ex); } catch (SQLException e) { if (transaction != null) transaction.rollback(); throw new TechnicalException(e); } }
Code Sample 2:
public String downloadToSdCard(String localFileName, String suffixFromHeader, String extension) { InputStream in = null; FileOutputStream fos = null; String absolutePath = null; try { Log.i(TAG, "Opening URL: " + url); StreamAndHeader inAndHeader = HTTPUtils.openWithHeader(url, suffixFromHeader); if (inAndHeader == null || inAndHeader.mStream == null) { return null; } in = inAndHeader.mStream; String sdcardpath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath(); String headerValue = suffixFromHeader == null || inAndHeader.mHeaderValue == null ? "" : inAndHeader.mHeaderValue; headerValue = headerValue.replaceAll("[-:]*\\s*", ""); String filename = sdcardpath + "/" + localFileName + headerValue + (extension == null ? "" : extension); mSize = in.available(); Log.i(TAG, "Downloading " + filename + ", size: " + mSize); fos = new FileOutputStream(new File(filename)); int buffersize = 1024; byte[] buffer = new byte[buffersize]; int readsize = buffersize; mCount = 0; while (readsize != -1) { readsize = in.read(buffer, 0, buffersize); if (readsize > 0) { Log.i(TAG, "Read " + readsize + " bytes..."); fos.write(buffer, 0, readsize); mCount += readsize; } } fos.flush(); fos.close(); FileInputStream controlIn = new FileInputStream(filename); mSavedSize = controlIn.available(); Log.v(TAG, "saved size: " + mSavedSize); mAbsolutePath = filename; done(); } catch (Exception e) { Log.e(TAG, "LoadingWorker.run", e); } finally { HTTPUtils.close(in); } return mAbsolutePath; } |
00
| Code Sample 1:
public void startImport(ActionEvent evt) { final PsiExchange psiExchange = PsiExchangeFactory.createPsiExchange(IntactContext.getCurrentInstance().getSpringContext()); for (final URL url : urlsToImport) { try { if (log.isInfoEnabled()) log.info("Importing: " + url); psiExchange.importIntoIntact(url.openStream()); } catch (IOException e) { handleException(e); return; } } addInfoMessage("File successfully imported", Arrays.asList(urlsToImport).toString()); }
Code Sample 2:
private Attachment setupSimpleAttachment(Context context, long messageId, boolean withBody) throws IOException { Attachment attachment = new Attachment(); attachment.mFileName = "the file.jpg"; attachment.mMimeType = "image/jpg"; attachment.mSize = 0; attachment.mContentId = null; attachment.mContentUri = "content://com.android.email/1/1"; attachment.mMessageKey = messageId; attachment.mLocation = null; attachment.mEncoding = null; if (withBody) { InputStream inStream = new ByteArrayInputStream(TEST_STRING.getBytes()); File cacheDir = context.getCacheDir(); File tmpFile = File.createTempFile("setupSimpleAttachment", "tmp", cacheDir); OutputStream outStream = new FileOutputStream(tmpFile); IOUtils.copy(inStream, outStream); attachment.mContentUri = "file://" + tmpFile.getAbsolutePath(); } return attachment; } |
11
| Code Sample 1:
private void copyOutResource(String dstPath, InputStream in) throws FileNotFoundException, IOException { FileOutputStream out = null; try { dstPath = this.outputDir + dstPath; File file = new File(dstPath); file.getParentFile().mkdirs(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } } }
Code Sample 2:
private void writeData(IBaseType dataType, Writer writer) throws XMLStreamException { InputStream isData; DataType data = (DataType) baseType; if (data.isSetInputStream()) { isData = data.getInputStream(); try { IOUtils.copy(isData, writer); } catch (IOException e) { throw new XMLStreamException("DataType fail writing streaming data ", e); } } else if (data.isSetOutputStream()) { throw new XMLStreamException("DataType only can write streaming input, its an output stream (only for reading) "); } else { new CharactersEventImpl(startElement.getLocation(), String.valueOf(baseType.asData()), false).writeAsEncodedUnicode(writer); } } |
11
| Code Sample 1:
private String generateUniqueIdMD5(String workgroupIdString, String runIdString) { String passwordUnhashed = workgroupIdString + "-" + runIdString; MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } m.update(passwordUnhashed.getBytes(), 0, passwordUnhashed.length()); String uniqueIdMD5 = new BigInteger(1, m.digest()).toString(16); return uniqueIdMD5; }
Code Sample 2:
public String getHash(String type, String text, String salt) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance(type); byte[] hash = new byte[md.getDigestLength()]; if (!salt.isEmpty()) { md.update(salt.getBytes("iso-8859-1"), 0, salt.length()); } md.update(text.getBytes("iso-8859-1"), 0, text.length()); hash = md.digest(); return convertToHex(hash); } |
00
| Code Sample 1:
private static File copyFileTo(File file, File directory) throws IOException { File newFile = new File(directory, file.getName()); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(file); fos = new FileOutputStream(newFile); byte buff[] = new byte[1024]; int val; while ((val = fis.read(buff)) > 0) fos.write(buff, 0, val); } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } return newFile; }
Code Sample 2:
protected void channelConnected() throws IOException { MessageDigest md = null; String digest = ""; try { String userid = nateon.getUserId(); if (userid.endsWith("@nate.com")) userid = userid.substring(0, userid.lastIndexOf('@')); md = MessageDigest.getInstance("MD5"); md.update(nateon.getPassword().getBytes()); md.update(userid.getBytes()); byte[] bData = md.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bData) { int v = (int) b; v = v < 0 ? v + 0x100 : v; String s = Integer.toHexString(v); if (s.length() == 1) sb.append('0'); sb.append(s); } digest = sb.toString(); } catch (Exception e) { e.printStackTrace(); } NateOnMessage out = new NateOnMessage("LSIN"); out.add(nateon.getUserId()).add(digest).add("MD5").add("3.615"); out.setCallback("processAuth"); writeMessage(out); } |
11
| Code Sample 1:
public static InputStream gunzip(final InputStream inputStream) throws IOException { Assert.notNull(inputStream, "inputStream"); GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream); InputOutputStream inputOutputStream = new InputOutputStream(); IOUtils.copy(gzipInputStream, inputOutputStream); return inputOutputStream.getInputStream(); }
Code Sample 2:
private JButton getButtonSonido() { if (buttonSonido == null) { buttonSonido = new JButton(); buttonSonido.setText(Messages.getString("gui.AdministracionResorces.15")); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetree.png")); buttonSonido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonSonido; } |
11
| Code Sample 1:
private void extractSourceFiles(String jar) { JarInputStream in = null; BufferedOutputStream out = null; try { in = new JarInputStream(new FileInputStream(getProjectFile(jar))); JarEntry item; byte buffer[] = new byte[4096]; int buflength; while ((item = in.getNextJarEntry()) != null) if (item.getName().startsWith(PREFIX) && (!item.getName().endsWith("/"))) { out = new BufferedOutputStream(new FileOutputStream(new File(dest, getFileName(item)))); while ((buflength = in.read(buffer)) != -1) out.write(buffer, 0, buflength); howmany++; out.flush(); out.close(); out = null; } } catch (IOException ex) { System.out.println("Unable to parse file " + jar + ", reason: " + ex.getMessage()); } finally { try { if (in != null) in.close(); } catch (IOException ex) { } try { if (out != null) out.close(); } catch (IOException ex) { } } }
Code Sample 2:
public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); } |
11
| Code Sample 1:
private void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public static synchronized void repartition(File[] sourceFiles, File targetDirectory, String prefix, long maxUnitBases, long maxUnitEntries) throws Exception { if (!targetDirectory.exists()) { if (!targetDirectory.mkdirs()) throw new Exception("Could not create directory " + targetDirectory.getAbsolutePath()); } File tmpFile = new File(targetDirectory, "tmp.fasta"); FileOutputStream fos = new FileOutputStream(tmpFile); FileChannel fco = fos.getChannel(); for (File file : sourceFiles) { FileInputStream fis = new FileInputStream(file); FileChannel fci = fis.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(64000); while (fci.read(buffer) > 0) { buffer.flip(); fco.write(buffer); buffer.clear(); } fci.close(); } fco.close(); FastaFile fastaFile = new FastaFile(tmpFile); fastaFile.split(targetDirectory, prefix, maxUnitBases, maxUnitEntries); tmpFile.delete(); } |
00
| Code Sample 1:
public void createCodeLocation() { List<IClasspathEntry> classpathEntries = new UniqueEList<IClasspathEntry>(); project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectname); try { IProjectDescription projectDescription = null; IJavaProject javaProject = JavaCore.create(project); if (project.exists()) { project.delete(true, null); } projectDescription = ResourcesPlugin.getWorkspace().newProjectDescription(projectname); project.create(projectDescription, new NullProgressMonitor()); String[] natureIds = projectDescription.getNatureIds(); if (natureIds == null) { natureIds = new String[] { JavaCore.NATURE_ID }; } else { boolean hasJavaNature = false; boolean hasPDENature = false; for (int i = 0; i < natureIds.length; ++i) { if (JavaCore.NATURE_ID.equals(natureIds[i])) { hasJavaNature = true; } if ("org.eclipse.pde.PluginNature".equals(natureIds[i])) { hasPDENature = true; } } if (!hasJavaNature) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = JavaCore.NATURE_ID; } if (!hasPDENature) { String[] oldNatureIds = natureIds; natureIds = new String[oldNatureIds.length + 1]; System.arraycopy(oldNatureIds, 0, natureIds, 0, oldNatureIds.length); natureIds[oldNatureIds.length] = "org.eclipse.pde.PluginNature"; } } projectDescription.setNatureIds(natureIds); ICommand[] builders = projectDescription.getBuildSpec(); if (builders == null) { builders = new ICommand[0]; } boolean hasManifestBuilder = false; boolean hasSchemaBuilder = false; for (int i = 0; i < builders.length; ++i) { if ("org.eclipse.pde.ManifestBuilder".equals(builders[i].getBuilderName())) { hasManifestBuilder = true; } if ("org.eclipse.pde.SchemaBuilder".equals(builders[i].getBuilderName())) { hasSchemaBuilder = true; } } if (!hasManifestBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.ManifestBuilder"); } if (!hasSchemaBuilder) { ICommand[] oldBuilders = builders; builders = new ICommand[oldBuilders.length + 1]; System.arraycopy(oldBuilders, 0, builders, 0, oldBuilders.length); builders[oldBuilders.length] = projectDescription.newCommand(); builders[oldBuilders.length].setBuilderName("org.eclipse.pde.SchemaBuilder"); } projectDescription.setBuildSpec(builders); project.open(new NullProgressMonitor()); project.setDescription(projectDescription, new NullProgressMonitor()); sourceContainer = project.getFolder("src"); sourceContainer.create(false, true, new NullProgressMonitor()); IClasspathEntry sourceClasspathEntry = JavaCore.newSourceEntry(new Path("/" + projectname + "/src")); classpathEntries.add(0, sourceClasspathEntry); String jreContainer = JavaRuntime.JRE_CONTAINER; String complianceLevel = CodeGenUtil.EclipseUtil.getJavaComplianceLevel(project); if ("1.5".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"; } else if ("1.6".equals(complianceLevel)) { jreContainer += "/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"; } classpathEntries.add(JavaCore.newContainerEntry(new Path(jreContainer))); classpathEntries.add(JavaCore.newContainerEntry(new Path("org.eclipse.pde.core.requiredPlugins"))); javaProject.setOutputLocation(new Path("/" + projectname + "/bin"), new NullProgressMonitor()); javaProject.setRawClasspath(classpathEntries.toArray(new IClasspathEntry[classpathEntries.size()]), new NullProgressMonitor()); } catch (CoreException e) { e.printStackTrace(); CodeGenEcorePlugin.INSTANCE.log(e); } }
Code Sample 2:
public void concatFiles() throws IOException { Writer writer = null; try { final File targetFile = new File(getTargetDirectory(), getTargetFile()); targetFile.getParentFile().mkdirs(); if (null != getEncoding()) { getLog().info("Writing aggregated file with encoding '" + getEncoding() + "'"); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), getEncoding())); } else { getLog().info("WARNING: writing aggregated file with system encoding"); writer = new FileWriter(targetFile); } for (File file : getFiles()) { Reader reader = null; try { if (null != getEncoding()) { getLog().info("Reading file " + file.getCanonicalPath() + " with encoding '" + getEncoding() + "'"); reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), getEncoding())); } else { getLog().info("WARNING: Reading file " + file.getCanonicalPath() + " with system encoding"); reader = new FileReader(file); } IOUtils.copy(reader, writer); final String delimiter = getDelimiter(); if (delimiter != null) { writer.write(delimiter.toCharArray()); } } finally { IOUtils.closeQuietly(reader); } } } finally { IOUtils.closeQuietly(writer); } } |
00
| Code Sample 1:
public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
Code Sample 2:
public static void messageDigestTest() { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update("computer".getBytes()); md.update("networks".getBytes()); System.out.println(new String(md.digest())); System.out.println(new String(md.digest("computernetworks".getBytes()))); } catch (Exception e) { e.printStackTrace(); } } |
11
| Code Sample 1:
public void render(final HttpServletRequest request, final HttpServletResponse response, InputStream inputStream, final Throwable t, final String contentType, final String encoding) throws Exception { if (contentType != null) { response.setContentType(contentType); } if (encoding != null) { response.setCharacterEncoding(encoding); } IOUtils.copy(inputStream, response.getOutputStream()); }
Code Sample 2:
public static boolean copyFile(File src, File dest) throws IOException { if (src == null) { throw new IllegalArgumentException("src == null"); } if (dest == null) { throw new IllegalArgumentException("dest == null"); } if (!src.isFile()) { return false; } FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); return true; } catch (IOException e) { throw e; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } |
11
| Code Sample 1:
public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
Code Sample 2:
private static void execute(String fileName) throws IOException, SQLException { InputStream input = DatabaseConstants.class.getResourceAsStream(fileName); StringWriter writer = new StringWriter(); IOUtils.copy(input, writer); String sql = writer.toString(); Statement statement = connection.createStatement(); statement.execute(sql); } |
00
| Code Sample 1:
public static String replace(URL url, Replacer replacer) throws Exception { URLConnection con = url.openConnection(); InputStreamReader reader = new InputStreamReader(con.getInputStream()); StringWriter wr = new StringWriter(); int c; StringBuffer token = null; while ((c = reader.read()) != -1) { if (c == '@') { if (token == null) { token = new StringBuffer(); } else { String val = replacer.replace(token.toString()); if (val != null) { wr.write(val); token = null; } else { wr.write('@'); wr.write(token.toString()); token.delete(0, token.length()); } } } else { if (token == null) { wr.write((char) c); } else { token.append((char) c); } } } if (token != null) { wr.write('@'); wr.write(token.toString()); } return wr.toString(); }
Code Sample 2:
public void sendMessage(String messageBufferName, String messageStr, String timeout) throws AppFabricException { MessageBufferUtil msgBufferUtilObj = new MessageBufferUtil(solutionName, TokenConstants.getSimpleAuthAuthenticationType()); String requestUri = msgBufferUtilObj.getRequestUri(); String sendPath = MessageBufferConstants.getPATH_FOR_SEND_MESSAGE(); String timeOutParameter = MessageBufferConstants.getTIMEOUTPARAMETER(); String messageBufferUri = msgBufferUtilObj.getMessageUri(messageBufferName, sendPath); String message = msgBufferUtilObj.getFormattedMessage(messageStr); String authorizationToken = ""; try { ACSTokenProvider tp = new ACSTokenProvider(httpWebProxyServer_, httpWebProxyPort_, this.credentials); authorizationToken = tp.getACSToken(requestUri, messageBufferUri); messageBufferUri = messageBufferUri.replaceAll("http", "https"); String sendUri = messageBufferUri + "?" + timeOutParameter + "=" + timeout; URL urlConn = new URL(sendUri); HttpURLConnection connection; if (httpWebProxy_ != null) connection = (HttpURLConnection) urlConn.openConnection(httpWebProxy_); else connection = (HttpURLConnection) urlConn.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", MessageBufferConstants.getCONTENT_TYPE_PROPERTY_FOR_TEXT()); connection.setRequestProperty("Content-Length", "" + message.length()); connection.setRequestProperty("Expect", "100-continue"); connection.setRequestProperty("Accept", "*/*"); String authStr = TokenConstants.getWrapAuthenticationType() + " " + TokenConstants.getWrapAuthorizationHeaderKey() + "=\"" + authorizationToken + "\""; connection.setRequestProperty("Authorization", authStr); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(message); wr.flush(); wr.close(); if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logRequest(connection, SDKLoggerHelper.RecordType.SendMessage_REQUEST); String responseCode = "<responseCode>" + connection.getResponseCode() + "</responseCode>"; if (!((connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_ACCEPTED) || (connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_CREATED) || (connection.getResponseCode() == MessageBufferConstants.HTTP_STATUS_CODE_OK))) { throw new AppFabricException("Message could not be sent. Error.Response code: " + connection.getResponseCode()); } if (LoggerUtil.getIsLoggingOn()) SDKLoggerHelper.logMessage(URLEncoder.encode(responseCode, "UTF-8"), SDKLoggerHelper.RecordType.SendMessage_RESPONSE); } catch (Exception e) { throw new AppFabricException(e.getMessage()); } } |
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:
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:
@Override public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("getAudioFileFormat(URL url)"); } InputStream inputStream = url.openStream(); try { return getAudioFileFormat(inputStream); } finally { if (inputStream != null) { inputStream.close(); } } }
Code Sample 2:
public final Matrix3D<E> read(final URL url) throws IOException { if (url == null) { throw new IllegalArgumentException("url must not be null"); } InputStream inputStream = null; try { inputStream = url.openStream(); return read(inputStream); } catch (IOException e) { throw e; } finally { MatrixIOUtils.closeQuietly(inputStream); } } |
00
| Code Sample 1:
public void update() { try { String passwordMD5 = new String(); if (this.password != null && this.password.length() > 0) { MessageDigest md = MessageDigest.getInstance("md5"); md.update(this.password.getBytes()); byte[] digest = md.digest(); for (int i = 0; i < digest.length; i++) { passwordMD5 += Integer.toHexString((digest[i] >> 4) & 0xf); passwordMD5 += Integer.toHexString((digest[i] & 0xf)); } } this.authCode = new String(Base64Encoder.encode(new String(this.username + ";" + passwordMD5).getBytes())); } catch (Throwable throwable) { throwable.printStackTrace(); } }
Code Sample 2:
public int getHttpStatus(ProxyInfo proxyInfo, String sUrl, String cookie, String host) { HttpURLConnection connection = null; try { if (proxyInfo == null) { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); } else { InetSocketAddress addr = new InetSocketAddress(proxyInfo.getPxIp(), proxyInfo.getPxPort()); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(proxy); } if (!isStringNull(host)) setHttpInfo(connection, cookie, host, ""); connection.setConnectTimeout(90 * 1000); connection.setReadTimeout(90 * 1000); connection.connect(); connection.getInputStream(); return connection.getResponseCode(); } catch (IOException e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } catch (Exception e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } } |
00
| Code Sample 1:
public static String getFileContents(String path) { BufferedReader buffReader = null; if (path.indexOf("://") != -1) { URL url = null; try { url = new URL(path); } catch (MalformedURLException e) { logger.warn("Malformed URL: \"" + path + "\""); } try { String encoding = XMLKit.getDeclaredXMLEncoding(url.openStream()); buffReader = new BufferedReader(new InputStreamReader(url.openStream(), encoding)); } catch (IOException e) { logger.warn("I/O error trying to read \"" + 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("Created an invalid parent file: \"" + parent + "\".", e); } } if (toRead.exists() && !toRead.isDirectory()) { path = toRead.getAbsolutePath(); try { String encoding = XMLKit.getDeclaredXMLEncoding(new FileInputStream(path)); buffReader = new BufferedReader(new InputStreamReader(new FileInputStream(path), encoding)); } catch (IOException e) { logger.warn("I/O error trying to read \"" + 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; try { while ((line = buffReader.readLine()) != null) { result.append(line); } buffReader.close(); } catch (IOException e) { logger.warn("I/O error trying to read \"" + path + "\""); return null; } return result.toString(); }
Code Sample 2:
protected byte[] getBytesForWebPageUsingHTTPClient(String urlString) throws ClientProtocolException, IOException { log("Retrieving url: " + urlString); DefaultHttpClient httpclient = new DefaultHttpClient(); if (this.archiveAccessSpecification.getUserID() != null) { httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(this.archiveAccessSpecification.getUserID(), this.archiveAccessSpecification.getUserPassword())); } HttpGet httpget = new HttpGet(urlString); log("about to do request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); log("-------------- Request results --------------"); log("Status line: " + response.getStatusLine()); if (entity != null) { log("Response content length: " + entity.getContentLength()); } log("contents"); byte[] bytes = null; if (entity != null) { bytes = getBytesFromInputStream(entity.getContent()); entity.consumeContent(); } log("Status code :" + response.getStatusLine().getStatusCode()); log(response.getStatusLine().getReasonPhrase()); if (response.getStatusLine().getStatusCode() != 200) return null; return bytes; } |
00
| Code Sample 1:
private void detachFile(File file, Block b) throws IOException { File tmpFile = volume.createDetachFile(b, file.getName()); try { IOUtils.copyBytes(new FileInputStream(file), new FileOutputStream(tmpFile), 16 * 1024, true); if (file.length() != tmpFile.length()) { throw new IOException("Copy of file " + file + " size " + file.length() + " into file " + tmpFile + " resulted in a size of " + tmpFile.length()); } FileUtil.replaceFile(tmpFile, file); } catch (IOException e) { boolean done = tmpFile.delete(); if (!done) { DataNode.LOG.info("detachFile failed to delete temporary file " + tmpFile); } throw e; } }
Code Sample 2:
public static String md5hash(String data) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(data.getBytes()); return new BigInteger(1, digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { LOG.error(e); } return null; } |
11
| Code Sample 1:
private void addAuditDatastream() throws ObjectIntegrityException, StreamIOException { if (m_obj.getAuditRecords().size() == 0) { return; } String dsId = m_pid.toURI() + "/AUDIT"; String dsvId = dsId + "/" + DateUtility.convertDateToString(m_obj.getCreateDate()); Entry dsEntry = m_feed.addEntry(); dsEntry.setId(dsId); dsEntry.setTitle("AUDIT"); dsEntry.setUpdated(m_obj.getCreateDate()); dsEntry.addCategory(MODEL.STATE.uri, "A", null); dsEntry.addCategory(MODEL.CONTROL_GROUP.uri, "X", null); dsEntry.addCategory(MODEL.VERSIONABLE.uri, "false", null); dsEntry.addLink(dsvId, Link.REL_ALTERNATE); Entry dsvEntry = m_feed.addEntry(); dsvEntry.setId(dsvId); dsvEntry.setTitle("AUDIT.0"); dsvEntry.setUpdated(m_obj.getCreateDate()); ThreadHelper.addInReplyTo(dsvEntry, m_pid.toURI() + "/AUDIT"); dsvEntry.addCategory(MODEL.FORMAT_URI.uri, AUDIT1_0.uri, null); dsvEntry.addCategory(MODEL.LABEL.uri, "Audit Trail for this object", null); if (m_format.equals(ATOM_ZIP1_1)) { String name = "AUDIT.0.xml"; try { m_zout.putNextEntry(new ZipEntry(name)); Reader r = new StringReader(DOTranslationUtility.getAuditTrail(m_obj)); IOUtils.copy(r, m_zout, m_encoding); m_zout.closeEntry(); r.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); dsvEntry.setSummary("AUDIT.0"); dsvEntry.setContent(iri, "text/xml"); } else { dsvEntry.setContent(DOTranslationUtility.getAuditTrail(m_obj), "text/xml"); } }
Code Sample 2:
private void importSources() { InputOutput io = IOProvider.getDefault().getIO("Import Sources", false); io.select(); PrintWriter pw = new PrintWriter(io.getOut()); pw.println("Beginning transaction...."); pw.println("Processing selected files:"); String[][] selectedFiles = getSelectedFiles(pw); if (selectedFiles.length == 0) { pw.println("There are no files to process."); } else { pw.println(new StringBuilder("Importing ").append(selectedFiles.length).append(" files to ").append(group.getDisplayName()).append(" within project ").append(ProjectUtils.getInformation(project).getDisplayName()).toString()); FileObject destFO = group.getRootFolder(); try { String destRootDir = new File(destFO.getURL().toURI()).getAbsolutePath(); if (destFO.canWrite()) { for (String[] s : selectedFiles) { try { File parentDir = new File(new StringBuilder(destRootDir).append(File.separator).append(s[0]).toString()); if (!parentDir.exists()) { parentDir.mkdirs(); } File f = new File(new StringBuilder(destRootDir).append(s[0]).append(File.separator).append(s[1]).toString()); if (!f.exists()) { f.createNewFile(); } FileInputStream fin = null; FileOutputStream fout = null; byte[] b = new byte[1024]; int read = -1; try { File inputFile = new File(new StringBuilder(rootDir).append(s[0]).append(File.separator).append(s[1]).toString()); pw.print(new StringBuilder("\tImporting file:").append(inputFile.getAbsolutePath()).toString()); fin = new FileInputStream(inputFile); fout = new FileOutputStream(f); while ((read = fin.read(b)) != -1) { fout.write(b, 0, read); } pw.println(" ... done"); fin.close(); fout.close(); } catch (FileNotFoundException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } catch (IOException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } finally { if (fin != null) { try { fin.close(); } catch (IOException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } } if (fout != null) { try { fout.close(); } catch (IOException ex) { } } } } catch (IOException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); } } pw.println("Import sources completed successfully."); } else { pw.println("Cannot write to the destination directory." + " Please check the priviledges and try again."); return; } } catch (FileStateInvalidException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); pw.println("Import failed!!"); } catch (URISyntaxException ex) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Exception(ex, "Error while importing sources!")); pw.println("Import failed!!"); } } } |
11
| Code Sample 1:
@Override public void save(String arxivId, InputStream inputStream, String encoding) { String filename = StringUtil.arxivid2filename(arxivId, "tex"); try { Writer writer = new OutputStreamWriter(new FileOutputStream(String.format("%s/%s", LATEX_DOCUMENT_DIR, filename)), encoding); IOUtils.copy(inputStream, writer, encoding); writer.flush(); writer.close(); inputStream.close(); } catch (IOException e) { logger.error("Failed to save the Latex source with id='{}'", arxivId, e); throw new RuntimeException(e); } }
Code Sample 2:
public static boolean compress(File source, File target, Manifest manifest) { try { if (!(source.exists() & source.isDirectory())) return false; if (target.exists()) target.delete(); ZipOutputStream output = null; boolean isJar = target.getName().toLowerCase().endsWith(".jar"); if (isJar) { File manifestDir = new File(source, "META-INF"); remove(manifestDir); if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target)); } else output = new ZipOutputStream(new FileOutputStream(target)); ArrayList list = getContents(source); String baseDir = source.getAbsolutePath().replace('\\', '/'); if (!baseDir.endsWith("/")) baseDir = baseDir + "/"; int baseDirLength = baseDir.length(); byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0, n = list.size(); i < n; i++) { File file = (File) list.get(i); FileInputStream f_in = new FileInputStream(file); String filename = file.getAbsolutePath().replace('\\', '/'); if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength); if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename)); while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); f_in.close(); output.closeEntry(); } output.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; } |
11
| Code Sample 1:
public void write(OutputStream out, String className, InputStream classDefStream) throws IOException { ByteArrayOutputStream a = new ByteArrayOutputStream(); IOUtils.copy(classDefStream, a); a.close(); DataOutputStream da = new DataOutputStream(out); da.writeUTF(className); da.writeUTF(new String(base64.cipher(a.toByteArray()))); }
Code Sample 2:
void copyFile(String src, String dest) throws IOException { int amount; byte[] buffer = new byte[4096]; FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dest); while ((amount = in.read(buffer)) != -1) out.write(buffer, 0, amount); in.close(); out.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 void writeOutput(String directory) throws IOException { File f = new File(directory); int i = 0; if (f.isDirectory()) { for (AppInventorScreen screen : screens.values()) { File screenFile = new File(getScreenFilePath(f.getAbsolutePath(), screen)); screenFile.getParentFile().mkdirs(); screenFile.createNewFile(); FileWriter out = new FileWriter(screenFile); String initial = files.get(i).toString(); Map<String, String> types = screen.getTypes(); String[] lines = initial.split("\n"); for (String key : types.keySet()) { if (!key.trim().equals(screen.getName().trim())) { String value = types.get(key); boolean varFound = false; boolean importFound = false; for (String line : lines) { if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*=.*;$")) varFound = true; if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*;$")) varFound = true; if (line.matches("^\\s*import\\s+.*" + value + "\\s*;$")) importFound = true; } if (!varFound) initial = initial.replaceFirst("(?s)(?<=\\{\n)", "\tprivate " + value + " " + key + ";\n"); if (!importFound) initial = initial.replaceFirst("(?=import)", "import com.google.devtools.simple.runtime.components.android." + value + ";\n"); } } out.write(initial); out.close(); i++; } File manifestFile = new File(getManifestFilePath(f.getAbsolutePath(), manifest)); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); FileWriter out = new FileWriter(manifestFile); out.write(manifest.toString()); out.close(); File projectFile = new File(getProjectFilePath(f.getAbsolutePath(), project)); projectFile.getParentFile().mkdirs(); projectFile.createNewFile(); out = new FileWriter(projectFile); out.write(project.toString()); out.close(); String[] copyResourceFilenames = { "proguard.cfg", "project.properties", "libSimpleAndroidRuntime.jar", "\\.classpath", "res/drawable/icon.png", "\\.settings/org.eclipse.jdt.core.prefs" }; for (String copyResourceFilename : copyResourceFilenames) { InputStream is = getClass().getResourceAsStream("/resources/" + copyResourceFilename.replace("\\.", "")); File outputFile = new File(f.getAbsoluteFile() + File.separator + copyResourceFilename.replace("\\.", ".")); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; if (is == null) System.out.println("/resources/" + copyResourceFilename.replace("\\.", "")); if (os == null) System.out.println(f.getAbsolutePath() + File.separator + copyResourceFilename.replace("\\.", ".")); while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } for (String assetName : assets) { InputStream is = new FileInputStream(new File(assetsDir.getAbsolutePath() + File.separator + assetName)); File outputFile = new File(f.getAbsoluteFile() + File.separator + assetName); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } File assetsOutput = new File(getAssetsFilePath(f.getAbsolutePath())); new File(assetsDir.getAbsoluteFile() + File.separator + "assets").renameTo(assetsOutput); } } |
11
| Code Sample 1:
public String getNextSequence(Integer id) throws ApplicationException { java.sql.PreparedStatement preStat = null; java.sql.ResultSet rs = null; boolean noRecordMatch = false; String prefix = ""; String suffix = ""; Long startID = null; Integer length = null; Long currID = null; Integer increment = null; int nextID; String formReferenceID = null; synchronized (lock) { synchronized (dbConn) { try { preStat = dbConn.prepareStatement("SELECT PREFIX,SUFFIX,START_NO,LENGTH,CURRENT_NO,INCREMENT FROM FORM_RECORD WHERE ID=?"); setPrepareStatement(preStat, 1, id); rs = preStat.executeQuery(); if (rs.next()) { prefix = rs.getString(1); suffix = rs.getString(2); startID = new Long(rs.getLong(3)); length = new Integer(rs.getInt(4)); currID = new Long(rs.getLong(5)); increment = new Integer(rs.getInt(6)); if (Utility.isEmpty(startID) || Utility.isEmpty(length) || Utility.isEmpty(currID) || Utility.isEmpty(increment) || startID.intValue() < 0 || length.intValue() < startID.toString().length() || currID.intValue() < startID.intValue() || increment.intValue() < 1 || new Integer(increment.intValue() + currID.intValue()).toString().length() > length.intValue()) { noRecordMatch = true; } else { if (!Utility.isEmpty(prefix)) { formReferenceID = prefix; } String strCurrID = currID.toString(); for (int i = 0; i < length.intValue() - strCurrID.length(); i++) { formReferenceID += "0"; } formReferenceID += strCurrID; if (!Utility.isEmpty(suffix)) { formReferenceID += suffix; } } } else { noRecordMatch = true; } } catch (Exception e) { log.error(e, e); try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } throw new ApplicationException("errors.framework.get_next_seq", e); } finally { try { rs.close(); } catch (Exception ignore) { } finally { rs = null; } try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } } if (!noRecordMatch && formReferenceID != null) { try { int updateCnt = 0; nextID = currID.intValue() + increment.intValue(); do { preStat = dbConn.prepareStatement("UPDATE FORM_RECORD SET CURRENT_NO=? WHERE ID=?"); setPrepareStatement(preStat, 1, new Integer(nextID)); setPrepareStatement(preStat, 2, id); updateCnt = preStat.executeUpdate(); if (updateCnt == 0) { Thread.sleep(50); } } while (updateCnt == 0); dbConn.commit(); } catch (Exception e) { log.error(e, e); try { dbConn.rollback(); } catch (Exception ignore) { } throw new ApplicationException("errors.framework.get_next_seq", e); } finally { try { preStat.close(); } catch (Exception ignore) { } finally { preStat = null; } try { dbConn.close(); } catch (Exception ignore) { } finally { dbConn = null; } } } return formReferenceID; } } }
Code Sample 2:
@Override public void alterar(QuestaoMultiplaEscolha q) throws Exception { PreparedStatement stmt = null; String sql = "UPDATE questao SET id_disciplina=?, enunciado=?, grau_dificuldade=? WHERE id_questao=?"; try { stmt = conexao.prepareStatement(sql); stmt.setInt(1, q.getDisciplina().getIdDisciplina()); stmt.setString(2, q.getEnunciado()); stmt.setString(3, q.getDificuldade().name()); stmt.setInt(4, q.getIdQuestao()); stmt.executeUpdate(); conexao.commit(); alterarQuestaoMultiplaEscolha(q); } catch (SQLException e) { conexao.rollback(); throw e; } } |
11
| Code Sample 1:
private boolean saveDocumentXml(String repository, String tempRepo) { boolean result = true; try { XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "documents/document"; InputSource insource = new InputSource(new FileInputStream(tempRepo + File.separator + AppConstants.DMS_XML)); NodeList nodeList = (NodeList) xpath.evaluate(expression, insource, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); System.out.println(node.getNodeName()); DocumentModel document = new DocumentModel(); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node child = childs.item(j); if (child.getNodeType() == Node.ELEMENT_NODE) { if (child.getNodeName() != null && child.getFirstChild() != null && child.getFirstChild().getNodeValue() != null) { System.out.println(child.getNodeName() + "::" + child.getFirstChild().getNodeValue()); } if (Document.FLD_ID.equals(child.getNodeName())) { if (child.getFirstChild() != null) { String szId = child.getFirstChild().getNodeValue(); if (szId != null && szId.length() > 0) { try { document.setId(new Long(szId)); } catch (Exception e) { e.printStackTrace(); } } } } else if (document.FLD_NAME.equals(child.getNodeName())) { document.setName(child.getFirstChild().getNodeValue()); document.setTitle(document.getName()); document.setDescr(document.getName()); document.setExt(getExtension(document.getName())); } else if (document.FLD_LOCATION.equals(child.getNodeName())) { document.setLocation(child.getFirstChild().getNodeValue()); } else if (document.FLD_OWNER.equals(child.getNodeName())) { Long id = new Long(child.getFirstChild().getNodeValue()); User user = new UserModel(); user.setId(id); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setOwner(user); } } } } boolean isSave = docService.save(document); if (isSave) { String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File fileFolder = new File(sbRepo.append(sbFolder).toString()); if (!fileFolder.exists()) { fileFolder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(fileFolder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(tempRepo + File.separator + document.getName()).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); document.setSize(fcSource.size()); log.info("Batch upload file " + document.getName() + " into [" + document.getLocation() + "] as " + document.getName() + "." + document.getExt()); folder.setId(DEFAULT_FOLDER); folder = (Folder) folderService.find(folder); if (folder != null && folder.getId() != null) { document.setFolder(folder); } workspace.setId(DEFAULT_WORKSPACE); workspace = (Workspace) workspaceService.find(workspace); if (workspace != null && workspace.getId() != null) { document.setWorkspace(workspace); } user.setId(DEFAULT_USER); user = (User) userService.find(user); if (user != null && user.getId() != null) { document.setCrtby(user.getId()); } document.setCrtdate(new Date()); document = (DocumentModel) docService.resetDuplicateDocName(document); docService.save(document); DocumentIndexer.indexDocument(preference, document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } } } catch (Exception e) { result = false; e.printStackTrace(); } return result; }
Code Sample 2:
public void copy(File src, File dest) throws FileNotFoundException, IOException { FileInputStream srcStream = new FileInputStream(src); FileOutputStream destStream = new FileOutputStream(dest); FileChannel srcChannel = srcStream.getChannel(); FileChannel destChannel = destStream.getChannel(); srcChannel.transferTo(0, srcChannel.size(), destChannel); destChannel.close(); srcChannel.close(); destStream.close(); srcStream.close(); } |
00
| Code Sample 1:
public static String MD5ToString(String md5) { String hashword = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(md5.getBytes()); BigInteger hash = new BigInteger(1, md.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
Code Sample 2:
public static InputStream getUrlInputStream(final java.net.URL url) throws java.io.IOException, java.lang.InstantiationException { final java.net.URLConnection conn = url.openConnection(); conn.connect(); final InputStream input = url.openStream(); if (input == null) { throw new java.lang.InstantiationException("Url " + url + " does not provide data."); } return input; } |
00
| Code Sample 1:
public AddressType[] getAdressFromCRSCoordinate(Point3d crs_position) { AddressType[] result = null; String postRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" + "<xls:XLS xmlns:xls=\"http://www.opengis.net/xls\" xmlns:sch=\"http://www.ascc.net/xml/schematron\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/xls \n" + " http://gdi3d.giub.uni-bonn.de/lus/schemas/LocationUtilityService.xsd\" version=\"1.1\"> \n" + " <xls:RequestHeader srsName=\"EPSG:" + Navigator.getEpsg_code() + "\"/> \n" + " <xls:Request methodName=\"ReverseGeocodeRequest\" requestID=\"123456789\" version=\"1.1\"> \n" + " <xls:ReverseGeocodeRequest> \n" + " <xls:Position> \n" + " <gml:Point srsName=\"" + Navigator.getEpsg_code() + "\"> \n" + " <gml:pos>" + crs_position.x + " " + crs_position.y + "</gml:pos> \n" + " </gml:Point> \n" + " </xls:Position> \n" + " <xls:ReverseGeocodePreference>StreetAddress</xls:ReverseGeocodePreference> \n" + " </xls:ReverseGeocodeRequest> \n" + " </xls:Request> \n" + "</xls:XLS> \n"; try { if (Navigator.isVerbose()) { System.out.println("contacting " + serviceEndPoint + ":\n" + postRequest); } URL u = new URL(serviceEndPoint); HttpURLConnection urlc = (HttpURLConnection) u.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); urlc.setAllowUserInteraction(false); urlc.setRequestMethod("POST"); urlc.setRequestProperty("Content-Type", "application/xml"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); PrintWriter xmlOut = null; xmlOut = new java.io.PrintWriter(urlc.getOutputStream()); xmlOut.write(postRequest); xmlOut.flush(); xmlOut.close(); InputStream is = urlc.getInputStream(); XLSDocument xlsResponse = XLSDocument.Factory.parse(is); is.close(); XLSType xlsTypeResponse = xlsResponse.getXLS(); AbstractBodyType abBodyResponse[] = xlsTypeResponse.getBodyArray(); ResponseType response = (ResponseType) abBodyResponse[0].changeType(ResponseType.type); AbstractResponseParametersType respParam = response.getResponseParameters(); if (respParam == null) { return null; } ReverseGeocodeResponseType drResp = (ReverseGeocodeResponseType) respParam.changeType(ReverseGeocodeResponseType.type); net.opengis.xls.ReverseGeocodedLocationType[] types = drResp.getReverseGeocodedLocationArray(); int num = types.length; if (num > 2) { return null; } result = new AddressType[num]; for (int i = 0; i < num; i++) { String addressDescription = "<b>"; net.opengis.xls.ReverseGeocodedLocationType type = types[i]; result[i] = type.getAddress(); } } catch (java.net.ConnectException ce) { JOptionPane.showMessageDialog(null, "no connection to reverse geocoder", "Connection Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { e.printStackTrace(); } return result; }
Code Sample 2:
public void bubblesort(String filenames[]) { for (int i = filenames.length - 1; i > 0; i--) { for (int j = 0; j < i; j++) { String temp; if (filenames[j].compareTo(filenames[j + 1]) > 0) { temp = filenames[j]; filenames[j] = filenames[j + 1]; filenames[j + 1] = temp; } } } } |
11
| Code Sample 1:
public static final String encryptMD5(String decrypted) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(decrypted.getBytes()); byte hash[] = md5.digest(); md5.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
Code Sample 2:
public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); } |
11
| Code Sample 1:
public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); fs.close(); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
private void publishMap(LWMap map) throws IOException { File savedMap = PublishUtil.saveMap(map); InputStream istream = new BufferedInputStream(new FileInputStream(savedMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("ConceptMap", "vue"))); int fileLength = (int) savedMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); } |
11
| Code Sample 1:
private byte[] _generate() throws NoSuchAlgorithmException { if (host == null) { try { seed = InetAddress.getLocalHost().toString(); } catch (UnknownHostException e) { seed = "localhost/127.0.0.1"; } catch (SecurityException e) { seed = "localhost/127.0.0.1"; } host = seed; } else { seed = host; } seed = seed + new Date().toString(); seed = seed + Long.toString(rnd.nextLong()); md = MessageDigest.getInstance(algorithm); md.update(seed.getBytes()); return md.digest(); }
Code Sample 2:
public static String md5encrypt(String toEncrypt) { if (toEncrypt == null) { throw new IllegalArgumentException("null is not a valid password to encrypt"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toEncrypt.getBytes()); byte[] hash = md.digest(); return new String(dumpBytes(hash)); } catch (NoSuchAlgorithmException nsae) { return toEncrypt; } } |
00
| Code Sample 1:
private static String sendRPC(String xml) throws MalformedURLException, IOException { String str = ""; String strona = OSdbServer; String logowanie = xml; URL url = new URL(strona); URLConnection connection = url.openConnection(); connection.setRequestProperty("Connection", "Close"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(true); connection.getOutputStream().write(logowanie.getBytes("UTF-8")); Scanner in; in = new Scanner(connection.getInputStream()); while (in.hasNextLine()) { str += in.nextLine(); } ; return str; }
Code Sample 2:
private boolean goToForum() { URL url = null; URLConnection urlConn = null; int code = 0; boolean gotNumReplies = false; boolean gotMsgNum = false; try { url = new URL("http://" + m_host + "/forums/index.php?topic=" + m_gameId + ".new"); } catch (MalformedURLException e) { e.printStackTrace(); return false; } try { urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("GET"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(false); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); if (m_referer != null) urlConn.setRequestProperty("Referer", m_referer); if (m_cookies != null) urlConn.setRequestProperty("Cookie", m_cookies); m_referer = url.toString(); readCookies(urlConn); code = ((HttpURLConnection) urlConn).getResponseCode(); if (code != 200) { String msg = ((HttpURLConnection) urlConn).getResponseMessage(); m_turnSummaryRef = String.valueOf(code) + ": " + msg; return false; } BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line = ""; Pattern p_numReplies = Pattern.compile(".*?;num_replies=(\\d+)\".*"); Pattern p_msgNum = Pattern.compile(".*?<a name=\"msg(\\d+)\"></a><a name=\"new\"></a>.*"); Pattern p_attachId = Pattern.compile(".*?action=dlattach;topic=" + m_gameId + ".0;attach=(\\d+)\">.*"); while ((line = in.readLine()) != null) { if (!gotNumReplies) { Matcher match_numReplies = p_numReplies.matcher(line); if (match_numReplies.matches()) { m_numReplies = match_numReplies.group(1); gotNumReplies = true; continue; } } if (!gotMsgNum) { Matcher match_msgNum = p_msgNum.matcher(line); if (match_msgNum.matches()) { m_msgNum = match_msgNum.group(1); gotMsgNum = true; continue; } } Matcher match_attachId = p_attachId.matcher(line); if (match_attachId.matches()) m_attachId = match_attachId.group(1); } in.close(); } catch (Exception e) { e.printStackTrace(); return false; } if (!gotNumReplies || !gotMsgNum) { m_turnSummaryRef = "Error: "; if (!gotNumReplies) m_turnSummaryRef += "No num_replies found in A&A.org forum topic. "; if (!gotMsgNum) m_turnSummaryRef += "No msgXXXXXX found in A&A.org forum topic. "; return false; } return true; } |
11
| Code Sample 1:
public static String hash(String str) { MessageDigest summer; try { summer = MessageDigest.getInstance("md5"); summer.update(str.getBytes()); } catch (NoSuchAlgorithmException ex) { return null; } BigInteger hash = new BigInteger(1, summer.digest()); String hashword = hash.toString(16); return hashword; }
Code Sample 2:
@Override public String encode(String password) { String hash = null; MessageDigest m; try { m = MessageDigest.getInstance("MD5"); m.update(password.getBytes(), 0, password.length()); hash = String.format("%1$032X", new BigInteger(1, m.digest())); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hash; } |
00
| Code Sample 1:
private void publishPage(URL url, String path, File outputFile) throws IOException { if (debug) { System.out.println(" publishing page: " + path); System.out.println(" url == " + url); System.out.println(" file == " + outputFile); } StringBuffer sb = new StringBuffer(); try { InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); boolean firstLine = true; String line; do { line = br.readLine(); if (line != null) { if (!firstLine) sb.append("\n"); else firstLine = false; sb.append(line); } } while (line != null); br.close(); } catch (IOException e) { String mess = outputFile.toString() + ": " + e.getMessage(); errors.add(mess); } FileOutputStream fos = new FileOutputStream(outputFile); OutputStreamWriter sw = new OutputStreamWriter(fos); sw.write(sb.toString()); sw.close(); if (prepareArchive) archiveFiles.add(new ArchiveFile(path, outputFile)); }
Code Sample 2:
@Override public void processSource() { try { URL url = new URL(this.mensa.getJsonUrl(weekNumber)); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); StringBuilder agentBuilder = new StringBuilder(); agentBuilder.append(cxt.getString(R.string.app_name)).append(' ').append(cxt.getString(R.string.app_version)).append('|').append(Build.DISPLAY).append('|').append(VERSION.RELEASE).append('|').append(Build.ID).append('|').append(Build.MODEL).append('|').append(Locale.getDefault().getLanguage()).append('-').append(Locale.getDefault().getCountry()); connection.setRequestProperty("User-Agent", agentBuilder.toString()); InputStream inStream = connection.getInputStream(); String response = getStringFromInputStream(inStream); JSONObject weekplanJsonObj = new JSONObject(response); this.menues = parseWeekplan(weekplanJsonObj); this.valuability = WeekPlan.VALUABLE; } catch (IOException ex) { this.valuability = WeekPlan.NOCON; this.menues = null; } catch (JSONException ex) { this.valuability = WeekPlan.ERROR; this.menues = null; } } |
11
| Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
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) { } } } |
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 { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
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!"); } |
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 run() { try { Socket socket = getSocket(); System.out.println("opening socket to " + address + " on " + port); InputStream in = socket.getInputStream(); for (; ; ) { FileTransferHeader header = FileTransferHeader.readHeader(in); if (header == null) break; System.out.println("header: " + header); String[] parts = header.getFilename().getSegments(); String filename; if (parts.length > 0) filename = "dl-" + parts[parts.length - 1]; else filename = "dl-" + session.getScreenname(); System.out.println("writing to file " + filename); long sum = 0; if (new File(filename).exists()) { FileInputStream fis = new FileInputStream(filename); byte[] block = new byte[10]; for (int i = 0; i < block.length; ) { int count = fis.read(block); if (count == -1) break; i += count; } FileTransferChecksum summer = new FileTransferChecksum(); summer.update(block, 0, 10); sum = summer.getValue(); } FileChannel fileChannel = new FileOutputStream(filename).getChannel(); FileTransferHeader outHeader = new FileTransferHeader(header); outHeader.setHeaderType(FileTransferHeader.HEADERTYPE_ACK); outHeader.setIcbmMessageId(cookie); outHeader.setBytesReceived(0); outHeader.setReceivedChecksum(sum); OutputStream socketOut = socket.getOutputStream(); System.out.println("sending header: " + outHeader); outHeader.write(socketOut); for (int i = 0; i < header.getFileSize(); ) { long transferred = fileChannel.transferFrom(Channels.newChannel(in), 0, header.getFileSize() - i); System.out.println("transferred " + transferred); if (transferred == -1) return; i += transferred; } System.out.println("finished transfer!"); fileChannel.close(); FileTransferHeader doneHeader = new FileTransferHeader(header); doneHeader.setHeaderType(FileTransferHeader.HEADERTYPE_RECEIVED); doneHeader.setFlags(doneHeader.getFlags() | FileTransferHeader.FLAG_DONE); doneHeader.setBytesReceived(doneHeader.getBytesReceived() + 1); doneHeader.setIcbmMessageId(cookie); doneHeader.setFilesLeft(doneHeader.getFilesLeft() - 1); doneHeader.write(socketOut); if (doneHeader.getFilesLeft() - 1 <= 0) { socket.close(); break; } } } catch (IOException e) { e.printStackTrace(); return; } } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.