label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static void copyFile(File src, File dest, boolean force) throws IOException, InterruptedIOException { if (dest.exists()) { if (force) { dest.delete(); } else { throw new IOException("Cannot overwrite existing file!"); } } byte[] buffer = new byte[5 * 1024 * 1024]; int read = 0; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dest)); while (true) { read = in.read(buffer); if (read == -1) { break; } out.write(buffer, 0, read); } } finally { buffer = null; if (in != null) { try { in.close(); } finally { if (out != null) { out.close(); } } } } } Code Sample 2: public static void main(String args[]) { InputStream input = System.in; OutputStream output = System.out; if (args.length > 0) { try { input = new FileInputStream(args[0]); } catch (FileNotFoundException e) { System.err.println("Unable to open file: " + args[0]); System.exit(-1); } catch (IOException e) { System.err.println("Unable to access file: " + args[0]); System.exit(-1); } } if (args.length > 1) { try { output = new FileOutputStream(args[1]); } catch (FileNotFoundException e) { System.err.println("Unable to open file: " + args[1]); System.exit(-1); } catch (IOException e) { System.err.println("Unable to access file: " + args[1]); System.exit(-1); } } byte buffer[] = new byte[512]; int len; try { while ((len = input.read(buffer)) > 0) output.write(buffer, 0, len); } catch (IOException e) { System.err.println("Error copying file"); } finally { input.close(); output.close(); } }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("image/png"); OutputStream outStream; outStream = resp.getOutputStream(); InputStream is; String name = req.getParameter("name"); if (name == null) { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } else { ImageRecord imageRecord = imageBean.getFile(name); if (imageRecord != null) { is = new BufferedInputStream(new FileInputStream(imageRecord.getThumbnailFile())); } else { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } } IOUtils.copy(is, outStream); outStream.close(); outStream.flush(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: private void copy(String imgPath, String path) { try { File input = new File(imgPath); File output = new File(path, input.getName()); if (output.exists()) { if (!MessageDialog.openQuestion(getShell(), "Overwrite", "There is already an image file " + input.getName() + " under the package.\n Do you really want to overwrite it?")) return; } byte[] data = new byte[1024]; FileInputStream fis = new FileInputStream(imgPath); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output)); int length; while ((length = bis.read(data)) > 0) { bos.write(data, 0, length); bos.flush(); } bos.close(); fis.close(); IJavaProject ijp = VisualSwingPlugin.getCurrentProject(); if (ijp != null) { ijp.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); view.refresh(); view.expandAll(); } } catch (Exception e) { VisualSwingPlugin.getLogger().error(e); } } Code Sample 2: void serialize(ZipOutputStream out) throws IOException { if ("imsmanifest.xml".equals(getFullName())) return; out.putNextEntry(new ZipEntry(getFullName())); IOUtils.copy(getDataStream(), out); out.closeEntry(); }
11
Code Sample 1: protected void zipDirectory(File dir, File zipfile) throws IOException, IllegalArgumentException { if (!dir.isDirectory()) throw new IllegalArgumentException("Compress: not a directory: " + dir); String[] entries = dir.list(); byte[] buffer = new byte[4096]; int bytes_read; ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile)); for (int i = 0; i < entries.length; i++) { File f = new File(dir, entries[i]); if (f.isDirectory()) continue; FileInputStream in = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getPath()); out.putNextEntry(entry); while ((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); in.close(); } out.close(); } Code Sample 2: public static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } }
00
Code Sample 1: private static BundleInfo[] getBundleInfoArray(String location) throws IOException { URL url = new URL(location + BUNDLE_LIST_FILE); BufferedReader br = null; List<BundleInfo> list = new ArrayList<BundleInfo>(); try { br = new BufferedReader(new InputStreamReader(url.openStream())); while (true) { String line = br.readLine(); if (line == null) { break; } int pos1 = line.indexOf('='); if (pos1 < 0) { continue; } BundleInfo info = new BundleInfo(); info.bundleSymbolicName = line.substring(0, pos1); info.location = line.substring(pos1 + 1); list.add(info); } if (!setBundleInfoName(location + BUNDLE_NAME_LIST_FILE + "_" + Locale.getDefault().getLanguage(), list)) { setBundleInfoName(location + BUNDLE_NAME_LIST_FILE, list); } return list.toArray(BUNDLE_INFO_EMPTY_ARRAY); } finally { if (br != null) { br.close(); } } } Code Sample 2: public boolean add(String url) { try { HttpURLConnection request = (HttpURLConnection) new URL(url).openConnection(); request.setRequestMethod("POST"); request.setRequestProperty(GameRecord.GAME_IP_HEADER, String.valueOf(ip)); request.setRequestProperty(GameRecord.GAME_PORT_HEADER, String.valueOf(port)); request.setRequestProperty(GameRecord.GAME_MESSAGE_HEADER, message); request.setRequestProperty(GameRecord.GAME_LATITUDE_HEADER, df.format(lat)); request.setRequestProperty(GameRecord.GAME_LONGITUDE_HEADER, df.format(lon)); request.setRequestProperty("Content-Length", "0"); request.connect(); if (request.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected response: " + request.getResponseCode() + " " + request.getResponseMessage()); } return true; } catch (IOException e) { e.printStackTrace(); } return false; }
00
Code Sample 1: public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout, Map<String, String> headers) throws Throwable { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); if (username != null || password != null) { byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } con.setConnectTimeout(timeout); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); } Code Sample 2: @Transient public byte[] getData() { InputStream is = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { is = urlInstance.openStream(); byte[] bytes = new byte[1024 * 20]; while (is.available() > 0) { int bytesRead = is.read(bytes); bos.write(bytes, 0, bytesRead); } return bos.toByteArray(); } catch (Exception e) { log.error("Error reading URL: " + url, e); return null; } finally { if (is != null) try { is.close(); } catch (Exception e) { log.debug("Error closing URL input stream: " + url, e); } } }
11
Code Sample 1: private static void copyFile(File sourceFile, File destFile) throws IOException { System.out.println(sourceFile.getAbsolutePath()); System.out.println(destFile.getAbsolutePath()); FileChannel source = new FileInputStream(sourceFile).getChannel(); try { FileChannel destination = new FileOutputStream(destFile).getChannel(); try { destination.transferFrom(source, 0, source.size()); } finally { if (destination != null) { destination.close(); } } } finally { source.close(); } } Code Sample 2: @Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } }
00
Code Sample 1: public String quebraLink(String link) throws StringIndexOutOfBoundsException { link = link.replace(".url", ""); int cod = 0; final String linkInit = link.replace("#", ""); boolean estado = false; char letra; String linkOrig; String newlink = ""; linkOrig = link.replace("#", ""); linkOrig = linkOrig.replace(".url", ""); linkOrig = linkOrig.replace(".html", ""); linkOrig = linkOrig.replace("http://", ""); if (linkOrig.contains("clubedodownload")) { for (int i = 7; i < linkInit.length(); i++) { if (linkOrig.charAt(i) == '/') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (newlink.contains("//:ptth")) { newlink = inverteFrase(newlink); if (isValid(newlink)) { return newlink; } } else if (newlink.contains("http://")) { if (isValid(newlink)) { return newlink; } } } } } if (linkOrig.contains("protetordelink.tv")) { for (int i = linkOrig.length() - 1; i >= 0; i--) { letra = linkOrig.charAt(i); if (letra == '/') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } newlink = HexToChar(newlink); if (newlink.contains("ptth")) { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); newlink = inverteFrase(newlink); if (isValid(newlink)) { return newlink; } } else { newlink = inverteFrase(newlink); if (isValid(newlink)) { return newlink; } } } else { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } if (linkOrig.contains("baixeaquifilmes")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (newlink.contains(":ptth")) { newlink = inverteFrase(newlink); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } if (linkOrig.contains("downloadsgratis")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '!') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (precisaRepassar(QuebraLink.decode64(newlink))) { newlink = quebraLink(QuebraLink.decode64(newlink)); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } newlink = ""; if (linkOrig.contains("vinxp")) { System.out.println("é"); for (int i = 1; i < linkOrig.length(); i++) { if (linkOrig.charAt(i) == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } break; } } if (newlink.contains(".vinxp")) { newlink = newlink.replace(".vinxp", ""); } newlink = decodeCifraDeCesar(newlink); System.out.println(newlink); return newlink; } if (linkOrig.contains("?")) { String linkTemporary = ""; newlink = ""; if (linkOrig.contains("go!")) { linkOrig = linkOrig.replace("?go!", "?"); } if (linkOrig.contains("=")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } linkTemporary = QuebraLink.decode64(newlink); break; } } if (linkTemporary.contains("http")) { newlink = ""; for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (linkTemporary.contains("ptth")) { newlink = ""; linkTemporary = inverteFrase(linkTemporary); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } linkTemporary = ""; for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { linkTemporary += linkOrig.charAt(j); } link = QuebraLink.decode64(linkTemporary); break; } } if (link.contains("http")) { newlink = ""; for (int i = 0; i < link.length(); i++) { letra = link.charAt(i); if (letra == 'h') { for (int j = i; j < link.length(); j++) { newlink += link.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (link.contains("ptth")) { newlink = ""; linkTemporary = inverteFrase(link); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } linkOrig = linkInit; link = linkOrig; newlink = ""; } if (linkOrig.contains("?")) { String linkTemporary = ""; newlink = ""; if (linkOrig.contains("go!")) { linkOrig = linkOrig.replace("?go!", "?"); } if (linkOrig.contains("=")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } linkTemporary = linkTemporary.replace(".", ""); try { linkTemporary = HexToChar(newlink); } catch (Exception e) { System.err.println("erro hex 1º"); estado = true; } break; } } if (linkTemporary.contains("http") && !estado) { newlink = ""; for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (linkTemporary.contains("ptth") && !estado) { newlink = ""; linkTemporary = inverteFrase(linkTemporary); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } estado = false; linkTemporary = ""; for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { linkTemporary += linkOrig.charAt(j); } linkTemporary = linkTemporary.replace(".", ""); try { link = HexToChar(linkTemporary); } catch (Exception e) { System.err.println("erro hex 2º"); estado = true; } break; } } if (link.contains("http") && !estado) { newlink = ""; for (int i = 0; i < link.length(); i++) { letra = link.charAt(i); if (letra == 'h') { for (int j = i; j < link.length(); j++) { newlink += link.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } if (link.contains("ptth") && !estado) { newlink = ""; linkTemporary = inverteFrase(link); for (int i = 0; i < linkTemporary.length(); i++) { letra = linkTemporary.charAt(i); if (letra == 'h') { for (int j = i; j < linkTemporary.length(); j++) { newlink += linkTemporary.charAt(j); } newlink = newlink.replace("!og", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } linkOrig = linkInit; link = linkOrig; newlink = ""; } if (linkOrig.contains("?") && !linkOrig.contains("id=") && !linkOrig.contains("url=") && !linkOrig.contains("link=") && !linkOrig.contains("r=http") && !linkOrig.contains("r=ftp")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '?') { newlink = ""; for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } if (newlink.contains("ptth")) { newlink = inverteFrase(newlink); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } } } if ((link.contains("url=")) || (link.contains("link=")) || (link.contains("?r=http")) || (link.contains("?r=ftp"))) { if (!link.contains("//:ptth")) { for (int i = 0; i < link.length(); i++) { letra = link.charAt(i); if (letra == '=') { for (int j = i + 1; j < link.length(); j++) { letra = link.charAt(j); newlink += letra; } break; } } if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } if (linkOrig.contains("//:ptth") || linkOrig.contains("//:sptth")) { if (linkOrig.contains("=")) { for (int i = 0; i < linkOrig.length(); i++) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = linkOrig.length() - 1; j > i; j--) { letra = linkOrig.charAt(j); newlink += letra; } break; } } if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } newlink = inverteFrase(linkOrig); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } if (linkOrig.contains("?go!")) { linkOrig = linkOrig.replace("?go!", "?down!"); newlink = linkOrig; if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } if (linkOrig.contains("down!")) { linkOrig = linkOrig.replace("down!", ""); return quebraLink(linkOrig); } newlink = ""; for (int i = linkOrig.length() - 4; i >= 0; i--) { letra = linkOrig.charAt(i); if (letra == '=') { for (int j = i + 1; j < linkOrig.length(); j++) { newlink += linkOrig.charAt(j); } break; } } String ltmp = ""; try { ltmp = HexToChar(newlink); } catch (Exception e) { System.err.println("erro hex 3º"); } if (ltmp.contains("http://")) { if (precisaRepassar(ltmp)) { ltmp = quebraLink(ltmp); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else if (ltmp.contains("//:ptth")) { ltmp = inverteFrase(ltmp); if (precisaRepassar(ltmp)) { ltmp = quebraLink(ltmp); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else { ltmp = newlink; } ltmp = decode64(newlink); if (ltmp.contains("http://")) { if (precisaRepassar(ltmp)) { ltmp = quebraLink(newlink); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else if (ltmp.contains("//:ptth")) { ltmp = inverteFrase(ltmp); if (precisaRepassar(ltmp)) { newlink = quebraLink(newlink); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else { ltmp = newlink; } try { ltmp = decodeAscii(newlink); } catch (NumberFormatException e) { System.err.println("erro ascii"); } if (ltmp.contains("http://")) { if (precisaRepassar(ltmp)) { ltmp = quebraLink(newlink); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else if (ltmp.contains("//:ptth")) { ltmp = inverteFrase(ltmp); if (precisaRepassar(ltmp)) { ltmp = quebraLink(ltmp); if (isValid(ltmp)) { newlink = ltmp; return newlink; } } else { if (isValid(ltmp)) { newlink = ltmp; return newlink; } } } else { ltmp = null; } newlink = ""; int cont = 0; letra = '\0'; ltmp = ""; newlink = ""; for (int i = linkOrig.length() - 4; i >= 0; i--) { letra = linkOrig.charAt(i); if (letra == '=' || letra == '?') { for (int j = i + 1; j < linkOrig.length(); j++) { if (linkOrig.charAt(j) == '.') { break; } newlink += linkOrig.charAt(j); } break; } } ltmp = newlink; String tmp = ""; String tmp2 = ""; do { try { tmp = HexToChar(ltmp); tmp2 = HexToChar(inverteFrase(ltmp)); if (!tmp.isEmpty() && tmp.length() > 5 && !tmp.contains("") && !tmp.contains("§") && !tmp.contains("�") && !tmp.contains("")) { ltmp = HexToChar(ltmp); } else if (!inverteFrase(tmp2).isEmpty() && inverteFrase(tmp2).length() > 5 && !inverteFrase(tmp2).contains("”") && !inverteFrase(tmp2).contains("§") && !inverteFrase(tmp2).contains("�")) { ltmp = HexToChar(inverteFrase(ltmp)); } } catch (NumberFormatException e) { } tmp = decode64(ltmp); tmp2 = decode64(inverteFrase(ltmp)); if (!tmp.contains("�") && !tmp.contains("ޚ")) { ltmp = decode64(ltmp); } else if (!tmp2.contains("�") && !tmp2.contains("ޚ")) { ltmp = decode64(inverteFrase(ltmp)); } try { tmp = decodeAscii(ltmp); tmp2 = decodeAscii(inverteFrase(ltmp)); if (!tmp.contains("Œ") && !tmp.contains("�") && !tmp.contains("§") && !tmp.contains("½") && !tmp.contains("*") && !tmp.contains("\"") && !tmp.contains("^")) { ltmp = decodeAscii(ltmp); } else if (!tmp2.contains("Œ") && !tmp2.contains("�") && !tmp2.contains("§") && !tmp2.contains("½") && !tmp2.contains("*") && !tmp2.contains("\"") && !tmp2.contains("^")) { ltmp = decodeAscii(inverteFrase(ltmp)); } } catch (NumberFormatException e) { } cont++; if (ltmp.contains("http")) { newlink = ltmp; if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else if (ltmp.contains("ptth")) { newlink = inverteFrase(ltmp); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } } while (!isValid(newlink) && cont <= 20); tmp = null; tmp2 = null; ltmp = null; String leitura = ""; try { leitura = readHTML(linkInit); } catch (IOException e) { } leitura = leitura.toLowerCase(); if (leitura.contains("trocabotao")) { newlink = ""; for (int i = leitura.indexOf("trocabotao"); i < leitura.length(); i++) { if (Character.isDigit(leitura.charAt(i))) { int tmpInt = i; while (Character.isDigit(leitura.charAt(tmpInt))) { newlink += leitura.charAt(tmpInt); tmpInt++; } cod = Integer.parseInt(newlink); break; } } if (cod != 0) { for (int i = 7; i < linkInit.length(); i++) { letra = linkInit.charAt(i); if (letra == '/') { newlink = linkInit.substring(0, i + 1) + "linkdiscover.php?cod=" + cod; break; } } DataInputStream dat = null; try { URL url = new URL(newlink); InputStream in = url.openStream(); dat = new DataInputStream(new BufferedInputStream(in)); leitura = ""; int dado; while ((dado = dat.read()) != -1) { letra = (char) dado; leitura += letra; } newlink = leitura.replaceAll(" ", ""); if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } catch (MalformedURLException ex) { System.out.println("URL mal formada."); } catch (IOException e) { } finally { try { if (dat != null) { dat.close(); } } catch (IOException e) { System.err.println("Falha ao fechar fluxo."); } } } } if (precisaRepassar(linkInit)) { if (linkInit.substring(8).contains("http")) { newlink = linkInit.substring(linkInit.indexOf("http", 8), linkInit.length()); if (isValid(newlink)) { return newlink; } } } newlink = ""; StringBuffer strBuf = null; try { strBuf = new StringBuffer(readHTML(linkInit)); for (String tmp3 : getLibrary()) { if (strBuf.toString().toLowerCase().contains(tmp3)) { for (int i = strBuf.toString().indexOf(tmp3); i >= 0; i--) { if (strBuf.toString().charAt(i) == '"') { for (int j = i + 1; j < strBuf.length(); j++) { if (strBuf.toString().charAt(j) == '"') { if (precisaRepassar(newlink)) { newlink = quebraLink(newlink); if (isValid(newlink)) { return newlink; } } else { if (isValid(newlink)) { return newlink; } } } else { newlink += strBuf.toString().charAt(j); } } } } } } } catch (IOException ex) { } GUIQuebraLink.isBroken = false; return "Desculpe o link não pode ser quebrado."; } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static void main(String arg[]) { try { String readFile = arg[0]; String writeFile = arg[1]; java.io.FileInputStream ss = new java.io.FileInputStream(readFile); ManagedMemoryDataSource ms = new ManagedMemoryDataSource(ss, 1024 * 1024, "foo/data", true); javax.activation.DataHandler dh = new javax.activation.DataHandler(ms); java.io.InputStream is = dh.getInputStream(); java.io.FileOutputStream fo = new java.io.FileOutputStream(writeFile); byte[] buf = new byte[512]; int read = 0; do { read = is.read(buf); if (read > 0) { fo.write(buf, 0, read); } } while (read > -1); fo.close(); is.close(); } catch (java.lang.Exception e) { log.error(Messages.getMessage("exception00"), e); } } Code Sample 2: public static void copyFile(File from, File to) throws FileNotFoundException, IOException { requireFile(from); requireFile(to); if (to.isDirectory()) { to = new File(to, getFileName(from)); } FileChannel sourceChannel = new FileInputStream(from).getChannel(); FileChannel destinationChannel = new FileOutputStream(to).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
11
Code Sample 1: private void chooseGame(DefaultHttpClient httpclient) throws IOException, ClientProtocolException { HttpGet httpget = new HttpGet(Constants.STRATEGICDOMINATION_URL + "/gameboard.cgi?gameid=" + 1687); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("cg form get: " + response.getStatusLine()); if (entity != null) { InputStream inStream = entity.getContent(); IOUtils.copy(inStream, System.out); } System.out.println("cg set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } Code Sample 2: public void createNewFile(String filePath, InputStream in) throws IOException { FileOutputStream out = null; try { File file = newFileRef(filePath); FileHelper.createNewFile(file, true); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
00
Code Sample 1: public static void main(String[] args) { int dizi[] = { 23, 78, 45, 8, 3, 32, 56, 39, 92, 28 }; boolean test = false; int kars = 0; int tas = 0; while (true) { for (int j = 0; j < dizi.length - 1; j++) { kars++; if (dizi[j] > dizi[j + 1]) { int temp = dizi[j]; dizi[j] = dizi[j + 1]; dizi[j + 1] = temp; test = true; tas++; } } if (!test) { break; } else { test = false; } } for (int i = 0; i < dizi.length; i++) { System.out.print(dizi[i] + " "); } for (int i = 0; i < 5; i++) { System.out.println("i" + i); } } Code Sample 2: public static void concatenateOutput(File[] inputFiles, File outputFile) { int numberOfInputFiles = inputFiles.length; byte lf = (byte) '\n'; try { FileOutputStream fos = new FileOutputStream(outputFile); FileChannel outfc = fos.getChannel(); System.out.println("Processing " + inputFiles[0].getPath()); FileInputStream fis = new FileInputStream(inputFiles[0]); FileChannel infc = fis.getChannel(); int bufferCapacity = 100000; ByteBuffer bb = ByteBuffer.allocate(bufferCapacity); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); for (int f = 1; f < numberOfInputFiles; f++) { System.out.println("Processing " + inputFiles[f].getPath()); fis = new FileInputStream(inputFiles[f]); infc = fis.getChannel(); bb.clear(); int bytesread = infc.read(bb); bb.flip(); byte b = bb.get(); while (b != lf) { b = bb.get(); } outfc.write(bb); bb.clear(); while (infc.read(bb) > 0) { bb.flip(); outfc.write(bb); bb.clear(); } infc.close(); } outfc.close(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } }
11
Code Sample 1: protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; } Code Sample 2: public boolean validateLogin(String username, String password) { boolean user_exists = false; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); String password_hash = hash.toString(16); statement = connect.prepareStatement("SELECT id from toepen.users WHERE username = ? AND password = ?"); statement.setString(1, username); statement.setString(2, password_hash); resultSet = statement.executeQuery(); while (resultSet.next()) { user_exists = true; } } catch (Exception ex) { System.out.println(ex); } finally { close(); return user_exists; } }
00
Code Sample 1: public boolean crear() { int result = 0; String sql = "insert into torneo" + "(nombreTorneo, ciudad, fechaInicio, fechaFinal, organizador, numeroDivisiones, terminado)" + "values (?, ?, ?, ?, ?, ?, ?)"; try { connection = conexionBD.getConnection(); connection.setAutoCommit(false); ps = connection.prepareStatement(sql); populatePreparedStatement(eltorneo); result = 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 (result > 0); } Code Sample 2: public static JSONObject fromUrl(String url) throws Throwable { Validate.notEmpty(url); InputStream stream = null; HttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(httpget); if (response != null) { HttpEntity entity = response.getEntity(); if (entity != null) { try { stream = entity.getContent(); return fromStream(stream); } finally { try { if (stream != null) stream.close(); } catch (Exception ex) { } } } } } catch (Throwable tr) { Logger.e(TAG, "fromUrl", tr); throw tr; } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } return null; }
00
Code Sample 1: private Document getDocument(URL url) throws SAXException, IOException { InputStream is; try { is = url.openStream(); } catch (IOException io) { System.out.println("parameter error : The specified reading data is mistaken."); System.out.println(" Request URL is " + sourceUri); throw new IOException("\t" + io.toString()); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException pce) { System.out.println("error : The error of DocumentBuilder instance generation"); throw new RuntimeException(pce.toString()); } Document doc; try { doc = builder.parse(is); } catch (Exception e) { System.out.println("error : parse of reading data went wrong."); System.out.println(" Request URL is " + sourceUri); throw new RuntimeException(e.toString()); } return doc; } Code Sample 2: public void showGetStartedBox() { String message = new String("Error: Resource Not Found."); java.net.URL url = ClassLoader.getSystemResource("docs/get_started.html"); if (url != null) { try { StringBuffer buf = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); while (reader.ready()) { buf.append(reader.readLine()); } message = buf.toString(); } catch (IOException ex) { message = new String("IO Error."); } } new HtmlDisplayDialog(this, "Get Started", message); }
00
Code Sample 1: private void enumeratePathArchive(final String archive) throws IOException { final boolean trace1 = m_trace1; final File fullArchive = new File(m_currentPathDir, archive); JarInputStream in = null; try { in = new JarInputStream(new BufferedInputStream(new FileInputStream(fullArchive), 32 * 1024)); final IPathHandler handler = m_handler; Manifest manifest = in.getManifest(); if (manifest == null) manifest = readManifestViaJarFile(fullArchive); handler.handleArchiveStart(m_currentPathDir, new File(archive), manifest); for (ZipEntry entry; (entry = in.getNextEntry()) != null; ) { if (trace1) m_log.trace1("enumeratePathArchive", "processing archive entry [" + entry.getName() + "] ..."); handler.handleArchiveEntry(in, entry); in.closeEntry(); } if (m_processManifest) { if (manifest == null) manifest = in.getManifest(); if (manifest != null) { final Attributes attributes = manifest.getMainAttributes(); if (attributes != null) { final String jarClassPath = attributes.getValue(Attributes.Name.CLASS_PATH); if (jarClassPath != null) { final StringTokenizer tokenizer = new StringTokenizer(jarClassPath); for (int p = 1; tokenizer.hasMoreTokens(); ) { final String relPath = tokenizer.nextToken(); final File archiveParent = fullArchive.getParentFile(); final File path = archiveParent != null ? new File(archiveParent, relPath) : new File(relPath); final String fullPath = m_canonical ? Files.canonicalizePathname(path.getPath()) : path.getPath(); if (m_pathSet.add(fullPath)) { if (m_verbose) m_log.verbose(" added manifest Class-Path entry [" + path + "]"); m_path.add(m_pathIndex + (p++), path); } } } } } } } catch (FileNotFoundException fnfe) { if ($assert.ENABLED) throw fnfe; } finally { if (in != null) try { in.close(); } catch (Exception ignore) { } } } Code Sample 2: private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); }
00
Code Sample 1: private void gzip(FileHolder fileHolder) { byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; if (fileHolder.selectedFileList.size() == 0) { return; } File destFile = new File(fileHolder.destFiles[0]); try { OutputStream outStream = new FileOutputStream(destFile); outStream = new GZIPOutputStream(outStream); File selectedFile = fileHolder.selectedFileList.get(0); super.currentObjBeingProcessed = selectedFile; this.inStream = new FileInputStream(selectedFile); while ((bytes_read = this.inStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytes_read); } outStream.close(); this.inStream.close(); } catch (IOException e) { errEntry.setThrowable(e); errEntry.setAppContext("gzip()"); errEntry.setAppMessage("Error gzip'ing: " + destFile); logger.logError(errEntry); } } Code Sample 2: public static void main(String[] args) throws MalformedURLException, IOException { URL url = new URL("https://imo.im/"); URLConnection con = url.openConnection(); InputStream is = con.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while (((len = is.read(buffer)) >= 0)) { out.write(buffer, 0, len); } out.flush(); System.out.println(out.toString()); }
11
Code Sample 1: private void show(String fileName, HttpServletResponse response) throws IOException { TelnetInputStream ftpIn = ftpClient_sun.get(fileName); OutputStream out = null; try { out = response.getOutputStream(); IOUtils.copy(ftpIn, out); } finally { if (ftpIn != null) { ftpIn.close(); } } } Code Sample 2: public static FileChannel newFileChannel(File file, String rw, boolean enableException) throws IOException { if (file == null) return null; if (rw == null || rw.length() == 0) { return null; } rw = rw.toLowerCase(); if (rw.equals(MODE_READ)) { if (FileUtil.exists(file, enableException)) { FileInputStream fis = new FileInputStream(file); FileChannel ch = fis.getChannel(); setObjectMap(ch.hashCode(), fis, FIS); return ch; } } else if (rw.equals(MODE_WRITE)) { FileOutputStream fos = new FileOutputStream(file); FileChannel ch = fos.getChannel(); setObjectMap(ch.hashCode(), fos, FOS_W); return ch; } else if (rw.equals(MODE_APPEND)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel ch = raf.getChannel(); ch.position(ch.size()); setObjectMap(ch.hashCode(), raf, FOS_A); return ch; } } else if (rw.equals(MODE_READ_WRITE)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, rw); FileChannel ch = raf.getChannel(); setObjectMap(ch.hashCode(), raf, RAF); return ch; } } else { throw new IllegalArgumentException("Illegal read/write type : [" + rw + "]\n" + "You can use following types for: \n" + " (1) Read Only = \"r\"\n" + " (2) Write Only = \"w\"\n" + " (3) Read/Write = \"rw\"\n" + " (4) Append = \"a\""); } return null; }
11
Code Sample 1: public static void makeLPKFile(String[] srcFilePath, String makeFilePath, LPKHeader header) { FileOutputStream os = null; DataOutputStream dos = null; try { LPKTable[] fileTable = new LPKTable[srcFilePath.length]; long fileOffset = outputOffset(header); for (int i = 0; i < srcFilePath.length; i++) { String sourceFileName = FileUtils.getFileName(srcFilePath[i]); long sourceFileSize = FileUtils.getFileSize(srcFilePath[i]); LPKTable ft = makeLPKTable(sourceFileName, sourceFileSize, fileOffset); fileOffset = outputNextOffset(sourceFileSize, fileOffset); fileTable[i] = ft; } File file = new File(makeFilePath); if (!file.exists()) { FileUtils.makedirs(file); } os = new FileOutputStream(file); dos = new DataOutputStream(os); dos.writeInt(header.getPAKIdentity()); writeByteArray(header.getPassword(), dos); dos.writeFloat(header.getVersion()); dos.writeLong(header.getTables()); for (int i = 0; i < fileTable.length; i++) { writeByteArray(fileTable[i].getFileName(), dos); dos.writeLong(fileTable[i].getFileSize()); dos.writeLong(fileTable[i].getOffSet()); } for (int i = 0; i < fileTable.length; i++) { File ftFile = new File(srcFilePath[i]); FileInputStream ftFis = new FileInputStream(ftFile); DataInputStream ftDis = new DataInputStream(ftFis); byte[] buff = new byte[256]; int readLength = 0; while ((readLength = ftDis.read(buff)) != -1) { makeBuffer(buff, readLength); dos.write(buff, 0, readLength); } ftDis.close(); ftFis.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (dos != null) { try { dos.close(); dos = null; } catch (IOException e) { } } } } Code Sample 2: public static void main(String[] a) throws Exception { HashMap<String, Integer> numberOfOccurencesOfThisComboe = new HashMap<String, Integer>(); HashMap<String, String> fileToCATHMapping = new HashMap<String, String>(); ArrayList<String> allFilesToBeCopied = new ArrayList<String>(); new File(outputDir).mkdirs(); FileReader fis = new FileReader(completeFileWithDirToCathFileList); BufferedReader bis = new BufferedReader(fis); String line = ""; String currentCombo = ""; while ((line = bis.readLine()) != null) { String[] allEntries = line.split("\\s+"); String fileName = allEntries[0]; String thisCombo = allEntries[1] + allEntries[2] + allEntries[3] + allEntries[4]; String reducedComboForFilteringOut = allEntries[1] + allEntries[2] + allEntries[3]; fileToCATHMapping.put(fileName, reducedComboForFilteringOut); if (currentCombo.equals(thisCombo)) { } else { System.out.println("merke: " + fileName); allFilesToBeCopied.add(fileName); currentCombo = thisCombo; } } for (String fileName : allFilesToBeCopied) { String reducedComboForFilteringOut = fileToCATHMapping.get(fileName); if (!numberOfOccurencesOfThisComboe.containsKey(reducedComboForFilteringOut)) { numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, 1); } else { Integer thisCounter = numberOfOccurencesOfThisComboe.get(reducedComboForFilteringOut); thisCounter = thisCounter + 1; numberOfOccurencesOfThisComboe.put(reducedComboForFilteringOut, thisCounter); } } HashSet<String> isSingleElement = new HashSet<String>(); for (Entry<String, Integer> thisEntry : numberOfOccurencesOfThisComboe.entrySet()) { if (thisEntry.getValue() == 1) { System.out.println("single: " + thisEntry.getKey()); isSingleElement.add(thisEntry.getKey()); } else { System.out.println("not single: " + thisEntry.getKey()); } } System.out.println(allFilesToBeCopied.size()); for (String file : allFilesToBeCopied) { if (!isSingleElement.contains(fileToCATHMapping.get(file))) { try { FileChannel srcChannel = new FileInputStream(CathDir + file).getChannel(); FileChannel dstChannel = new FileOutputStream(outputDir + file).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } }
00
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentType = req.getParameter("type"); String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing File Arg"); return; } File f = new File(arg); if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } if (contentType != null) { resp.setContentType(contentType); } log.debug("Requested File: " + f + " as type: " + contentType); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } } Code Sample 2: public void reset(int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? "); psta.setInt(1, currentPilot); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } }
11
Code Sample 1: public static void generate(final InputStream input, String format, Point dimension, IPath outputLocation) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = outputLocation.toFile(); ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); return; } } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); } Code Sample 2: public String doAdd(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadFileForm vo = (UploadFileForm) form; FormFile file = vo.getFile(); String inforId = request.getParameter("inforId"); System.out.println("inforId=" + inforId); if (file != null) { String realpath = getServlet().getServletContext().getRealPath("/"); realpath = realpath.replaceAll("\\\\", "/"); String rootFilePath = getServlet().getServletContext().getRealPath(request.getContextPath()); rootFilePath = (new StringBuilder(String.valueOf(rootFilePath))).append(UploadFileOne.strPath).toString(); String strAppend = (new StringBuilder(String.valueOf(UUIDGenerator.nextHex()))).append(UploadFileOne.getFileType(file)).toString(); if (file.getFileSize() != 0) { file.getInputStream(); String name = file.getFileName(); String fullPath = realpath + "attach/" + strAppend + name; t_attach attach = new t_attach(); attach.setAttach_fullname(fullPath); attach.setAttach_name(name); attach.setInfor_id(Integer.parseInt(inforId)); attach.setInsert_day(new Date()); attach.setUpdate_day(new Date()); t_attach_EditMap attachEdit = new t_attach_EditMap(); attachEdit.add(attach); File sysfile = new File(fullPath); if (!sysfile.exists()) { sysfile.createNewFile(); } java.io.OutputStream out = new FileOutputStream(sysfile); org.apache.commons.io.IOUtils.copy(file.getInputStream(), out); out.close(); System.out.println("file name is :" + name); } } request.setAttribute("operating-status", "�����ɹ�! ��ӭ����ʹ�á�"); System.out.println("in the end...."); return "aftersave"; }
11
Code Sample 1: private String hashString(String key) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(key.getBytes()); byte[] hash = digest.digest(); BigInteger bi = new BigInteger(1, hash); return String.format("%0" + (hash.length << 1) + "X", bi) + KERNEL_VERSION; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return "" + key.hashCode(); } } Code Sample 2: public String encryptLdapPassword(String algorithm) { String sEncrypted = _password; if ((_password != null) && (_password.length() > 0)) { algorithm = Val.chkStr(algorithm); boolean bMD5 = algorithm.equalsIgnoreCase("MD5"); boolean bSHA = algorithm.equalsIgnoreCase("SHA") || algorithm.equalsIgnoreCase("SHA1") || algorithm.equalsIgnoreCase("SHA-1"); if (bSHA || bMD5) { String sAlgorithm = "MD5"; if (bSHA) { sAlgorithm = "SHA"; } try { MessageDigest md = MessageDigest.getInstance(sAlgorithm); md.update(getPassword().getBytes("UTF-8")); sEncrypted = "{" + sAlgorithm + "}" + (new BASE64Encoder()).encode(md.digest()); } catch (NoSuchAlgorithmException e) { sEncrypted = null; e.printStackTrace(System.err); } catch (UnsupportedEncodingException e) { sEncrypted = null; e.printStackTrace(System.err); } } } return sEncrypted; }
00
Code Sample 1: public DownloadThread call() throws UpdateModException { try { Thread.currentThread().setName("Download - " + modName); if (url != null) { URL urls = new URL(this.url); URLConnection connection = urls.openConnection(); connection.setConnectTimeout(7500); InputStream is = urls.openStream(); String filename = null; if (path == null || path.isEmpty()) { String pattern = "[^a-z,A-Z,0-9, ,.]"; filename = this.url.substring(this.url.lastIndexOf("/") + 1).replace("%20", " "); filename = filename.replaceAll(pattern, ""); } else { filename = path; } FileOutputStream fos = null; file = new File(System.getProperty("java.io.tmpdir") + File.separator + filename); fos = new FileOutputStream(file, false); FileUtils.copyInputStream(is, fos); is.close(); fos.flush(); fos.close(); } } catch (MalformedURLException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (ConnectException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (NullPointerException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (InvalidParameterException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (FileNotFoundException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } catch (IOException ex) { System.out.println(ex); file = null; throw new UpdateModException(null, ex); } return this; } Code Sample 2: public static boolean copyFile(File outFile, File inFile) { InputStream inStream = null; OutputStream outStream = null; try { if (outFile.createNewFile()) { inStream = new FileInputStream(inFile); outStream = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0) outStream.write(buffer, 0, length); inStream.close(); outStream.close(); } else return false; } catch (IOException iox) { iox.printStackTrace(); return false; } return true; }
00
Code Sample 1: public void ztest_cluster() throws Exception { Configuration.init(); TomcatServer ts1 = new TomcatServer(); ts1.registerServlet("/*", TestServlet.class.getName()); ts1.registerCluster(5554); ts1.start(5555); TomcatServer ts2 = new TomcatServer(); ts2.registerServlet("/*", TestServlet.class.getName()); ts2.registerCluster(5554); ts2.start(5556); URL url1 = new URL("http://127.0.0.1:5555/a"); HttpURLConnection c1 = (HttpURLConnection) url1.openConnection(); assert getData(c1).equals("a null"); String cookie = c1.getHeaderField("Set-Cookie"); Thread.sleep(5000); URL url2 = new URL("http://127.0.0.1:5556/a"); HttpURLConnection c2 = (HttpURLConnection) url2.openConnection(); c2.setRequestProperty("Cookie", cookie); assert getData(c2).equals("a a"); } Code Sample 2: private synchronized void createFTPConnection() throws FTPBrowseException { ftpClient = new FTPClient(); try { InetAddress inetAddress = InetAddress.getByName(url.getHost()); if (url.getPort() == -1) { ftpClient.connect(inetAddress); } else { ftpClient.connect(inetAddress, url.getPort()); } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new FTPBrowseException(ftpClient.getReplyString()); } if (null != passwordAuthentication) { ftpClient.login(passwordAuthentication.getUserName(), new StringBuffer().append(passwordAuthentication.getPassword()).toString()); } if (url.getPath().length() > 0) { ftpClient.changeWorkingDirectory(url.getPath()); } homeDirectory = ftpClient.printWorkingDirectory(); } catch (UnknownHostException e) { throw new FTPBrowseException(e.getMessage()); } catch (SocketException e) { throw new FTPBrowseException(e.getMessage()); } catch (FTPBrowseException e) { throw e; } catch (IOException e) { throw new FTPBrowseException(e.getMessage()); } }
00
Code Sample 1: public BufferedImage extract() throws DjatokaException { boolean useRegion = false; int left = 0; int top = 0; int width = 50; int height = 50; boolean useleftDouble = false; Double leftDouble = 0.0; boolean usetopDouble = false; Double topDouble = 0.0; boolean usewidthDouble = false; Double widthDouble = 0.0; boolean useheightDouble = false; Double heightDouble = 0.0; if (params.getRegion() != null) { StringTokenizer st = new StringTokenizer(params.getRegion(), "{},"); String token; if ((token = st.nextToken()).contains(".")) { topDouble = Double.parseDouble(token); usetopDouble = true; } else top = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { leftDouble = Double.parseDouble(token); useleftDouble = true; } else left = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { heightDouble = Double.parseDouble(token); useheightDouble = true; } else height = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { widthDouble = Double.parseDouble(token); usewidthDouble = true; } else width = Integer.parseInt(token); useRegion = true; } try { if (is != null) { File f = File.createTempFile("tmp", ".jp2"); f.deleteOnExit(); FileOutputStream fos = new FileOutputStream(f); sourceFile = f.getAbsolutePath(); IOUtils.copyStream(is, fos); is.close(); fos.close(); } } catch (IOException e) { throw new DjatokaException(e); } try { Jp2_source inputSource = new Jp2_source(); Kdu_compressed_source input = null; Jp2_family_src jp2_family_in = new Jp2_family_src(); Jp2_locator loc = new Jp2_locator(); jp2_family_in.Open(sourceFile, true); inputSource.Open(jp2_family_in, loc); inputSource.Read_header(); input = inputSource; Kdu_codestream codestream = new Kdu_codestream(); codestream.Create(input); Kdu_channel_mapping channels = new Kdu_channel_mapping(); if (inputSource.Exists()) channels.Configure(inputSource, false); else channels.Configure(codestream); int ref_component = channels.Get_source_component(0); Kdu_coords ref_expansion = getReferenceExpansion(ref_component, channels, codestream); Kdu_dims image_dims = new Kdu_dims(); codestream.Get_dims(ref_component, image_dims); Kdu_coords imageSize = image_dims.Access_size(); Kdu_coords imagePosition = image_dims.Access_pos(); if (useleftDouble) left = imagePosition.Get_x() + (int) Math.round(leftDouble * imageSize.Get_x()); if (usetopDouble) top = imagePosition.Get_y() + (int) Math.round(topDouble * imageSize.Get_y()); if (useheightDouble) height = (int) Math.round(heightDouble * imageSize.Get_y()); if (usewidthDouble) width = (int) Math.round(widthDouble * imageSize.Get_x()); if (useRegion) { imageSize.Set_x(width); imageSize.Set_y(height); imagePosition.Set_x(left); imagePosition.Set_y(top); } int reduce = 1 << params.getLevelReductionFactor(); imageSize.Set_x(imageSize.Get_x() * ref_expansion.Get_x()); imageSize.Set_y(imageSize.Get_y() * ref_expansion.Get_y()); imagePosition.Set_x(imagePosition.Get_x() * ref_expansion.Get_x() / reduce - ((ref_expansion.Get_x() / reduce - 1) / 2)); imagePosition.Set_y(imagePosition.Get_y() * ref_expansion.Get_y() / reduce - ((ref_expansion.Get_y() / reduce - 1) / 2)); Kdu_dims view_dims = new Kdu_dims(); view_dims.Assign(image_dims); view_dims.Access_size().Set_x(imageSize.Get_x()); view_dims.Access_size().Set_y(imageSize.Get_y()); int region_buf_size = imageSize.Get_x() * imageSize.Get_y(); int[] region_buf = new int[region_buf_size]; Kdu_region_decompressor decompressor = new Kdu_region_decompressor(); decompressor.Start(codestream, channels, -1, params.getLevelReductionFactor(), 16384, image_dims, ref_expansion, new Kdu_coords(1, 1), false, Kdu_global.KDU_WANT_OUTPUT_COMPONENTS); Kdu_dims new_region = new Kdu_dims(); Kdu_dims incomplete_region = new Kdu_dims(); Kdu_coords viewSize = view_dims.Access_size(); incomplete_region.Assign(image_dims); int[] imgBuffer = new int[viewSize.Get_x() * viewSize.Get_y()]; int[] kduBuffer = null; while (decompressor.Process(region_buf, image_dims.Access_pos(), 0, 0, region_buf_size, incomplete_region, new_region)) { Kdu_coords newOffset = new_region.Access_pos(); Kdu_coords newSize = new_region.Access_size(); newOffset.Subtract(view_dims.Access_pos()); kduBuffer = region_buf; int imgBuffereIdx = newOffset.Get_x() + newOffset.Get_y() * viewSize.Get_x(); int kduBufferIdx = 0; int xDiff = viewSize.Get_x() - newSize.Get_x(); for (int j = 0; j < newSize.Get_y(); j++, imgBuffereIdx += xDiff) { for (int i = 0; i < newSize.Get_x(); i++) { imgBuffer[imgBuffereIdx++] = kduBuffer[kduBufferIdx++]; } } } BufferedImage image = new BufferedImage(imageSize.Get_x(), imageSize.Get_y(), BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, viewSize.Get_x(), viewSize.Get_y(), imgBuffer, 0, viewSize.Get_x()); if (params.getRotationDegree() > 0) { image = ImageProcessingUtils.rotate(image, params.getRotationDegree()); } decompressor.Native_destroy(); channels.Native_destroy(); if (codestream.Exists()) codestream.Destroy(); inputSource.Native_destroy(); input.Native_destroy(); jp2_family_in.Native_destroy(); return image; } catch (KduException e) { e.printStackTrace(); throw new DjatokaException(e); } catch (Exception e) { e.printStackTrace(); throw new DjatokaException(e); } } Code Sample 2: @Override public String fetchURL(String urlString) throws ServiceException { try { URL url = new URL(urlString); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String content = ""; String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } reader.close(); return content; } catch (MalformedURLException e) { throw new ServiceException(e.getMessage()); } catch (IOException e) { throw new ServiceException(e.getMessage()); } }
00
Code Sample 1: public static String SHA1(String text) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes()); byte byteData[] = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } StringBuffer hexString = new StringBuffer(); for (int i = 0; i < byteData.length; i++) { String hex = Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } Code Sample 2: public static void batchInsertOrder(Order o) throws AppException { Connection conn = DBUtils.getDataConnection(); PreparedStatement pstmt = null; ResultSet rs = null; String sqlOrder = null; String sqlDetail = null; try { conn.setAutoCommit(false); sqlOrder = "insert into SO_SOMain (ID,cSOCode,dDate," + "cBusType,cCusCode,cCusName," + "cDepCode,cSTCode," + "iVTid,cMaker,cMemo) values (?,?,?,?,?,?,?,?,?,?,?)"; sqlDetail = "insert into SO_SODetails (ID,cSOCode,cInvCode,cInvName," + "iNum,iQuantity,iTaxUnitPrice,iSum,dPreDate,iSOsID,cFree1,cUnitID) values(?,?,?,?,?,?,?,?,?,?,?,?)"; pstmt = conn.prepareStatement(sqlOrder); long maxId = getMaxID(conn, pstmt, rs); maxId++; pstmt.setLong(1, maxId); Long l = maxId; o.setId(l.intValue()); String code = o.getCode(); long maxCSOCode = getMaxCSOCode(code, conn, pstmt, rs); String csOCode = getCSOCode(code, maxCSOCode); o.setCode(csOCode); pstmt.setString(2, csOCode); pstmt.setDate(3, DateUtil.getSqlDateFormUtilDate(o.getOrderDate())); pstmt.setString(4, o.getBusinessType()); pstmt.setString(5, o.getC().getId()); pstmt.setString(6, o.getC().getName()); pstmt.setString(7, o.getP().getDept().getId()); pstmt.setString(8, o.getSaleType().getId()); pstmt.setInt(9, o.getiVtid()); pstmt.setString(10, o.getP().getName()); pstmt.setString(11, o.getRemark()); pstmt.executeUpdate(); pstmt.clearParameters(); pstmt = conn.prepareStatement(sqlDetail); ArrayList<OrderDetail> ods = o.getOds(); long iSOsID = getiSOsID(conn, pstmt, rs); for (OrderDetail od : ods) { pstmt.setLong(1, maxId); pstmt.setString(2, csOCode); pstmt.setString(3, od.getInventory().getId()); pstmt.setString(4, od.getInventory().getName()); pstmt.setInt(5, od.getPiece()); pstmt.setBigDecimal(6, od.getCount()); pstmt.setBigDecimal(7, od.getPrice()); pstmt.setBigDecimal(8, od.getSum()); pstmt.setDate(9, DateUtil.getSqlDateFormUtilDate(od.getSendDate())); pstmt.setLong(10, ++iSOsID); pstmt.setString(11, od.getPacking().getcValue()); pstmt.setString(12, od.getInventory().getSAComUnitCode()); pstmt.executeUpdate(); pstmt.clearParameters(); } conn.commit(); } catch (SQLException sqle) { try { conn.rollback(); throw new AppException(sqle.getMessage()); } catch (SQLException ex) { Logger.getLogger(OrderDAO.class.getName()).log(Level.SEVERE, null, ex); throw new AppException(ex.getMessage()); } } finally { DBUtils.closeAll(rs, pstmt, conn); } }
11
Code Sample 1: public void run() { if (saveAsDialog == null) { saveAsDialog = new FileDialog(window.getShell(), SWT.SAVE); saveAsDialog.setFilterExtensions(saveAsTypes); } String outputFile = saveAsDialog.open(); if (outputFile != null) { Object inputFile = DataSourceSingleton.getInstance().getContainer().getWrapped(); InputStream in; try { if (inputFile instanceof URL) in = ((URL) inputFile).openStream(); else in = new FileInputStream((File) inputFile); OutputStream out = new FileOutputStream(outputFile); if (outputFile.endsWith("xml")) { int c; while ((c = in.read()) != -1) out.write(c); } else { PrintWriter pw = new PrintWriter(out); Element data = DataSourceSingleton.getInstance().getRawData(); writeTextFile(data, pw, -1); pw.close(); } in.close(); out.close(); } catch (MalformedURLException e1) { } catch (IOException e) { } } } Code Sample 2: private void compress(File target, Set<File> files) throws CacheOperationException, ConfigurationException { ZipOutputStream zipOutput = null; try { zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target))); for (File file : files) { BufferedInputStream fileInput = null; File cachePathName = new File(cacheFolder, file.getPath()); try { if (!cachePathName.exists()) { throw new CacheOperationException("Expected to add file ''{0}'' to export archive ''{1}'' (Account : {2}) but it " + "has gone missing (cause unknown). This can indicate implementation or deployment " + "error. Aborting export operation as a safety precaution.", cachePathName.getPath(), target.getAbsolutePath(), account.getOid()); } fileInput = new BufferedInputStream(new FileInputStream(cachePathName)); ZipEntry entry = new ZipEntry(file.getPath()); entry.setSize(cachePathName.length()); entry.setTime(cachePathName.lastModified()); zipOutput.putNextEntry(entry); cacheLog.debug("Added new export zip entry ''{0}''.", file.getPath()); int count, total = 0; int buffer = 2048; byte[] data = new byte[buffer]; while ((count = fileInput.read(data, 0, buffer)) != -1) { zipOutput.write(data, 0, count); total += count; } zipOutput.flush(); if (total != cachePathName.length()) { throw new CacheOperationException("Only wrote {0} out of {1} bytes when archiving file ''{2}'' (Account : {3}). " + "This could have occured either due implementation error or file I/O error. " + "Aborting archive operation to prevent a potentially corrupt export archive to " + "be created.", total, cachePathName.length(), cachePathName.getPath(), account.getOid()); } else { cacheLog.debug("Wrote {0} out of {1} bytes to zip entry ''{2}''", total, cachePathName.length(), file.getPath()); } } catch (SecurityException e) { throw new ConfigurationException("Security manager has denied r/w access when attempting to read file ''{0}'' and " + "write it to archive ''{1}'' (Account : {2}) : {3}", e, cachePathName.getPath(), target, account.getOid(), e.getMessage()); } catch (IllegalArgumentException e) { throw new CacheOperationException("Error creating ZIP archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (FileNotFoundException e) { throw new CacheOperationException("Attempted to include file ''{0}'' in export archive but it has gone missing " + "(Account : {1}). Possible implementation error in local file cache. Aborting " + "export operation as a precaution ({2})", e, cachePathName.getPath(), account.getOid(), e.getMessage()); } catch (ZipException e) { throw new CacheOperationException("Error writing export archive for account ID = {0} : {1}", e, account.getOid(), e.getMessage()); } catch (IOException e) { throw new CacheOperationException("I/O error while creating export archive for account ID = {0}. " + "Operation aborted ({1})", e, account.getOid(), e.getMessage()); } finally { if (zipOutput != null) { try { zipOutput.closeEntry(); } catch (Throwable t) { cacheLog.warn("Unable to close zip entry for file ''{0}'' in export archive ''{1}'' " + "(Account : {2}) : {3}.", t, file.getPath(), target.getAbsolutePath(), account.getOid(), t.getMessage()); } } if (fileInput != null) { try { fileInput.close(); } catch (Throwable t) { cacheLog.warn("Failed to close input stream from file ''{0}'' being added " + "to export archive (Account : {1}) : {2}", t, cachePathName.getPath(), account.getOid(), t.getMessage()); } } } } } catch (FileNotFoundException e) { throw new CacheOperationException("Unable to create target export archive ''{0}'' for account {1) : {2}", e, target, account.getOid(), e.getMessage()); } finally { try { if (zipOutput != null) { zipOutput.close(); } } catch (Throwable t) { cacheLog.warn("Failed to close the stream to export archive ''{0}'' : {1}.", t, target, t.getMessage()); } } }
11
Code Sample 1: public static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } } 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 { 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) { } ; } }
00
Code Sample 1: public static String CreateHash(String s) { String str = s.toString(); if (str == null || str.length() == 0) { throw new IllegalArgumentException("String cannot be null or empty"); } StringBuffer hexString = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] hash = md.digest(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { hexString.append(Integer.toHexString(0xFF & hash[i])); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return (hexString.toString()); } Code Sample 2: protected URLConnection openConnection(URL url) throws IOException { URLStreamHandler handler = factory.findAuthorizedURLStreamHandler(protocol); if (handler != null) { try { return (URLConnection) openConnectionMethod.invoke(handler, new Object[] { url }); } catch (Exception e) { factory.adaptor.getFrameworkLog().log(new FrameworkLogEntry(MultiplexingURLStreamHandler.class.getName(), "openConnection", FrameworkLogEntry.ERROR, e, null)); throw new RuntimeException(e.getMessage()); } } throw new MalformedURLException(); }
00
Code Sample 1: public void manageRequest(Transformer transformer) throws ServletException { try { this.parser.reset(); String encodedQuery = URLEncoder.encode(this.query, "ISO-8859-1"); URL url = new URL(EXIST_SERVER + "?_query=" + encodedQuery); InputStream in = url.openStream(); Document doc = this.parser.parse(in); Source source = new DOMSource(doc); transformer.transform(source, new StreamResult(this.getOut())); } catch (TransformerException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { Log.debug(fnfe); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: private SecretKey getSecretKey() { try { String path = "/org.dbreplicator/repconsole/secretKey.obj"; java.net.URL url1 = getClass().getResource(path); ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(url1.openStream())); SecretKey sk = (SecretKey) ois.readObject(); return sk; } catch (IOException ex) { } catch (ClassNotFoundException ex) { } return null; } Code Sample 2: public byte[] loadRaw(String ontologyUrl) throws IOException { URL url = new URL(ontologyUrl); InputStream is = url.openStream(); final int BUFFER_SIZE = 1024; byte[] buffer = new byte[BUFFER_SIZE]; ByteArrayOutputStream ontologyBytes = new ByteArrayOutputStream(); for (; ; ) { int bytesRead = is.read(buffer); if (bytesRead <= 0) break; ontologyBytes.write(buffer, 0, bytesRead); } return ontologyBytes.toByteArray(); }
11
Code Sample 1: @SuppressWarnings("unchecked") protected void processTransformAction(HttpServletRequest request, HttpServletResponse response, String action) throws Exception { File transformationFile = null; String tr = request.getParameter(Definitions.REQUEST_PARAMNAME_XSLT); if (StringUtils.isNotBlank(tr)) { transformationFile = new File(xslBase, tr); if (!transformationFile.isFile()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter \"" + Definitions.REQUEST_PARAMNAME_XSLT + "\" " + "with value \"" + tr + "\" refers to non existing file"); return; } } StreamResult result; ByteArrayOutputStream baos = null; if (isDevelopmentMode) { baos = new ByteArrayOutputStream(); if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(baos, Base64.DECODE)); } else { result = new StreamResult(baos); } } else { if (StringUtils.equals(action, "get")) { result = new StreamResult(new Base64.OutputStream(response.getOutputStream(), Base64.DECODE)); } else { result = new StreamResult(response.getOutputStream()); } } HashMap<String, Object> params = new HashMap<String, Object>(); params.putAll(request.getParameterMap()); params.put("{" + Definitions.CONFIGURATION_NAMESPACE + "}configuration", configuration); params.put("{" + Definitions.REQUEST_NAMESPACE + "}request", request); params.put("{" + Definitions.RESPONSE_NAMESPACE + "}response", response); params.put("{" + Definitions.SESSION_NAMESPACE + "}session", request.getSession()); params.put("{" + Definitions.INFOFUZE_NAMESPACE + "}development-mode", new Boolean(Config.getInstance().isDevelopmentMode())); Transformer transformer = new Transformer(); transformer.setTransformationFile(transformationFile); transformer.setParams(params); transformer.setTransformMode(TransformMode.NORMAL); transformer.setConfiguration(configuration); transformer.setErrorListener(new TransformationErrorListener(response)); transformer.setLogInfo(false); String method = transformer.getOutputProperties().getProperty(OutputKeys.METHOD, "xml"); String contentType; if (method.endsWith("html")) { contentType = Definitions.MIMETYPE_HTML; } else if (method.equals("xml")) { contentType = Definitions.MIMETYPE_XML; } else { contentType = Definitions.MIMETYPE_TEXTPLAIN; } String encoding = transformer.getOutputProperties().getProperty(OutputKeys.ENCODING, "UTF-8"); response.setContentType(contentType + ";charset=" + encoding); DataSourceIf dataSource = new NullSource(); transformer.transform((Source) dataSource, result); if (isDevelopmentMode) { IOUtils.copy(new ByteArrayInputStream(baos.toByteArray()), response.getOutputStream()); } } Code Sample 2: private void collectImageFile(@NotNull final Progress progress, @NotNull final File collectedDirectory) throws IOException { final File file = new File(collectedDirectory, ActionBuilderUtils.getString(ACTION_BUILDER, "configSource.image.name")); final FileOutputStream fos = new FileOutputStream(file); try { final FileChannel outChannel = fos.getChannel(); try { final int numOfFaceObjects = faceObjects.size(); progress.setLabel(ActionBuilderUtils.getString(ACTION_BUILDER, "archCollectImages"), numOfFaceObjects); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024); final Charset charset = Charset.forName("ISO-8859-1"); int i = 0; for (final FaceObject faceObject : faceObjects) { final String face = faceObject.getFaceName(); final String path = archFaceProvider.getFilename(face); try { final FileInputStream fin = new FileInputStream(path); try { final FileChannel inChannel = fin.getChannel(); final long imageSize = inChannel.size(); byteBuffer.clear(); byteBuffer.put(("IMAGE " + (faceObjects.isIncludeFaceNumbers() ? i + " " : "") + imageSize + " " + face + "\n").getBytes(charset)); byteBuffer.flip(); outChannel.write(byteBuffer); inChannel.transferTo(0L, imageSize, outChannel); } finally { fin.close(); } } catch (final FileNotFoundException ignored) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorFileNotFound", path); return; } catch (final IOException e) { ACTION_BUILDER.showMessageDialog(progress.getParentComponent(), "archCollectErrorIOException", path, e); return; } if (i++ % 100 == 0) { progress.setValue(i); } } progress.setValue(faceObjects.size()); } finally { outChannel.close(); } } finally { fos.close(); } }
00
Code Sample 1: public boolean synch(boolean verbose) { try { this.verbose = verbose; if (verbose) System.out.println(" -- Synchronizing: " + destDir + " to " + urlStr); URLConnection urc = new URL(urlStr + "/" + MANIFEST).openConnection(); InputStream is = urc.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); while (true) { String str = r.readLine(); if (str == null) { break; } dealWith(str); } is.close(); } catch (Exception ex) { System.out.println("Synchronization of " + destDir + " failed."); ex.printStackTrace(); return false; } return true; } Code Sample 2: public static void readShaderSource(ClassLoader context, String path, URL url, StringBuffer result) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { if (line.startsWith("#include ")) { String includeFile = line.substring(9).trim(); String next = Locator.getRelativeOf(path, includeFile); URL nextURL = Locator.getResource(next, context); if (nextURL == null) { next = includeFile; nextURL = Locator.getResource(next, context); } if (nextURL == null) { throw new FileNotFoundException("Can't find include file " + includeFile); } readShaderSource(context, next, nextURL, result); } else { result.append(line + "\n"); } } } catch (IOException e) { throw new RuntimeException(e); } }
11
Code Sample 1: public void deleteRole(AuthSession authSession, RoleBean roleBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (roleBean.getRoleId() == null) throw new IllegalArgumentException("role id is null"); String sql = "delete from WM_AUTH_ACCESS_GROUP where ID_ACCESS_GROUP=? "; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, roleBean.getRoleId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete role"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: @Override public int updateStatement(String sql) { Statement statement = null; try { statement = getConnection().createStatement(); return statement.executeUpdate(sql); } catch (SQLException e) { try { getConnection().rollback(); } catch (SQLException e1) { log.error(e1.getMessage(), e1); } log.error(e.getMessage(), e); return 0; } finally { try { statement.close(); getConnection().close(); } catch (SQLException e) { log.error(e.getMessage(), e); } } }
11
Code Sample 1: public MemoryTextBody(InputStream is, String mimeCharset) throws IOException { this.mimeCharset = mimeCharset; TempPath tempPath = TempStorage.getInstance().getRootTempPath(); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(is, out); out.close(); tempFile = out.toByteArray(); } 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; } }
00
Code Sample 1: public static void main(String args[]) { int i, j, l; short NUMNUMBERS = 256; short numbers[] = new short[NUMNUMBERS]; Darjeeling.print("START"); for (l = 0; l < 100; l++) { for (i = 0; i < NUMNUMBERS; i++) numbers[i] = (short) (NUMNUMBERS - 1 - i); for (i = 0; i < NUMNUMBERS; i++) { for (j = 0; j < NUMNUMBERS - i - 1; j++) if (numbers[j] > numbers[j + 1]) { short temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } Darjeeling.print("END"); } Code Sample 2: @Override protected void copyContent(String filename) throws IOException { InputStream in = null; try { String resourceDir = System.getProperty("resourceDir"); File resource = new File(resourceDir, filename); ByteArrayOutputStream out = new ByteArrayOutputStream(); if (resource.exists()) { in = new FileInputStream(resource); } else { in = LOADER.getResourceAsStream(RES_PKG + filename); } IOUtils.copy(in, out); setResponseData(out.toByteArray()); } finally { if (in != null) { in.close(); } } }
11
Code Sample 1: public static void importDB(String input, String output) { try { Class.forName("org.sqlite.JDBC"); String fileName = output + File.separator + G.databaseName; File dataBase = new File(fileName); if (!dataBase.exists()) { G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); createTablesDB(); } else G.conn = DriverManager.getConnection("jdbc:sqlite:" + fileName); long tiempoInicio = System.currentTimeMillis(); String directoryPath = input + File.separator; File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); File fileXML = new File(input + File.separator + G.imagesName); if (!fileXML.exists()) { JOptionPane.showMessageDialog(null, "No se encuentra el fichero XML", "Error", JOptionPane.ERROR_MESSAGE); } else { SAXBuilder builder = new SAXBuilder(false); Document docXML = builder.build(fileXML); Element root = docXML.getRootElement(); List images = root.getChildren("image"); Iterator j = images.iterator(); List<Element> globalLanguages = root.getChild("languages").getChildren("language"); Iterator<Element> langsI = globalLanguages.iterator(); HashMap<String, Integer> languageIDs = new HashMap<String, Integer>(); HashMap<String, Integer> typeIDs = new HashMap<String, Integer>(); Element e; int i = 0; int contTypes = 0; int contImages = 0; while (langsI.hasNext()) { e = langsI.next(); languageIDs.put(e.getText(), i); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO language (id,name) VALUES (?,?)"); stmt.setInt(1, i); stmt.setString(2, e.getText()); stmt.executeUpdate(); stmt.close(); i++; } G.conn.setAutoCommit(false); while (j.hasNext()) { Element image = (Element) j.next(); String id = image.getAttributeValue("id"); List languages = image.getChildren("language"); Iterator k = languages.iterator(); if (exists(list, id)) { String pathSrc = directoryPath.concat(id); String pathDst = output + File.separator + id.substring(0, 1).toUpperCase() + File.separator; String folder = output + File.separator + id.substring(0, 1).toUpperCase(); String pathDstTmp = pathDst.concat(id); String idTmp = id; File testFile = new File(pathDstTmp); int cont = 1; while (testFile.exists()) { idTmp = id.substring(0, id.lastIndexOf('.')) + '_' + cont + id.substring(id.lastIndexOf('.'), id.length()); pathDstTmp = pathDst + idTmp; testFile = new File(pathDstTmp); cont++; } pathDst = pathDstTmp; id = idTmp; File newDirectoryFolder = new File(folder); if (!newDirectoryFolder.exists()) { newDirectoryFolder.mkdirs(); } try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(pathDst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.toString()); } while (k.hasNext()) { Element languageElement = (Element) k.next(); String language = languageElement.getAttributeValue("id"); List words = languageElement.getChildren("word"); Iterator l = words.iterator(); while (l.hasNext()) { Element wordElement = (Element) l.next(); String type = wordElement.getAttributeValue("type"); if (!typeIDs.containsKey(type)) { typeIDs.put(type, contTypes); PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO type (id,name) VALUES (?,?)"); stmt.setInt(1, contTypes); stmt.setString(2, type); stmt.executeUpdate(); stmt.close(); contTypes++; } PreparedStatement stmt = G.conn.prepareStatement("INSERT OR IGNORE INTO main (word, idL, idT, name, nameNN) VALUES (?,?,?,?,?)"); stmt.setString(1, wordElement.getText().toLowerCase()); stmt.setInt(2, languageIDs.get(language)); stmt.setInt(3, typeIDs.get(type)); stmt.setString(4, id); stmt.setString(5, id); stmt.executeUpdate(); stmt.close(); if (contImages == 5000) { G.conn.commit(); contImages = 0; } else contImages++; } } } else { } } G.conn.setAutoCommit(true); G.conn.close(); long totalTiempo = System.currentTimeMillis() - tiempoInicio; System.out.println("El tiempo total es :" + totalTiempo / 1000 + " segundos"); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: 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; }
00
Code Sample 1: public static byte[] read(URL url) throws IOException { byte[] bytes; InputStream is = null; try { is = url.openStream(); bytes = readAllBytes(is); } finally { if (is != null) { is.close(); } } return bytes; } Code Sample 2: public static long copy(File src, File dest) throws UtilException { FileChannel srcFc = null; FileChannel destFc = null; try { srcFc = new FileInputStream(src).getChannel(); destFc = new FileOutputStream(dest).getChannel(); long srcLength = srcFc.size(); srcFc.transferTo(0, srcLength, destFc); return srcLength; } catch (IOException e) { throw new UtilException(e); } finally { try { if (srcFc != null) srcFc.close(); srcFc = null; } catch (IOException e) { } try { if (destFc != null) destFc.close(); destFc = null; } catch (IOException e) { } } }
11
Code Sample 1: private void simulate() throws Exception { BufferedWriter out = null; out = new BufferedWriter(new FileWriter(outFile)); out.write("#Thread\tReputation\tAction\n"); out.flush(); System.out.println("Simulate..."); File file = new File(trsDemoSimulationfile); ObtainUserReputation obtainUserReputationRequest = new ObtainUserReputation(); ObtainUserReputationResponse obtainUserReputationResponse; RateUser rateUserRequest; RateUserResponse rateUserResponse; FileInputStream fis = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String call = br.readLine(); while (call != null) { rateUserRequest = generateRateUserRequest(call); try { rateUserResponse = trsPort.rateUser(rateUserRequest); System.out.println("----------------R A T I N G-------------------"); System.out.println("VBE: " + rateUserRequest.getVbeId()); System.out.println("VO: " + rateUserRequest.getVoId()); System.out.println("USER: " + rateUserRequest.getUserId()); System.out.println("SERVICE: " + rateUserRequest.getServiceId()); System.out.println("ACTION: " + rateUserRequest.getActionId()); System.out.println("OUTCOME: " + rateUserResponse.isOutcome()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the rateUser should be true: MESSAGE=" + rateUserResponse.getMessage(), true, rateUserResponse.isOutcome()); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(null); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } obtainUserReputationRequest.setIoi(null); obtainUserReputationRequest.setServiceId(null); obtainUserReputationRequest.setUserId(rateUserRequest.getUserId()); obtainUserReputationRequest.setVbeId(rateUserRequest.getVbeId()); obtainUserReputationRequest.setVoId(rateUserRequest.getVoId()); try { obtainUserReputationResponse = trsPort.obtainUserReputation(obtainUserReputationRequest); System.out.println("-----------R E P U T A T I O N----------------"); System.out.println("VBE: " + obtainUserReputationRequest.getVbeId()); System.out.println("VO: " + obtainUserReputationRequest.getVoId()); System.out.println("USER: " + obtainUserReputationRequest.getUserId()); System.out.println("SERVICE: " + obtainUserReputationRequest.getServiceId()); System.out.println("IOI: " + obtainUserReputationRequest.getIoi()); System.out.println("REPUTATION: " + obtainUserReputationResponse.getReputation()); System.out.println("----------------------------------------------"); assertEquals("The outcome field of the obtainUserReputation should be true: MESSAGE=" + obtainUserReputationResponse.getMessage(), true, obtainUserReputationResponse.isOutcome()); assertEquals(0.0, obtainUserReputationResponse.getReputation(), 1.0); } catch (RemoteException e) { fail(e.getMessage()); } call = br.readLine(); } fis.close(); br.close(); out.flush(); out.close(); } Code Sample 2: public static void copyFile(File sourceFile, File destFile) throws IOException { FileChannel inputFileChannel = new FileInputStream(sourceFile).getChannel(); FileChannel outputFileChannel = new FileOutputStream(destFile).getChannel(); long offset = 0L; long length = inputFileChannel.size(); final long MAXTRANSFERBUFFERLENGTH = 1024 * 1024; try { for (; offset < length; ) { offset += inputFileChannel.transferTo(offset, MAXTRANSFERBUFFERLENGTH, outputFileChannel); inputFileChannel.position(offset); } } finally { try { outputFileChannel.close(); } catch (Exception ignore) { } try { inputFileChannel.close(); } catch (IOException ignore) { } } }
11
Code Sample 1: private void copy(File fromFile, File toFile) throws IOException { String fromFileName = fromFile.getName(); File tmpFile = new File(fromFileName); String toFileName = toFile.getName(); if (!tmpFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!tmpFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!tmpFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(tmpFile); File toF = new File(toFile.getCanonicalPath()); if (!toF.exists()) ; toF.createNewFile(); if (!SBCMain.DEBUG_MODE) to = new FileOutputStream(toFile); else to = new FileOutputStream(toF); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
11
Code Sample 1: public Leilao insertLeilao(Leilao leilao) throws SQLException { Connection conn = null; String insert = "insert into Leilao (idleilao, atividade_idatividade, datainicio, datafim) " + "values " + "(nextval('seq_leilao'), " + leilao.getAtividade().getIdAtividade() + ", '" + leilao.getDataInicio() + "', '" + leilao.getDataFim() + "')"; try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); if (result == 1) { String sqlSelect = "select last_value from seq_leilao"; ResultSet rs = stmt.executeQuery(sqlSelect); while (rs.next()) { leilao.setIdLeilao(rs.getInt("last_value")); } } conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } return null; } Code Sample 2: public void updatePortletName(PortletName portletNameBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); String sql = "update WM_PORTAL_PORTLET_NAME " + "set TYPE=? " + "where ID_SITE_CTX_TYPE=?"; ps = dbDyn.prepareStatement(sql); ps.setString(1, portletNameBean.getPortletName()); RsetTools.setLong(ps, 2, portletNameBean.getPortletId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of updated record - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error save portlet name"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
11
Code Sample 1: public static void copy(File source, File dest) throws BuildException { dest = new File(dest, source.getName()); if (source.isFile()) { byte[] buffer = new byte[4096]; FileInputStream fin = null; FileOutputStream fout = null; try { fin = new FileInputStream(source); fout = new FileOutputStream(dest); int count = 0; while ((count = fin.read(buffer)) > 0) fout.write(buffer, 0, count); fin.close(); fout.close(); } catch (IOException ex) { throw new BuildException(ex); } finally { try { if (fin != null) fin.close(); } catch (IOException ex) { } try { if (fout != null) fout.close(); } catch (IOException ex) { } } } else { dest.mkdirs(); File[] children = source.listFiles(); for (File child : children) copy(child, dest); } } Code Sample 2: private boolean enregistreToi() { PrintWriter lEcrivain; String laDest = "./img_types/" + sonImage; if (!new File("./img_types").exists()) { new File("./img_types").mkdirs(); } try { FileChannel leFicSource = new FileInputStream(sonFichier).getChannel(); FileChannel leFicDest = new FileOutputStream(laDest).getChannel(); leFicSource.transferTo(0, leFicSource.size(), leFicDest); leFicSource.close(); leFicDest.close(); lEcrivain = new PrintWriter(new FileWriter(new File("bundll/types.jay"), true)); lEcrivain.println(sonNom); lEcrivain.println(sonImage); if (sonOptionRadio1.isSelected()) { lEcrivain.println("0:?"); } if (sonOptionRadio2.isSelected()) { lEcrivain.println("1:" + JOptionPane.showInputDialog(null, "Vous avez choisis de rendre ce terrain difficile � franchir.\nVeuillez en indiquer la raison.", "Demande de pr�cision", JOptionPane.INFORMATION_MESSAGE)); } if (sonOptionRadio3.isSelected()) { lEcrivain.println("2:?"); } lEcrivain.close(); return true; } catch (Exception lException) { return false; } }
00
Code Sample 1: public void testHttpsConnection() { try { URL url = new URL("https://addons.mozilla.org/zh-CN/firefox/"); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setDoOutput(true); connection.getOutputStream().write("hello".getBytes()); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void fileCopy(String from_name, String to_name) throws IOException { File fromFile = new File(from_name); File toFile = new File(to_name); if (fromFile.equals(toFile)) abort("cannot copy on itself: " + from_name); if (!fromFile.exists()) abort("no such currentSourcepartName file: " + from_name); if (!fromFile.isFile()) abort("can't copy directory: " + from_name); if (!fromFile.canRead()) abort("currentSourcepartName file is unreadable: " + from_name); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) abort("destination file is unwriteable: " + to_name); } else { String parent = toFile.getParent(); if (parent == null) abort("destination directory doesn't exist: " + parent); File dir = new File(parent); if (!dir.exists()) abort("destination directory doesn't exist: " + parent); if (dir.isFile()) abort("destination is not a directory: " + parent); if (!dir.canWrite()) abort("destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: @Test public void testCopy_readerToOutputStream_Encoding_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (OutputStream) null, "UTF16"); fail(); } catch (NullPointerException ex) { } } Code Sample 2: private static void init() { try { ClassLoader cl = Thread.currentThread().getContextClassLoader(); Enumeration<URL> enumeration = cl.getResources("extension-services.properties"); do { if (!enumeration.hasMoreElements()) break; URL url = (URL) enumeration.nextElement(); System.out.println(" - " + url); try { props = new Properties(); props.load(url.openStream()); } catch (Exception e) { e.printStackTrace(); } } while (true); } catch (IOException e) { } }
11
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: private JeeObserverServerContext(JeeObserverServerContextProperties properties) throws DatabaseException, ServerException { super(); try { final MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(("JE" + System.currentTimeMillis()).getBytes()); final BigInteger hash = new BigInteger(1, md5.digest()); this.sessionId = hash.toString(16).toUpperCase(); } catch (final Exception e) { this.sessionId = "JE" + System.currentTimeMillis(); JeeObserverServerContext.logger.log(Level.WARNING, "JeeObserver Server session ID MD5 error: {0}", this.sessionId); JeeObserverServerContext.logger.log(Level.FINEST, e.getMessage(), e); } try { @SuppressWarnings("unchecked") final Class<DatabaseHandler> databaseHandlerClass = (Class<DatabaseHandler>) Class.forName(properties.getDatabaseHandler()); final Constructor<DatabaseHandler> handlerConstructor = databaseHandlerClass.getConstructor(new Class<?>[] { String.class, String.class, String.class, String.class, String.class, Integer.class }); this.databaseHandler = handlerConstructor.newInstance(new Object[] { properties.getDatabaseDriver(), properties.getDatabaseUrl(), properties.getDatabaseUser(), properties.getDatabasePassword(), properties.getDatabaseSchema(), new Integer(properties.getDatabaseConnectionPoolSize()) }); } catch (final Exception e) { throw new ServerException("Database handler loading exception.", e); } this.databaseHandlerTimer = new Timer(JeeObserverServerContext.DATABASE_HANDLER_TASK_NAME, true); this.server = new JeeObserverServer(properties.getServerPort()); this.enabled = true; this.properties = properties; this.startTimestamp = new Date(); try { this.ip = InetAddress.getLocalHost().getHostAddress(); } catch (final UnknownHostException e) { JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage(), e); } this.operatingSystemName = System.getProperty("os.name"); this.operatingSystemVersion = System.getProperty("os.version"); this.operatingSystemArchitecture = System.getProperty("os.arch"); this.javaVersion = System.getProperty("java.version"); this.javaVendor = System.getProperty("java.vendor"); }
00
Code Sample 1: public static void copyFile(String inputFile, String outputFile) throws IOException { FileInputStream fis = new FileInputStream(inputFile); FileOutputStream fos = new FileOutputStream(outputFile); for (int b = fis.read(); b != -1; b = fis.read()) fos.write(b); fos.close(); fis.close(); } Code Sample 2: public void setPassword(String password) { MessageDigest md; try { md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); String encodedPassword = Base64.encode(digest); this.password = encodedPassword; } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Password creation failed", e); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { logger.log(Level.SEVERE, "Password creation failed", e); throw new RuntimeException(e); } }
11
Code Sample 1: @Test public void testWriteAndReadBigger() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwrite.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[body.length()]; int readCount = in.read(buffer); in.close(); assertEquals(body.length(), readCount); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } } Code Sample 2: 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: private boolean createFTPConnection() { client = new FTPClient(); System.out.println("Client created"); try { client.connect(this.hostname, this.port); System.out.println("Connected: " + this.hostname + ", " + this.port); client.login(username, password); System.out.println("Logged in: " + this.username + ", " + this.password); this.setupActiveFolder(); return true; } catch (IllegalStateException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (FTPIllegalReplyException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } catch (FTPException ex) { Logger.getLogger(FTPProject.class.getName()).log(Level.SEVERE, null, ex); } return false; } Code Sample 2: ServiceDescription getServiceDescription() throws ConfigurationException { final XPath pathsXPath = this.xPathFactory.newXPath(); try { final Node serviceDescriptionNode = (Node) pathsXPath.evaluate(ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration, XPathConstants.NODE); final String title = getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.TITLE_ELEMENT); ServiceDescription.Builder builder = new ServiceDescription.Builder(title, Migrate.class.getCanonicalName()); Property[] serviceProperties = getServiceProperties(serviceDescriptionNode); builder.author(getMandatoryElementText(serviceDescriptionNode, ConfigurationFileTagsV1.CREATOR_ELEMENT)); builder.classname(this.canonicalServiceName); builder.description(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.DESCRIPTION_ELEMENT)); final String serviceVersion = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.VERSION_ELEMENT); final Tool toolDescription = getToolDescriptionElement(serviceDescriptionNode); String identifier = getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.IDENTIFIER_ELEMENT); if (identifier == null || "".equals(identifier)) { try { final MessageDigest identDigest = MessageDigest.getInstance("MD5"); identDigest.update(this.canonicalServiceName.getBytes()); final String versionInfo = (serviceVersion != null) ? serviceVersion : ""; identDigest.update(versionInfo.getBytes()); final URI toolIDURI = toolDescription.getIdentifier(); final String toolIdentifier = toolIDURI == null ? "" : toolIDURI.toString(); identDigest.update(toolIdentifier.getBytes()); final BigInteger md5hash = new BigInteger(identDigest.digest()); identifier = md5hash.toString(16); } catch (NoSuchAlgorithmException nsae) { throw new RuntimeException(nsae); } } builder.identifier(identifier); builder.version(serviceVersion); builder.tool(toolDescription); builder.instructions(getOptionalElementText(serviceDescriptionNode, ConfigurationFileTagsV1.INSTRUCTIONS_ELEMENT)); builder.furtherInfo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.FURTHER_INFO_ELEMENT)); builder.logo(getOptionalURIElement(serviceDescriptionNode, ConfigurationFileTagsV1.LOGO_ELEMENT)); builder.serviceProvider(this.serviceProvider); final DBMigrationPathFactory migrationPathFactory = new DBMigrationPathFactory(this.configuration); final MigrationPaths migrationPaths = migrationPathFactory.getAllMigrationPaths(); builder.paths(MigrationPathConverter.toPlanetsPaths(migrationPaths)); builder.inputFormats(migrationPaths.getInputFormatURIs().toArray(new URI[0])); builder.parameters(getUniqueParameters(migrationPaths)); builder.properties(serviceProperties); return builder.build(); } catch (XPathExpressionException xPathExpressionException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), xPathExpressionException); } catch (NullPointerException nullPointerException) { throw new ConfigurationException(String.format("Failed parsing the '%s' element in the '%s' element.", ConfigurationFileTagsV1.SERVICE_DESCRIPTION_ELEMENT_XPATH, this.configuration.getNodeName()), nullPointerException); } }
00
Code Sample 1: public SequenceIterator call(SequenceIterator[] arguments, XPathContext context) throws XPathException { try { String encodedString = ((StringValue) arguments[0].next()).getStringValue(); byte[] decodedBytes = Base64.decode(encodedString); if (arguments.length > 1 && ((BooleanValue) arguments[1].next()).getBooleanValue()) { ByteArrayInputStream bis = new ByteArrayInputStream(decodedBytes); GZIPInputStream zis = new GZIPInputStream(bis); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zis, baos); decodedBytes = baos.toByteArray(); } Document doc = XmlUtils.stringToDocument(new String(decodedBytes, "UTF-8")); Source source = new DOMSource(doc.getDocumentElement()); XPathEvaluator evaluator = new XPathEvaluator(context.getConfiguration()); NodeInfo[] infos = new NodeInfo[] { evaluator.setSource(source) }; return new ArrayIterator(infos); } catch (Exception e) { throw new XPathException("Could not base64 decode string", e); } } Code Sample 2: public void run() { try { HttpURLConnection con = (HttpURLConnection) url.openConnection(); Osm2Model osm = new Osm2Model(pedestrian, filterCyclic); osm.progress.connect(this, "progress(int)"); osm.parseFile(con.getInputStream(), con.getContentLength()); if (osm.somethingImported()) { done.emit(); } else { nothing.emit(); } } catch (Exception e) { failed.emit(); } }
00
Code Sample 1: public Resource get(String serviceUrl, String resourceId, String svcId, boolean appendProfile) throws Exception { Resource resource = new Resource(); String openurl = getURL(serviceUrl, resourceId, svcId, appendProfile); logger.debug("OpenURL Request: " + openurl); URL url; try { url = new URL(openurl); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); int code = huc.getResponseCode(); if (code == 200) { InputStream is = huc.getInputStream(); resource.setBytes(IOUtils.getByteArray(is)); resource.setContentType(huc.getContentType()); } else if (code == 404) { return null; } else { logger.error("An error of type " + code + " occurred for " + url.toString()); throw new Exception("Cannot get " + url.toString()); } } catch (MalformedURLException e) { throw new Exception("A MalformedURLException occurred for " + openurl); } catch (IOException e) { throw new Exception("An IOException occurred attempting to connect to " + openurl); } return resource; } Code Sample 2: private Bitmap fetchImage(String urlstr) throws Exception { URL url; url = new URL(urlstr); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setDoInput(true); c.setRequestProperty("User-Agent", "Agent"); c.connect(); InputStream is = c.getInputStream(); Bitmap img; img = BitmapFactory.decodeStream(is); return img; }
11
Code Sample 1: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } } Code Sample 2: private void javaToHtml(File source, File destination) throws IOException { Reader reader = new FileReader(source); Writer writer = new FileWriter(destination); JavaUtils.writeJava(reader, writer); writer.flush(); writer.close(); }
00
Code Sample 1: public static String encryptMd5(String plaintext) { String hashtext = ""; try { MessageDigest m; m = MessageDigest.getInstance("MD5"); m.reset(); m.update(plaintext.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; } Code Sample 2: public static ArrayList[] imageSearch(String imageQuery, int startingIndex) { try { imageQuery = URLEncoder.encode(imageQuery, "UTF-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String queryS = new String(); queryS += "http://images.google.com/images?gbv=1&start=" + startingIndex + "&q=" + imageQuery; String result = ""; try { URL query = new URL(queryS); HttpURLConnection urlc = (HttpURLConnection) query.openConnection(); urlc.setInstanceFollowRedirects(true); urlc.setRequestProperty("User-Agent", ""); urlc.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream())); StringBuffer response = new StringBuffer(); char[] buffer = new char[1024]; while (true) { int charsRead = in.read(buffer); if (charsRead == -1) { break; } response.append(buffer, 0, charsRead); } in.close(); result = response.toString(); } catch (Exception e) { e.printStackTrace(); } ArrayList<String> thumbs = new ArrayList<String>(); ArrayList<String> imgs = new ArrayList<String>(); Matcher m = imgBlock.matcher(result); while (m.find()) { String s = m.group(); Matcher imgM = imgurl.matcher(s); imgM.find(); String url = imgM.group(1); Matcher srcM = imgsrc.matcher(s); srcM.find(); String thumb = srcM.group(1); thumbs.add(thumb); imgs.add(url); } return new ArrayList[] { thumbs, imgs }; }
11
Code Sample 1: public void copy(final File source, final File target) throws FileSystemException { LogHelper.logMethod(log, toObjectString(), "copy(), source = " + source + ", target = " + target); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); sourceChannel.transferTo(0L, sourceChannel.size(), targetChannel); log.info("Copied " + source + " to " + target); } catch (FileNotFoundException e) { throw new FileSystemException("Unexpected FileNotFoundException while copying a file", e); } catch (IOException e) { throw new FileSystemException("Unexpected IOException while copying a file", e); } finally { if (sourceChannel != null) { try { sourceChannel.close(); } catch (IOException e) { log.error("IOException during source channel close after copy", e); } } if (targetChannel != null) { try { targetChannel.close(); } catch (IOException e) { log.error("IOException during target channel close after copy", e); } } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: public void elimina(Cliente cli) throws errorSQL, errorConexionBD { System.out.println("GestorCliente.elimina()"); int id = cli.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM cliente WHERE cod_cliente =" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); sql = "DELETE FROM persona WHERE id =" + id; System.out.println("Ejecutando: " + sql); stmt.executeUpdate(sql); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorCliente.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorCliente.elimina(): " + e); } } Code Sample 2: public static String md5Encrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] md5hash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } md5hash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < md5hash.length; i++) { if (Integer.toHexString(0xFF & md5hash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & md5hash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & md5hash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; }
00
Code Sample 1: public ODFSignatureService(TimeStampServiceValidator timeStampServiceValidator, RevocationDataService revocationDataService, SignatureFacet signatureFacet, InputStream documentInputStream, OutputStream documentOutputStream, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo digestAlgo) throws Exception { super(digestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".odf"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } } Code Sample 2: public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) { res += "0" + tmp; } else { res += tmp; } } } catch (NoSuchAlgorithmException ex) { if (globali.jcVariabili.DEBUG) globali.jcFunzioni.erroreSQL(ex.toString()); } return res; }
00
Code Sample 1: 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: @Override public Object getImage(String key) { if (key.indexOf("exhibition/") != -1) { InputStream inputStream = null; try { URL url = new URL(getBaseURL() + "icons/" + key + ".png"); inputStream = url.openStream(); return url; } catch (Exception e) { } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); } } } } return super.getImage(key); }
11
Code Sample 1: public static Image loadImage(String path) { ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = mainFrame.getClass().getResourceAsStream(path); if (in == null) throw new RuntimeException("Ressource " + path + " not found"); try { IOUtils.copy(in, out); in.close(); out.flush(); } catch (IOException e) { e.printStackTrace(); new RuntimeException("Error reading ressource " + path, e); } return Toolkit.getDefaultToolkit().createImage(out.toByteArray()); } Code Sample 2: private void fileCopy(File filename) throws IOException { if (this.stdOut) { this.fileDump(filename); return; } File source_file = new File(spoolPath + "/" + filename); File destination_file = new File(copyPath + "/" + filename); FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; try { if (!source_file.exists() || !source_file.isFile()) throw new FileCopyException("no such source file: " + source_file); if (!source_file.canRead()) throw new FileCopyException("source file is unreadable: " + source_file); if (destination_file.exists()) { if (destination_file.isFile()) { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); if (!destination_file.canWrite()) throw new FileCopyException("destination file is unwriteable: " + destination_file); if (!this.overwrite) { System.out.print("File " + destination_file + " already exists. Overwrite? (Y/N): "); System.out.flush(); if (!in.readLine().toUpperCase().equals("Y")) throw new FileCopyException("copy cancelled."); } } else throw new FileCopyException("destination is not a file: " + destination_file); } else { File parentdir = parent(destination_file); if (!parentdir.exists()) throw new FileCopyException("destination directory doesn't exist: " + destination_file); if (!parentdir.canWrite()) throw new FileCopyException("destination directory is unwriteable: " + destination_file); } source = new FileInputStream(source_file); destination = new FileOutputStream(destination_file); buffer = new byte[1024]; while ((bytes_read = source.read(buffer)) != -1) { destination.write(buffer, 0, bytes_read); } System.out.println("File " + filename + " successfull copied to " + destination_file); if (this.keep == false && source_file.isFile()) { try { source.close(); } catch (Exception e) { } if (source_file.delete()) { new File(this.spoolPath + "/info/" + filename + ".desc").delete(); } } } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.flush(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } }
11
Code Sample 1: public static ResultSet execute(String commands) { ResultSet rs = null; BufferedReader reader = new BufferedReader(new StringReader(commands)); String sqlCommand = null; Connection conn = ConnPool.getConnection(); try { Statement stmt = conn.createStatement(); while ((sqlCommand = reader.readLine()) != null) { sqlCommand = sqlCommand.toLowerCase().trim(); if (sqlCommand.equals("") || sqlCommand.startsWith("#")) { continue; } if (dmaLogger.isInfoEnabled(SqlExecutor.class)) { dmaLogger.logInfo("Executing SQL: " + sqlCommand, SqlExecutor.class); } long currentTimeMillis = System.currentTimeMillis(); if (sqlCommand.startsWith("select")) { rs = stmt.executeQuery(sqlCommand); } else { stmt.executeUpdate(sqlCommand); } dmaLogger.logInfo(DateUtil.getElapsedTime("SQL execution of " + sqlCommand + " took: ", (System.currentTimeMillis() - currentTimeMillis)), SqlExecutor.class); } if (rs == null) { stmt.close(); } return rs; } catch (SQLException e) { try { conn.rollback(); } catch (SQLException se) { } throw new RuntimeException("Execution of " + sqlCommand + " failed:" + e.getMessage(), e); } catch (IOException e) { try { conn.rollback(); } catch (SQLException se) { } throw new RuntimeException("Execution of " + sqlCommand + " failed:", e); } finally { ConnPool.releaseConnection(conn); } } Code Sample 2: public ProjectDeploymentConfiguration deleteProjectDeploymentConfig(int id) throws AdaptationException { ProjectDeploymentConfiguration config = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "SELECT * FROM ProjectDeploymentConfigurations " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to delete project deployment " + "configuration failed."; log.error(msg); throw new AdaptationException(msg); } config = getProjectDeploymentConfiguration(resultSet); query = "DELETE FROM ProjectDeploymentConfigurations " + "WHERE id = " + id; statement.executeUpdate(query); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in deleteProjectDeploymentConfig"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return config; }
11
Code Sample 1: public void copyFileFromLocalMachineToRemoteMachine(InputStream source, File destination) throws Exception { String fileName = destination.getPath(); File f = new File(getFtpServerHome(), "" + System.currentTimeMillis()); f.deleteOnExit(); org.apache.commons.io.IOUtils.copy(source, new FileOutputStream(f)); remoteHostClient.setAscii(isAscii()); remoteHostClient.setPromptOn(isPrompt()); remoteHostClient.copyFileFromLocalMachineToRemoteClient(f.getName(), fileName); } Code Sample 2: public void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
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 run() { Pair p = null; try { while ((p = queue.pop()) != null) { GetMethod get = new GetMethod(p.getRemoteUri()); try { get.setFollowRedirects(true); get.setRequestHeader("Mariner-Application", "prerenderer"); get.setRequestHeader("Mariner-DeviceName", deviceName); int iGetResultCode = httpClient.executeMethod(get); if (iGetResultCode != 200) { throw new IOException("Got response code " + iGetResultCode + " for a request for " + p.getRemoteUri()); } InputStream is = get.getResponseBodyAsStream(); File localFile = new File(deviceFile, p.getLocalUri()); localFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(localFile); IOUtils.copy(is, os); os.close(); } finally { get.releaseConnection(); } } } catch (Exception ex) { result = ex; } }
11
Code Sample 1: public static void createZipFromDataset(String localResourceId, File dataset, File metadata) { CommunicationLogger.warning("System entered ZipFactory"); try { String tmpDir = System.getProperty("java.io.tmpdir"); String outFilename = tmpDir + "/" + localResourceId + ".zip"; CommunicationLogger.warning("File name: " + outFilename); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename)); byte[] buf = new byte[1024]; FileInputStream in = new FileInputStream(dataset); out.putNextEntry(new ZipEntry(dataset.getName())); int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in = new FileInputStream(metadata); out.putNextEntry(new ZipEntry(metadata.getName())); while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.closeEntry(); in.close(); out.close(); } catch (IOException e) { System.out.println("IO EXCEPTION: " + e.getMessage()); } } Code Sample 2: public String merge(int width, int height) throws Exception { htErrors.clear(); sendGetImageRequests(width, height); Vector files = new Vector(); ConcurrentHTTPTransactionHandler c = new ConcurrentHTTPTransactionHandler(); c.setCache(cache); c.checkIfModified(false); for (int i = 0; i < vImageUrls.size(); i++) { if ((String) vImageUrls.get(i) != null) { c.register((String) vImageUrls.get(i)); } else { } } c.doTransactions(); vTransparency = new Vector(); for (int i = 0; i < vImageUrls.size(); i++) { if (vImageUrls.get(i) != null) { String path = c.getResponseFilePath((String) vImageUrls.get(i)); if (path != null) { String contentType = c.getHeaderValue((String) vImageUrls.get(i), "content-type"); if (contentType.startsWith("image")) { files.add(path); vTransparency.add(htTransparency.get(vRank.get(i))); } } } } if (files.size() > 1) { File output = TempFiles.getFile(); String path = output.getPath(); ImageMerger.mergeAndSave(files, vTransparency, path, ImageMerger.GIF); imageName = output.getName(); imagePath = output.getPath(); return (imageName); } else if (files.size() == 1) { File f = new File((String) files.get(0)); File out = TempFiles.getFile(); BufferedInputStream is = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(out)); byte buf[] = new byte[1024]; for (int nRead; (nRead = is.read(buf, 0, 1024)) > 0; os.write(buf, 0, nRead)) ; os.flush(); os.close(); is.close(); imageName = out.getName(); return imageName; } else return ""; }
11
Code Sample 1: @Override public User login(String username, String password) { User user = null; try { user = (User) em.createQuery("Select o from User o where o.username = :username").setParameter("username", username).getSingleResult(); } catch (NoResultException e) { throw new NestedException(e.getMessage(), e); } try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(password.getBytes("UTF-8")); byte[] hash = digest.digest(); BigInteger bigInt = new BigInteger(1, hash); String hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } if (hashtext.equals(user.getPassword())) return user; } catch (Exception e) { throw new NestedException(e.getMessage(), e); } return null; } Code Sample 2: public static String md5(String text) { MessageDigest msgDigest = null; try { msgDigest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("System doesn't support MD5 algorithm."); } try { msgDigest.update(text.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("System doesn't support your EncodingException."); } byte[] bytes = msgDigest.digest(); String md5Str = new String(encodeHex(bytes)); return md5Str; }
00
Code Sample 1: public static String send(String ipStr, int port, String password, String command, InetAddress localhost, int localPort) throws SocketTimeoutException, BadRcon, ResponseEmpty { StringBuffer response = new StringBuffer(); try { rconSocket = new Socket(); rconSocket.bind(new InetSocketAddress(localhost, localPort)); rconSocket.connect(new InetSocketAddress(ipStr, port), RESPONSE_TIMEOUT); out = rconSocket.getOutputStream(); in = rconSocket.getInputStream(); BufferedReader buffRead = new BufferedReader(new InputStreamReader(in)); rconSocket.setSoTimeout(RESPONSE_TIMEOUT); String digestSeed = ""; boolean loggedIn = false; boolean keepGoing = true; while (keepGoing) { String receivedContent = buffRead.readLine(); if (receivedContent.startsWith("### Digest seed: ")) { digestSeed = receivedContent.substring(17, receivedContent.length()); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(digestSeed.getBytes()); md5.update(password.getBytes()); String digestStr = "login " + digestedToHex(md5.digest()) + "\n"; out.write(digestStr.getBytes()); } catch (NoSuchAlgorithmException e1) { response.append("MD5 algorithm not available - unable to complete RCON request."); keepGoing = false; } } else if (receivedContent.startsWith("error: not authenticated: you can only invoke 'login'")) { throw new BadRcon(); } else if (receivedContent.startsWith("Authentication failed.")) { throw new BadRcon(); } else if (receivedContent.startsWith("Authentication successful, rcon ready.")) { keepGoing = false; loggedIn = true; } } if (loggedIn) { String cmd = "exec " + command + "\n"; out.write(cmd.getBytes()); readResponse(buffRead, response); if (response.length() == 0) { throw new ResponseEmpty(); } } } catch (SocketTimeoutException timeout) { throw timeout; } catch (UnknownHostException e) { response.append("UnknownHostException: " + e.getMessage()); } catch (IOException e) { response.append("Couldn't get I/O for the connection: " + e.getMessage()); e.printStackTrace(); } finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } if (rconSocket != null) { rconSocket.close(); } } catch (IOException e1) { } } return response.toString(); } 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 void store(Component component, String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("UPDATE component_prop " + "SET size_height = ?, size_width = ?, pos_x = ?, pos_y = ? " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); Point point = component.getLocation(); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); int update = psta.executeUpdate(); if (update == 0) { psta = jdbc.prepareStatement("INSERT INTO component_prop " + "(size_height, size_width, pos_x, pos_y, pilot_id, component_name) " + "VALUES (?,?,?,?,?,?)"); psta.setInt(1, component.getHeight()); psta.setInt(2, component.getWidth()); psta.setInt(3, point.x); psta.setInt(4, point.y); psta.setInt(5, currentPilot); psta.setString(6, componentName); psta.executeUpdate(); } jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } Code Sample 2: public Document parse(Document document) { CSSCompilerBuilder compilerBuilder = new CSSCompilerBuilder(); StyleSheetCompilerFactory compilerFactory = getStyleSheetCompilerFactory(); compilerBuilder.setStyleSheetCompilerFactory(compilerFactory); CSSCompiler cssCompiler = compilerBuilder.getCSSCompiler(); CompiledStyleSheet defaultCompiledStyleSheet; try { URL url = getClass().getResource("/com/volantis/mcs/runtime/default.css"); InputStream stream = url.openStream(); defaultCompiledStyleSheet = cssCompiler.compile(new InputStreamReader(stream), null); } catch (IOException e) { throw new ExtendedRuntimeException(e); } StylingFactory stylingFactory = StylingFactory.getDefaultInstance(); StylingEngine stylingEngine = stylingFactory.createStylingEngine(new InlineStyleSheetCompilerFactory(StylingFunctions.getResolver())); stylingEngine.pushStyleSheet(defaultCompiledStyleSheet); DocumentStyler styler = new DocumentStyler(stylingEngine, XDIMESchemata.CDM_NAMESPACE); styler.style(document); DOMWalker walker = new DOMWalker(new WalkingDOMVisitorStub() { public void visit(Element element) { if (element.getStyles() == null) { throw new IllegalArgumentException("element " + element.getName() + " has no styles"); } } }); walker.walk(document); DOMTransformer transformer = new DeferredInheritTransformer(); document = transformer.transform(null, document); return document; }
11
Code Sample 1: public static synchronized String hash(String plaintext) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { return null; } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return null; } byte raw[] = md.digest(); return (new BASE64Encoder()).encode(raw); } Code Sample 2: public synchronized String encrypt(String plaintext) throws SystemUnavailableException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new SystemUnavailableException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new SystemUnavailableException(e.getMessage()); } byte raw[] = md.digest(); String hash = new Base64().encodeAsString(raw); return hash; }
00
Code Sample 1: public void testIsVersioned() throws ServiceException, IOException { JCRNodeSource emptySource = loadTestSource(); assertTrue(emptySource.isVersioned()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } assertTrue(emptySource.isVersioned()); } Code Sample 2: public static boolean init(String language) { URL url = S.class.getResource("strings_" + language + ".txt"); strings = new Properties(); try { strings.load(url.openStream()); } catch (Exception e) { String def = "en"; if (language.equals(def)) return false; return init(def); } ; return true; }
00
Code Sample 1: public String getNextObjectId() throws SQLException { long nextserial = 1; String s0 = "lock table serials in exclusive mode"; String s1 = "SELECT nextserial FROM serials WHERE tablename = 'SERVER_OIDS'"; String s2; try { Statement stmt = dbconnect.connection.createStatement(); stmt.executeUpdate(s0); ResultSet rs = stmt.executeQuery(s1); if (!rs.next()) { s2 = "insert into serials (tablename,nextserial) values ('SERVER_OIDS', " + (nextserial) + ")"; } else { nextserial = rs.getLong(1) + 1; s2 = "update serials set nextserial=" + (nextserial) + " where tablename='SERVER_OIDS'"; } stmt.executeUpdate(s2); dbconnect.connection.commit(); rs.close(); stmt.close(); return "" + nextserial; } catch (SQLException e) { dbconnect.connection.rollback(); throw e; } } Code Sample 2: @SuppressWarnings("unchecked") public static <T extends Class> Collection<T> listServices(T serviceType, ClassLoader classLoader) throws IOException, ClassNotFoundException { final Collection<T> result = new LinkedHashSet<T>(); final Enumeration<URL> resouces = classLoader.getResources("META-INF/services/" + serviceType.getName()); while (resouces.hasMoreElements()) { final URL url = resouces.nextElement(); final BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String line = reader.readLine(); while (line != null) { if (line.startsWith("#")) { } else if ("".equals(line.trim())) { } else { final T implClass = (T) Class.forName(line, true, classLoader); if (!serviceType.isAssignableFrom(implClass)) { throw new IllegalStateException(String.format("%s: class %s does not implement required interfafce %s", url, implClass, serviceType)); } result.add(implClass); } line = reader.readLine(); } } finally { reader.close(); } } return result; }
11
Code Sample 1: private void execute(String file, String[] ebms, String[] eems, String[] ims, String[] efms) throws BuildException { if (verbose) { System.out.println("Preprocessing file " + file + " (type: " + type + ")"); } try { File targetFile = new File(file); FileReader fr = new FileReader(targetFile); BufferedReader reader = new BufferedReader(fr); File preprocFile = File.createTempFile(targetFile.getName(), "tmp", targetFile.getParentFile()); FileWriter fw = new FileWriter(preprocFile); BufferedWriter writer = new BufferedWriter(fw); int result = preprocess(reader, writer, ebms, eems, ims, efms); reader.close(); writer.close(); switch(result) { case OVERWRITE: if (!targetFile.delete()) { System.out.println("Can't overwrite target file with preprocessed file"); throw new BuildException("Can't overwrite target file " + target + " with preprocessed file"); } preprocFile.renameTo(targetFile); if (verbose) { System.out.println("File " + preprocFile.getName() + " modified."); } modifiedCnt++; break; case REMOVE: if (!targetFile.delete()) { System.out.println("Can't delete target file"); throw new BuildException("Can't delete target file " + target); } if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } if (verbose) { System.out.println("File " + preprocFile.getName() + " removed."); } removedCnt++; break; case KEEP: if (!preprocFile.delete()) { System.out.println("Can't delete temporary preprocessed file " + preprocFile.getName()); throw new BuildException("Can't delete temporary preprocessed file " + preprocFile.getName()); } break; default: throw new BuildException("Unexpected preprocessing result for file " + preprocFile.getName()); } } catch (Exception e) { e.printStackTrace(); throw new BuildException(e.getMessage()); } } Code Sample 2: protected void copyDependents() { for (File source : dependentFiles.keySet()) { try { if (!dependentFiles.get(source).exists()) { if (dependentFiles.get(source).isDirectory()) dependentFiles.get(source).mkdirs(); else dependentFiles.get(source).getParentFile().mkdirs(); } IOUtils.copyEverything(source, dependentFiles.get(source)); } catch (IOException e) { e.printStackTrace(); } } }
00
Code Sample 1: public static String encryptMd5(String plaintext) { String hashtext = ""; try { MessageDigest m; m = MessageDigest.getInstance("MD5"); m.reset(); m.update(plaintext.getBytes()); byte[] digest = m.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; } Code Sample 2: private void loadServers() { try { URL url = new URL(VirtualDeckConfig.SERVERS_URL); cmbServer.addItem("Local"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; if (in.readLine().equals("[list]")) { while ((str = in.readLine()) != null) { String[] host_line = str.split(";"); Host h = new Host(); h.setIp(host_line[0]); h.setPort(Integer.parseInt(host_line[1])); h.setName(host_line[2]); getServers().add(h); cmbServer.addItem(h.getName()); } } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
00
Code Sample 1: private static void salvarObra(Artista artista, Obra obra) throws Exception { Connection conn = null; PreparedStatement ps = null; int categoria; System.out.println("Migracao.salvarObra() obra: " + obra.toString2()); if (obra.getCategoria() != null) { categoria = getCategoria(obra.getCategoria().getNome()).getCodigo(); } else { categoria = getCategoria("Sem Categoria").getCodigo(); } try { conn = C3P0Pool.getConnection(); String sql = "insert into obra VALUES (?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setNull(1, Types.INTEGER); ps.setString(2, obra.getTitulo()); ps.setInt(3, obra.getSelec()); ps.setInt(4, categoria); ps.setInt(5, artista.getNumeroInscricao()); ps.setInt(6, obra.getCodigo()); ps.executeUpdate(); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: public Object run() { List correctUsers = (List) JsonPath.query("select * from ? where name=?", usersTable(), username); if (correctUsers.size() == 0) { return new LoginException("user " + username + " not found"); } Persistable userObject = (Persistable) correctUsers.get(0); boolean alreadyHashed = false; boolean passwordMatch = password.equals(userObject.get(PASSWORD_FIELD)); if (!passwordMatch) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(((String) userObject.get(PASSWORD_FIELD)).getBytes()); passwordMatch = password.equals(new String(new Base64().encode(md.digest()))); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } alreadyHashed = true; } if (passwordMatch) { Logger.getLogger(User.class.toString()).info("User " + username + " has been authenticated"); User user = (User) userObject; try { if (alreadyHashed) user.currentTicket = password; else { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes()); user.currentTicket = new String(new Base64().encode(md.digest())); } } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } return user; } else { Logger.getLogger(User.class.toString()).info("The password was incorrect for " + username); return new LoginException("The password was incorrect for user " + username + ". "); } }
00
Code Sample 1: public String md5Encode(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(pass.getBytes()); byte[] result = md.digest(); return new String(result); } Code Sample 2: private static boolean genMovieRatingFile(String completePath, String masterFile, String CustLocationsFileName, String MovieRatingFileName) { try { File inFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC1 = new FileInputStream(inFile1).getChannel(); int fileSize1 = (int) inC1.size(); int totalNoDataRows = fileSize1 / 7; ByteBuffer mappedBuffer = inC1.map(FileChannel.MapMode.READ_ONLY, 0, fileSize1); System.out.println("Loaded master binary file"); File inFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel inC2 = new FileInputStream(inFile2).getChannel(); int fileSize2 = (int) inC2.size(); System.out.println(fileSize2); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieRatingFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); for (int i = 0; i < 1; i++) { ByteBuffer locBuffer = inC2.map(FileChannel.MapMode.READ_ONLY, i * fileSize2, fileSize2); System.out.println("Loaded cust location file chunk: " + i); while (locBuffer.hasRemaining()) { int locationToRead = locBuffer.getInt(); mappedBuffer.position((locationToRead - 1) * 7); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); ByteBuffer outBuf = ByteBuffer.allocate(3); outBuf.putShort(movieName); outBuf.put(rating); outBuf.flip(); outC.write(outBuf); } } mappedBuffer.clear(); inC1.close(); inC2.close(); outC.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
11
Code Sample 1: @Deprecated public boolean backupLuceneIndex(int indexLocation, int backupLocation) { boolean result = false; try { System.out.println("lucene backup started"); String indexPath = this.getIndexFolderPath(indexLocation); String backupPath = this.getIndexFolderPath(backupLocation); File inDir = new File(indexPath); boolean flag = true; if (inDir.exists() && inDir.isDirectory()) { File filesList[] = inDir.listFiles(); if (filesList != null) { File parDirBackup = new File(backupPath); if (!parDirBackup.exists()) parDirBackup.mkdir(); String date = this.getDate(); backupPath += "/" + date; File dirBackup = new File(backupPath); if (!dirBackup.exists()) dirBackup.mkdir(); else { File files[] = dirBackup.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { if (files[i] != null) { files[i].delete(); } } } dirBackup.delete(); dirBackup.mkdir(); } for (int i = 0; i < filesList.length; i++) { if (filesList[i].isFile()) { try { File destFile = new File(backupPath + "/" + filesList[i].getName()); if (!destFile.exists()) destFile.createNewFile(); FileInputStream in = new FileInputStream(filesList[i]); FileOutputStream out = new FileOutputStream(destFile); FileChannel fcIn = in.getChannel(); FileChannel fcOut = out.getChannel(); fcIn.transferTo(0, fcIn.size(), fcOut); } catch (FileNotFoundException ex) { System.out.println("FileNotFoundException ---->" + ex); flag = false; } catch (IOException excIO) { System.out.println("IOException ---->" + excIO); flag = false; } } } } } System.out.println("lucene backup finished"); System.out.println("flag ========= " + flag); if (flag) { result = true; } } catch (Exception e) { System.out.println("Exception in backupLuceneIndex Method : " + e); e.printStackTrace(); } return result; } Code Sample 2: @Override public synchronized File download_dictionary(Dictionary dict, String localfpath) { abort = false; try { URL dictionary_location = new URL(dict.getLocation()); InputStream in = dictionary_location.openStream(); FileOutputStream w = new FileOutputStream(local_cache, false); int b = 0; while ((b = in.read()) != -1) { w.write(b); if (abort) throw new Exception("Download Aborted"); } in.close(); w.close(); File lf = new File(localfpath); FileInputStream r = new FileInputStream(local_cache); FileOutputStream fw = new FileOutputStream(lf); int c; while ((c = r.read()) != -1) fw.write(c); r.close(); fw.close(); clearCache(); return lf; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InvalidTupleOperationException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } clearCache(); return null; }
11
Code Sample 1: @Override public Object execute(ExecutionEvent event) throws ExecutionException { URL url; try { url = new URL("platform:/plugin/de.vogella.rcp.plugin.filereader/files/test.txt"); InputStream inputStream = url.openConnection().getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (IOException e) { e.printStackTrace(); } return null; } Code Sample 2: private void setup() { env = new EnvAdvanced(); try { URL url = Sysutil.getURL("world.env"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { String[] fields = line.split(","); if (fields[0].equalsIgnoreCase("skybox")) { env.setRoom(new EnvSkyRoom(fields[1])); } else if (fields[0].equalsIgnoreCase("camera")) { env.setCameraXYZ(Double.parseDouble(fields[1]), Double.parseDouble(fields[2]), Double.parseDouble(fields[3])); env.setCameraYaw(Double.parseDouble(fields[4])); env.setCameraPitch(Double.parseDouble(fields[5])); } else if (fields[0].equalsIgnoreCase("terrain")) { terrain = new EnvTerrain(fields[1]); terrain.setTexture(fields[2]); env.addObject(terrain); } else if (fields[0].equalsIgnoreCase("object")) { GameObject n = (GameObject) Class.forName(fields[10]).newInstance(); n.setX(Double.parseDouble(fields[1])); n.setY(Double.parseDouble(fields[2])); n.setZ(Double.parseDouble(fields[3])); n.setScale(Double.parseDouble(fields[4])); n.setRotateX(Double.parseDouble(fields[5])); n.setRotateY(Double.parseDouble(fields[6])); n.setRotateZ(Double.parseDouble(fields[7])); n.setTexture(fields[9]); n.setModel(fields[8]); n.setEnv(env); env.addObject(n); } } } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public void actionPerformed(ActionEvent e) { if (e.getSource() == cancel) { email.setText(""); name.setText(""); category.setSelectedIndex(0); subject.setText(""); message.setText(""); setVisible(false); } else { StringBuffer errors = new StringBuffer(); if (email.getText().trim().equals("")) errors.append("El campo 'Email' es obligatorio<br/>"); if (name.getText().trim().equals("")) errors.append("El campo 'Nombre' es obligatorio<br/>"); if (subject.getText().trim().equals("")) errors.append("El campo 'T�tulo' es obligatorio<br/>"); if (message.getText().trim().equals("")) errors.append("No hay conrtenido en el mensaje<br/>"); if (errors.length() > 0) { JOptionPane.showMessageDialog(this, "<html><b>Error</b><br/>" + errors.toString() + "</html>", "Error", JOptionPane.ERROR_MESSAGE); } else { try { StringBuffer params = new StringBuffer(); params.append("name=").append(URLEncoder.encode(name.getText(), "UTF-8")).append("&category=").append(URLEncoder.encode((String) category.getSelectedItem(), "UTF-8")).append("&title=").append(URLEncoder.encode(subject.getText(), "UTF-8")).append("&email=").append(URLEncoder.encode(email.getText(), "UTF-8")).append("&id=").append(URLEncoder.encode(MainWindow.getUserPreferences().getUniqueId() + "", "UTF-8")).append("&body=").append(URLEncoder.encode(message.getText(), "UTF-8")); URL url = new URL("http://www.cronopista.com/diccionario2/sendMessage.php"); URLConnection connection = url.openConnection(); Utils.setupProxy(connection); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(params.toString()); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String decodedString; while ((decodedString = in.readLine()) != null) { System.out.println(decodedString); } in.close(); email.setText(""); name.setText(""); category.setSelectedIndex(0); subject.setText(""); message.setText(""); setVisible(false); } catch (Exception ex) { JOptionPane.showMessageDialog(this, "<html><b>Error</b><br/>Ha ocurrido un error enviando tu mensaje.<br/>" + "Por favor, int�ntalo m�s tarde o ponte en contacto conmigo a trav�s de www.cronopista.com</html>", "Error", JOptionPane.ERROR_MESSAGE); } } } } Code Sample 2: public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { URL url = configuration.get(publicID); try { if (url != null) return url.openStream(); } catch (IOException ex) { throw new XMLStreamException(String.format("Unable to open stream for resource %s: %s", url, InternalUtils.toMessage(ex)), ex); } return null; }
11
Code Sample 1: public static void copyFile(String source, String destination, boolean overwrite) { File sourceFile = new File(source); try { File destinationFile = new File(destination); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destinationFile)); int temp = 0; while ((temp = bis.read()) != -1) bos.write(temp); bis.close(); bos.close(); } catch (Exception e) { } return; } Code Sample 2: public static void compress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new BufferedInputStream(new FileInputStream(srcFile)); output = new GZIPOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
11
Code Sample 1: private static void generateFile(String inputFilename, String outputFilename) throws Exception { File inputFile = new File(inputFilename); if (inputFile.exists() == false) { throw new Exception(Messages.getString("ScriptDocToBinary.Input_File_Does_Not_Exist") + inputFilename); } Environment environment = new Environment(); environment.initBuiltInObjects(); NativeObjectsReader reader = new NativeObjectsReader(environment); InputStream input = new FileInputStream(inputFile); System.out.println(Messages.getString("ScriptDocToBinary.Reading_Documentation") + inputFilename); reader.loadXML(input); checkFile(outputFilename); File binaryFile = new File(outputFilename); FileOutputStream outputStream = new FileOutputStream(binaryFile); TabledOutputStream output = new TabledOutputStream(outputStream); reader.getScriptDoc().write(output); output.close(); System.out.println(Messages.getString("ScriptDocToBinary.Finished")); System.out.println(); } Code Sample 2: public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } }
00
Code Sample 1: public void reset(String componentName, int currentPilot) { try { PreparedStatement psta = jdbc.prepareStatement("DELETE FROM component_prop " + "WHERE pilot_id = ? " + "AND component_name = ?"); psta.setInt(1, currentPilot); psta.setString(2, componentName); psta.executeUpdate(); jdbc.commit(); } catch (SQLException e) { jdbc.rollback(); log.debug(e); } } 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: public String md5(String string) throws GeneralSecurityException { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(string.getBytes()); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } 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; }
11
Code Sample 1: protected String encrypt(final String data, final String key) throws CryptographicFailureException { Validate.notNull(data, "Provided data cannot be null."); Validate.notNull(key, "Provided key name cannot be null."); final PublicKey pk = getPublicKey(key); if (pk == null) { throw new CryptographicFailureException("PublicKeyNotFound", String.format("Cannot find public key '%s'", key)); } try { final Cipher cipher = Cipher.getInstance(pk.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, pk); final ByteArrayInputStream bin = new ByteArrayInputStream(data.getBytes()); final CipherInputStream cin = new CipherInputStream(bin, cipher); final ByteArrayOutputStream bout = new ByteArrayOutputStream(); IOUtils.copy(cin, bout); return new String(Base64.encodeBase64(bout.toByteArray())); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(String.format("Cannot find instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (NoSuchPaddingException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (InvalidKeyException e) { throw new IllegalStateException(String.format("Cannot build instance of algorithm '%s'", pk.getAlgorithm()), e); } catch (IOException e) { throw new IllegalStateException("Cannot build in-memory cipher copy", e); } } Code Sample 2: public boolean backupLastAuditSchema(File lastAuditSchema) { boolean isBkupFileOK = false; String writeTimestamp = DateFormatUtils.format(new java.util.Date(), configFile.getTimestampPattern()); File target = new File(configFile.getAuditSchemaFileDir() + File.separator + configFile.getAuditSchemaFileName() + ".bkup_" + writeTimestamp); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(lastAuditSchema).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((target != null) && (target.exists()) && (target.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } return isBkupFileOK; }
11
Code Sample 1: public String getTextData() { if (tempFileWriter != null) { try { tempFileWriter.flush(); tempFileWriter.close(); FileReader in = new FileReader(tempFile); StringWriter out = new StringWriter(); int len; char[] buf = new char[BUFSIZ]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); out.close(); in.close(); return out.toString(); } catch (IOException ioe) { Logger.instance().log(Logger.ERROR, LOGGER_PREFIX, "XMLTextData.getTextData", ioe); return ""; } } else if (textBuffer != null) return textBuffer.toString(); else return null; } Code Sample 2: public static void copyFile(File srcFile, File desFile) throws IOException { AssertUtility.notNull(srcFile); AssertUtility.notNull(desFile); FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(desFile); try { FileChannel srcChannel = fis.getChannel(); FileChannel dstChannel = fos.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } finally { fis.close(); fos.close(); } }
00
Code Sample 1: public static String BaiKe(String unknown) { String encodeurl = ""; long sTime = System.currentTimeMillis(); long eTime; try { String regEx = "\\#(.+)\\#"; String searchText = ""; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(unknown); if (m.find()) { searchText = m.group(1); } System.out.println("searchText : " + searchText); encodeurl = URLEncoder.encode(searchText, "UTF-8"); String url = "http://www.hudong.com/wiki/" + encodeurl; HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setConnectTimeout(10000); Parser parser = new Parser(conn); parser.setEncoding(parser.getEncoding()); NodeFilter filtera = new TagNameFilter("DIV"); NodeList nodes = parser.extractAllNodesThatMatch(filtera); String textInPage = ""; if (nodes != null) { for (int i = 0; i < nodes.size(); i++) { Node textnode = (Node) nodes.elementAt(i); if ("div class=\"summary\"".equals(textnode.getText())) { String temp = textnode.toPlainTextString(); textInPage += temp + "\n"; } } } String s = Replace(textInPage, searchText); eTime = System.currentTimeMillis(); String time = "搜索[" + searchText + "]用时:" + (eTime - sTime) / 1000.0 + "s"; System.out.println(s); return time + "\r\n" + s; } catch (Exception e) { e.printStackTrace(); return "大姨妈来了"; } } Code Sample 2: public File getAppHome() { if (appHome == null) { if (System.getProperty("app.home") != null) { appHome = new File(System.getProperty("app.home")); } if (appHome == null) { URL url = Main.class.getClassLoader().getResource("com/hs/mail/container/Main.class"); if (url != null) { try { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); url = jarConnection.getJarFileURL(); URI baseURI = new URI(url.toString()).resolve(".."); appHome = new File(baseURI).getCanonicalFile(); System.setProperty("app.home", appHome.getAbsolutePath()); } catch (Exception ignored) { } } } if (appHome == null) { appHome = new File("../."); System.setProperty("app.home", appHome.getAbsolutePath()); } } return appHome; }
00
Code Sample 1: @Override public void run() { File dir = new File(loggingDir); if (!dir.isDirectory()) { logger.error("Logging directory \"" + dir.getAbsolutePath() + "\" does not exist."); return; } File file = new File(dir, new Date().toString().replaceAll("[ ,:]", "") + "LoadBalancerLog.txt"); FileWriter writer; try { writer = new FileWriter(file); } catch (IOException e) { e.printStackTrace(); return; } int counter = 0; while (!isInterrupted() && counter < numProbes) { try { writer.write(System.currentTimeMillis() + "," + currentPending + "," + currentThreads + "," + droppedTasks + "," + executionExceptions + "," + currentWeight + "," + averageWaitTime + "," + averageExecutionTime + "#"); writer.flush(); } catch (IOException e) { e.printStackTrace(); break; } counter++; try { sleep(probeTime); } catch (InterruptedException e) { e.printStackTrace(); break; } } try { writer.close(); } catch (IOException e) { e.printStackTrace(); return; } FileReader reader; try { reader = new FileReader(file); } catch (FileNotFoundException e2) { e2.printStackTrace(); return; } Vector<StatStorage> dataV = new Vector<StatStorage>(); int c; try { c = reader.read(); } catch (IOException e1) { e1.printStackTrace(); c = -1; } String entry = ""; Date startTime = null; Date stopTime = null; while (c != -1) { if (c == 35) { String parts[] = entry.split(","); if (startTime == null) startTime = new Date(Long.parseLong(parts[0])); if (parts.length > 0) dataV.add(parse(parts)); stopTime = new Date(Long.parseLong(parts[0])); entry = ""; } else { entry += (char) c; } try { c = reader.read(); } catch (IOException e) { e.printStackTrace(); } } try { reader.close(); } catch (IOException e) { e.printStackTrace(); } if (dataV.size() > 0) { int[] dataPending = new int[dataV.size()]; int[] dataOccupied = new int[dataV.size()]; long[] dataDropped = new long[dataV.size()]; long[] dataException = new long[dataV.size()]; int[] dataWeight = new int[dataV.size()]; long[] dataExecution = new long[dataV.size()]; long[] dataWait = new long[dataV.size()]; for (int i = 0; i < dataV.size(); i++) { dataPending[i] = dataV.get(i).pending; dataOccupied[i] = dataV.get(i).occupied; dataDropped[i] = dataV.get(i).dropped; dataException[i] = dataV.get(i).exceptions; dataWeight[i] = dataV.get(i).currentWeight; dataExecution[i] = (long) dataV.get(i).executionTime; dataWait[i] = (long) dataV.get(i).waitTime; } String startName = startTime.toString(); startName = startName.replaceAll("[ ,:]", ""); file = new File(dir, startName + "pending.gif"); SimpleChart.drawChart(file, 640, 480, dataPending, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "occupied.gif"); SimpleChart.drawChart(file, 640, 480, dataOccupied, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "dropped.gif"); SimpleChart.drawChart(file, 640, 480, dataDropped, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "exceptions.gif"); SimpleChart.drawChart(file, 640, 480, dataException, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "weight.gif"); SimpleChart.drawChart(file, 640, 480, dataWeight, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "execution.gif"); SimpleChart.drawChart(file, 640, 480, dataExecution, startTime, stopTime, new Color(0, 0, 0)); file = new File(dir, startName + "wait.gif"); SimpleChart.drawChart(file, 640, 480, dataWait, startTime, stopTime, new Color(0, 0, 0)); } recordedExecutionThreads = 0; recordedWaitingThreads = 0; averageExecutionTime = 0; averageWaitTime = 0; if (!isLocked) { debugThread = new DebugThread(); debugThread.start(); } } Code Sample 2: public Component loadComponent(URI uri, URI origuri) throws ComponentException { try { Component comp = null; InputStream is = null; java.net.URL url = null; try { url = uri.getJavaURL(); } catch (java.net.MalformedURLException e) { throw new ComponentException("Invalid URL " + uri + " for component " + origuri + ":\n " + e.getMessage()); } try { if (url.getProtocol().equals("ftp")) is = ftpHandler.getInputStream(url); else { java.net.URLConnection conn = url.openConnection(); conn.connect(); is = conn.getInputStream(); } } catch (IOException e) { if (is != null) is.close(); throw new ComponentException("IO error loading URL " + url + " for component " + origuri + ":\n " + e.getMessage()); } try { comp = componentIO.loadComponent(origuri, uri, is, isSavable(uri)); } catch (ComponentException e) { if (is != null) is.close(); throw new ComponentException("Error loading component " + origuri + " from " + url + ":\n " + e.getMessage()); } is.close(); return comp; } catch (IOException ioe) { Tracer.debug("didn't manage to close inputstream...."); return null; } }
00
Code Sample 1: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; } Code Sample 2: public static String shaEncrypt(final String txt) { String enTxt = txt; MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { logger.error("Error:", e); } if (null != md) { byte[] shahash = new byte[32]; try { md.update(txt.getBytes("UTF-8"), 0, txt.length()); } catch (UnsupportedEncodingException e) { logger.error("Error:", e); } shahash = md.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < shahash.length; i++) { if (Integer.toHexString(0xFF & shahash[i]).length() == 1) { md5StrBuff.append("0").append(Integer.toHexString(0xFF & shahash[i])); } else { md5StrBuff.append(Integer.toHexString(0xFF & shahash[i])); } } enTxt = md5StrBuff.toString(); } return enTxt; }
00
Code Sample 1: ServerInfo getServerInfo(String key, String protocol) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IOException, ClassNotFoundException, IllegalBlockSizeException, BadPaddingException { DESedeKeySpec ks = new DESedeKeySpec(Base64.decode(key)); SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede"); SecretKey sk = skf.generateSecret(ks); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.DECRYPT_MODE, sk); ClassLoader cl = this.getClass().getClassLoader(); URL url = cl.getResource(protocol + ".sobj"); JarURLConnection jc = (JarURLConnection) url.openConnection(); ObjectInputStream os = new ObjectInputStream(jc.getInputStream()); SealedObject so = (SealedObject) os.readObject(); return (ServerInfo) so.getObject(cipher); } Code Sample 2: public byte[] loadResource(String name) throws IOException { ClassPathResource cpr = new ClassPathResource(name); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(cpr.getInputStream(), baos); return baos.toByteArray(); }
00
Code Sample 1: public String getWebPage(String url) { String content = ""; URL urlObj = null; try { urlObj = new URL(url); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); throw new Error("URL creation failed."); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream())); String line; while ((line = reader.readLine()) != null) { content += line; } } catch (IOException e) { e.printStackTrace(); throw new Error("Page retrieval failed."); } return content; } Code Sample 2: public void run() { saveWLHome(); for (final TabControl control : tabControls) { control.performOk(WLPropertyPage.this.getProject(), WLPropertyPage.this); } if (isEnabledJCLCopy()) { final File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File log4jLibrary = new File(lib, "log4j-1.2.13.jar"); if (!log4jLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jcl/log4j-1.2.13.jar")); fos = new FileOutputStream(log4jLibrary); IOUtils.copy(srcFile, fos); srcFile.close(); fos.flush(); fos.close(); srcFile = toInputStream(new Path("/jcl/commons-logging-1.0.4.jar")); File jcl = new File(lib, "commons-logging-1.0.4.jar"); fos = new FileOutputStream(jcl); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy JCL jars file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (IOException e) { } } } } if (isEnabledJSTLCopy()) { File url = new File(WLPropertyPage.this.domainDirectory.getText()); File lib = new File(url, "lib"); File jstlLibrary = new File(lib, "jstl.jar"); if (!jstlLibrary.exists()) { InputStream srcFile = null; FileOutputStream fos = null; try { srcFile = toInputStream(new Path("jstl/jstl.jar")); fos = new FileOutputStream(jstlLibrary); IOUtils.copy(srcFile, fos); } catch (IOException e) { Logger.log(Logger.ERROR, "Could not copy the JSTL 1.1 jar file to Bea WL", e); } finally { try { if (srcFile != null) { srcFile.close(); srcFile = null; } if (fos != null) { fos.flush(); fos.close(); fos = null; } } catch (final IOException e) { Logger.getLog().debug("I/O exception closing resources", e); } } } } }
11
Code Sample 1: protected void saveResponse(final WebResponse response, final WebRequest request) throws IOException { counter_++; final String extension = chooseExtension(response.getContentType()); final File f = createFile(request.getUrl(), extension); final InputStream input = response.getContentAsStream(); final OutputStream output = new FileOutputStream(f); try { IOUtils.copy(response.getContentAsStream(), output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } final URL url = response.getWebRequest().getUrl(); LOG.info("Created file " + f.getAbsolutePath() + " for response " + counter_ + ": " + url); final StringBuilder buffer = new StringBuilder(); buffer.append("tab[tab.length] = {code: " + response.getStatusCode() + ", "); buffer.append("fileName: '" + f.getName() + "', "); buffer.append("contentType: '" + response.getContentType() + "', "); buffer.append("method: '" + request.getHttpMethod().name() + "', "); if (request.getHttpMethod() == HttpMethod.POST && request.getEncodingType() == FormEncodingType.URL_ENCODED) { buffer.append("postParameters: " + nameValueListToJsMap(request.getRequestParameters()) + ", "); } buffer.append("url: '" + escapeJSString(url.toString()) + "', "); buffer.append("loadTime: " + response.getLoadTime() + ", "); final byte[] bytes = IOUtils.toByteArray(response.getContentAsStream()); buffer.append("responseSize: " + ((bytes == null) ? 0 : bytes.length) + ", "); buffer.append("responseHeaders: " + nameValueListToJsMap(response.getResponseHeaders())); buffer.append("};\n"); appendToJSFile(buffer.toString()); } Code Sample 2: public void install(Session session) throws Exception { String cfgPath = ConfigurationFactory.getConfigSonInstance().getConfigurationPath(); File setupKson = new File(cfgPath, "setup.kson"); InputStream is = null; if (setupKson.exists()) { log.debug("Reagind kson from " + setupKson.getAbsolutePath()); is = new FileInputStream(setupKson); } else { String ksonCp = "/org/chon/cms/core/setup/setup.kson"; is = Setup.class.getResourceAsStream(ksonCp); log.info("Creating initial setup.kson in " + setupKson.getAbsolutePath()); IOUtils.copy(is, new FileOutputStream(setupKson)); is = new FileInputStream(setupKson); } BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); List<String> lines = new ArrayList<String>(); while (true) { String line = br.readLine(); if (line == null) break; lines.add(line); } List<NodeCreation> ncList = readKSon(lines.toArray(new String[lines.size()])); for (NodeCreation nc : ncList) { try { createNode(session, nc); } catch (Exception e) { System.err.println("error crating node " + nc.path + " -> " + e.getMessage()); } } session.save(); }
00
Code Sample 1: public static final String getContent(String address) { String content = ""; OutputStream out = null; URLConnection conn = null; InputStream in = null; try { URL url = new URL(address); out = new ByteArrayOutputStream(); conn = url.openConnection(); in = conn.getInputStream(); byte[] buffer = new byte[1024]; int numRead; while ((numRead = in.read(buffer)) != -1) { out.write(buffer, 0, numRead); } content = out.toString(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException ioe) { } } return content; } Code Sample 2: private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
00
Code Sample 1: private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); this.setTitle("�ϥλ���"); jTextPane1.setEditable(false); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextPane1); this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL url = ReadmeFrame.class.getResource("readme.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder strBuilder = new StringBuilder(); while (reader.ready()) { strBuilder.append(reader.readLine()); strBuilder.append('\n'); } reader.close(); jTextPane1.setText(strBuilder.toString()); } Code Sample 2: public static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); srcChannel = null; dstChannel.close(); dstChannel = null; } catch (IOException ex) { Tools.logException(Tools.class, ex, dst.getAbsolutePath()); } }
00
Code Sample 1: private void copyResourceToDir(String ondexDir, String resource) { InputStream inputStream = OndexGraphImpl.class.getClassLoader().getResourceAsStream(resource); try { FileWriter fileWriter = new FileWriter(new File(ondexDir, resource)); IOUtils.copy(inputStream, fileWriter); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { logger.error("Unable to copy '" + resource + "' file to " + ondexDir + "'"); } } Code Sample 2: private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { if ((this.jTree2.getSelectionPath() == null) || !(this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode)) { Msg.showMsg("Devi selezionare lo stile sotto il quale caricare la ricetta!", this); return; } if ((this.txtUser.getText() == null) || (this.txtUser.getText().length() == 0)) { Msg.showMsg("Il nome utente è obbligatorio!", this); return; } if ((this.txtPwd.getPassword() == null) || (this.txtPwd.getPassword().length == 0)) { Msg.showMsg("La password è obbligatoria!", this); return; } this.nomeRicetta = this.txtNome.getText(); if ((this.nomeRicetta == null) || (this.nomeRicetta.length() == 0)) { Msg.showMsg("Il nome della ricetta è obbligatorio!", this); return; } StyleTreeNode node = null; if (this.jTree2.getSelectionPath().getLastPathComponent() instanceof StyleTreeNode) { node = (StyleTreeNode) this.jTree2.getSelectionPath().getLastPathComponent(); } try { String data = URLEncoder.encode("nick", "UTF-8") + "=" + URLEncoder.encode(this.txtUser.getText(), "UTF-8"); data += "&" + URLEncoder.encode("pwd", "UTF-8") + "=" + URLEncoder.encode(new String(this.txtPwd.getPassword()), "UTF-8"); data += "&" + URLEncoder.encode("id_stile", "UTF-8") + "=" + URLEncoder.encode(node.getIdStile(), "UTF-8"); data += "&" + URLEncoder.encode("nome_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.nomeRicetta, "UTF-8"); data += "&" + URLEncoder.encode("xml_ricetta", "UTF-8") + "=" + URLEncoder.encode(this.xml, "UTF-8"); URL url = new URL("http://" + Main.config.getRemoteServer() + "/upload_ricetta.asp?" + data); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String str = ""; while ((line = rd.readLine()) != null) { str += line; } rd.close(); Msg.showMsg(str, this); doDefaultCloseAction(); } catch (Exception e) { Utils.showException(e, "Errore in upload", this); } reloadTree(); }
00
Code Sample 1: private CathUtils() throws Exception { super(Ontology.CATH); InputStream is = null; BufferedReader reader = null; try { final String CATH_REGEXP = OntologyFactory.getOntology(Ontology.CATH).getRegularExpression(); final URL url = new URL("http://release.cathdb.info/v3.4.0/CathNames"); is = url.openStream(); reader = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset())); String line = null; while ((line = reader.readLine()) != null) { final String[] tokens = line.split("\\s+"); if (RegularExpressionUtils.getMatches(tokens[0], CATH_REGEXP).size() > 0) { idToName.put(tokens[0], line.substring(line.indexOf(':') + 1, line.length())); } } } finally { try { if (is != null) { is.close(); } } finally { if (reader != null) { reader.close(); } } } } Code Sample 2: public static Debugger getDebugger(InetAddress host, int port, String password) throws IOException { try { Socket s = new Socket(host, port); try { ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream()); ObjectInputStream in = new ObjectInputStream(s.getInputStream()); int protocolVersion = in.readInt(); if (protocolVersion > 220) { throw new IOException("Incompatible protocol version " + protocolVersion + ". At most 220 was expected."); } byte[] challenge = (byte[]) in.readObject(); MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); md.update(challenge); out.writeObject(md.digest()); return new LocalDebuggerProxy((Debugger) in.readObject()); } finally { s.close(); } } catch (IOException e) { throw e; } catch (Exception e) { throw new UndeclaredThrowableException(e); } }
11
Code Sample 1: public Logging() throws Exception { File home = new File(System.getProperty("user.home"), ".jorgan"); if (!home.exists()) { home.mkdirs(); } File logging = new File(home, "logging.properties"); if (!logging.exists()) { InputStream input = getClass().getResourceAsStream("logging.properties"); OutputStream output = null; try { output = new FileOutputStream(logging); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } FileInputStream input = null; try { input = new FileInputStream(logging); LogManager.getLogManager().readConfiguration(input); } finally { IOUtils.closeQuietly(input); } } Code Sample 2: public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } }
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: private int testAccesspoint(String s) throws IOException { HttpURLConnection connection = null; try { URL url = new URL(s); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "text/xml"); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode >= 500) { return 100; } else { return 0; } } finally { if (connection != null) { connection.disconnect(); } } }
00
Code Sample 1: public static String SHA512(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("UTF-8"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); } 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: private LinkedList<Datum> processDatum(Datum dataset) { ArrayList<Object[]> markerTestResults = new ArrayList<Object[]>(); ArrayList<Object[]> alleleEstimateResults = new ArrayList<Object[]>(); boolean hasAlleleNames = false; String blank = new String(""); MarkerPhenotypeAdapter theAdapter; if (dataset.getDataType().equals(MarkerPhenotype.class)) { theAdapter = new MarkerPhenotypeAdapter((MarkerPhenotype) dataset.getData()); } else theAdapter = new MarkerPhenotypeAdapter((Phenotype) dataset.getData()); int numberOfMarkers = theAdapter.getNumberOfMarkers(); if (numberOfMarkers == 0) { return calculateBLUEsFromPhenotypes(theAdapter, dataset.getName()); } int numberOfCovariates = theAdapter.getNumberOfCovariates(); int numberOfFactors = theAdapter.getNumberOfFactors(); int numberOfPhenotypes = theAdapter.getNumberOfPhenotypes(); int expectedIterations = numberOfPhenotypes * numberOfMarkers; int iterationsSofar = 0; int percentFinished = 0; File tempFile = null; File ftestFile = null; File blueFile = null; BufferedWriter ftestWriter = null; BufferedWriter BLUEWriter = null; String ftestHeader = "Trait\tMarker\tLocus\tLocus_pos\tChr\tChr_pos\tmarker_F\tmarker_p\tperm_p\tmarkerR2\tmarkerDF\tmarkerMS\terrorDF\terrorMS\tmodelDF\tmodelMS"; String BLUEHeader = "Trait\tMarker\tObs\tLocus\tLocus_pos\tChr\tChr_pos\tAllele\tEstimate"; if (writeOutputToFile) { String outputbase = outputName; if (outputbase.endsWith(".txt")) { int index = outputbase.lastIndexOf("."); outputbase = outputbase.substring(0, index); } String datasetNameNoSpace = dataset.getName().trim().replaceAll("\\ ", "_"); ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.txt"); int count = 0; while (ftestFile.exists()) { count++; ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest" + count + ".txt"); } blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs.txt"); count = 0; while (blueFile.exists()) { count++; blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs" + count + ".txt"); } tempFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.tmp"); try { if (permute) { ftestWriter = new BufferedWriter(new FileWriter(tempFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } else { ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } if (reportBLUEs) { BLUEWriter = new BufferedWriter(new FileWriter(blueFile)); BLUEWriter.write(BLUEHeader); BLUEWriter.newLine(); } } catch (IOException e) { myLogger.error("Failed to open file for output"); myLogger.error(e); return null; } } if (permute) { minP = new double[numberOfPhenotypes][numberOfPermutations]; for (int i = 0; i < numberOfPermutations; i++) { for (int j = 0; j < numberOfPhenotypes; j++) { minP[j][i] = 1; } } } for (int ph = 0; ph < numberOfPhenotypes; ph++) { double[] phenotypeData = theAdapter.getPhenotypeValues(ph); boolean[] missing = theAdapter.getMissingPhenotypes(ph); ArrayList<String[]> factorList = MarkerPhenotypeAdapterUtils.getFactorList(theAdapter, ph, missing); ArrayList<double[]> covariateList = MarkerPhenotypeAdapterUtils.getCovariateList(theAdapter, ph, missing); double[][] permutedData = null; if (permute) { permutedData = permuteData(phenotypeData, missing, factorList, covariateList, theAdapter); } for (int m = 0; m < numberOfMarkers; m++) { Object[] markerData = theAdapter.getMarkerValue(ph, m); boolean[] finalMissing = new boolean[missing.length]; System.arraycopy(missing, 0, finalMissing, 0, missing.length); MarkerPhenotypeAdapterUtils.updateMissing(finalMissing, theAdapter.getMissingMarkers(ph, m)); int[] nonmissingRows = MarkerPhenotypeAdapterUtils.getNonMissingIndex(finalMissing); int numberOfObs = nonmissingRows.length; double[] y = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) y[i] = phenotypeData[nonmissingRows[i]]; int firstMarkerAlleleEstimate = 1; ArrayList<ModelEffect> modelEffects = new ArrayList<ModelEffect>(); FactorModelEffect meanEffect = new FactorModelEffect(new int[numberOfObs], false); meanEffect.setID("mean"); modelEffects.add(meanEffect); if (numberOfFactors > 0) { for (int f = 0; f < numberOfFactors; f++) { String[] afactor = factorList.get(f); String[] factorLabels = new String[numberOfObs]; for (int i = 0; i < numberOfObs; i++) factorLabels[i] = afactor[nonmissingRows[i]]; FactorModelEffect fme = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(factorLabels), true, theAdapter.getFactorName(f)); modelEffects.add(fme); firstMarkerAlleleEstimate += fme.getNumberOfLevels() - 1; } } if (numberOfCovariates > 0) { for (int c = 0; c < numberOfCovariates; c++) { double[] covar = new double[numberOfObs]; double[] covariateData = covariateList.get(c); for (int i = 0; i < numberOfObs; i++) covar[i] = covariateData[nonmissingRows[i]]; modelEffects.add(new CovariateModelEffect(covar, theAdapter.getCovariateName(c))); firstMarkerAlleleEstimate++; } } ModelEffect markerEffect; boolean markerIsDiscrete = theAdapter.isMarkerDiscrete(m); ArrayList<Object> alleleNames = new ArrayList<Object>(); if (markerIsDiscrete) { Object[] markers = new Object[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markers[i] = markerData[nonmissingRows[i]]; int[] markerLevels = ModelEffectUtils.getIntegerLevels(markers, alleleNames); markerEffect = new FactorModelEffect(markerLevels, true, theAdapter.getMarkerName(m)); hasAlleleNames = true; } else { double[] markerdbl = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markerdbl[i] = ((Double) markerData[nonmissingRows[i]]).doubleValue(); markerEffect = new CovariateModelEffect(markerdbl, theAdapter.getMarkerName(m)); } int[] alleleCounts = markerEffect.getLevelCounts(); modelEffects.add(markerEffect); int markerEffectNumber = modelEffects.size() - 1; Identifier[] taxaSublist = new Identifier[numberOfObs]; Identifier[] taxa = theAdapter.getTaxa(ph); for (int i = 0; i < numberOfObs; i++) taxaSublist[i] = taxa[nonmissingRows[i]]; boolean areTaxaReplicated = containsDuplicates(taxaSublist); double[] markerSSdf = null, errorSSdf = null, modelSSdf = null; double F, p; double[] beta = null; if (areTaxaReplicated && markerIsDiscrete) { ModelEffect taxaEffect = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(taxaSublist), true); modelEffects.add(taxaEffect); SweepFastNestedModel sfnm = new SweepFastNestedModel(modelEffects, y); double[] taxaSSdf = sfnm.getTaxaInMarkerSSdf(); double[] residualSSdf = sfnm.getErrorSSdf(); markerSSdf = sfnm.getMarkerSSdf(); errorSSdf = sfnm.getErrorSSdf(); modelSSdf = sfnm.getModelcfmSSdf(); F = markerSSdf[0] / markerSSdf[1] / taxaSSdf[0] * taxaSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], taxaSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sfnm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sfnm.getInverseOfXtX(), markerdf); } } else { SweepFastLinearModel sflm = new SweepFastLinearModel(modelEffects, y); modelSSdf = sflm.getModelcfmSSdf(); markerSSdf = sflm.getMarginalSSdf(markerEffectNumber); errorSSdf = sflm.getResidualSSdf(); F = markerSSdf[0] / markerSSdf[1] / errorSSdf[0] * errorSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], errorSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sflm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sflm.getInverseOfXtX(), markerdf); } } if (!filterOutput || p < maxp) { String traitname = theAdapter.getPhenotypeName(ph); if (traitname == null) traitname = blank; String marker = theAdapter.getMarkerName(m); if (marker == null) marker = blank; String locus = theAdapter.getLocusName(m); Integer site = new Integer(theAdapter.getLocusPosition(m)); String chrname = ""; Double chrpos = Double.NaN; if (hasMap) { int ndx = -1; ndx = myMap.getMarkerIndex(marker); if (ndx > -1) { chrname = myMap.getChromosome(ndx); chrpos = myMap.getGeneticPosition(ndx); } } Object[] result = new Object[16]; int col = 0; result[col++] = traitname; result[col++] = marker; result[col++] = locus; result[col++] = site; result[col++] = chrname; result[col++] = chrpos; result[col++] = new Double(F); result[col++] = new Double(p); result[col++] = Double.NaN; result[col++] = new Double(markerSSdf[0] / (modelSSdf[0] + errorSSdf[0])); result[col++] = new Double(markerSSdf[1]); result[col++] = new Double(markerSSdf[0] / markerSSdf[1]); result[col++] = new Double(errorSSdf[1]); result[col++] = new Double(errorSSdf[0] / errorSSdf[1]); result[col++] = new Double(modelSSdf[1]); result[col++] = new Double(modelSSdf[0] / modelSSdf[1]); if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int i = 1; i < 16; i++) sb.append("\t").append(result[i]); try { ftestWriter.write(sb.toString()); ftestWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { markerTestResults.add(result); } int numberOfMarkerAlleles = alleleNames.size(); if (numberOfMarkerAlleles == 0) numberOfMarkerAlleles++; for (int i = 0; i < numberOfMarkerAlleles; i++) { result = new Object[9]; result[0] = traitname; result[1] = marker; result[2] = new Integer(alleleCounts[i]); result[3] = locus; result[4] = site; result[5] = chrname; result[6] = chrpos; if (numberOfMarkerAlleles == 1) result[7] = ""; else result[7] = alleleNames.get(i); if (i == numberOfMarkerAlleles - 1) result[8] = 0.0; else result[8] = beta[firstMarkerAlleleEstimate + i]; if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int j = 1; j < 9; j++) sb.append("\t").append(result[j]); try { BLUEWriter.write(sb.toString()); BLUEWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { alleleEstimateResults.add(result); } } } int tmpPercent = ++iterationsSofar * 100 / expectedIterations; if (tmpPercent > percentFinished) { percentFinished = tmpPercent; fireProgress(percentFinished); } } } fireProgress(0); if (writeOutputToFile) { try { ftestWriter.close(); BLUEWriter.close(); } catch (IOException e) { e.printStackTrace(); } } HashMap<String, Integer> traitnameMap = new HashMap<String, Integer>(); if (permute) { for (int ph = 0; ph < numberOfPhenotypes; ph++) { Arrays.sort(minP[ph]); traitnameMap.put(theAdapter.getPhenotypeName(ph), ph); } if (writeOutputToFile) { try { BufferedReader tempReader = new BufferedReader(new FileReader(tempFile)); ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(tempReader.readLine()); ftestWriter.newLine(); String input; String[] data; Pattern tab = Pattern.compile("\t"); while ((input = tempReader.readLine()) != null) { data = tab.split(input); String trait = data[0]; double pval = Double.parseDouble(data[7]); int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; data[8] = Double.toString((double) ndx / (double) numberOfPermutations); ftestWriter.write(data[0]); for (int i = 1; i < data.length; i++) { ftestWriter.write("\t"); ftestWriter.write(data[i]); } ftestWriter.newLine(); } tempReader.close(); ftestWriter.close(); tempFile.delete(); } catch (IOException e) { myLogger.error(e); } } else { for (Object[] result : markerTestResults) { String trait = result[0].toString(); double pval = (Double) result[7]; int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; result[8] = new Double((double) ndx / (double) numberOfPermutations); } } } String[] columnLabels = new String[] { "Trait", "Marker", "Locus", "Locus_pos", "Chr", "Chr_pos", "marker_F", "marker_p", "perm_p", "markerR2", "markerDF", "markerMS", "errorDF", "errorMS", "modelDF", "modelMS" }; boolean hasMarkerNames = theAdapter.hasMarkerNames(); LinkedList<Integer> outputList = new LinkedList<Integer>(); outputList.add(0); if (hasMarkerNames) outputList.add(1); outputList.add(2); outputList.add(3); if (hasMap) { outputList.add(4); outputList.add(5); } outputList.add(6); outputList.add(7); if (permute) outputList.add(8); for (int i = 9; i < 16; i++) outputList.add(i); LinkedList<Datum> resultset = new LinkedList<Datum>(); int nrows = markerTestResults.size(); Object[][] table = new Object[nrows][]; int numberOfColumns = outputList.size(); String[] colnames = new String[numberOfColumns]; int count = 0; for (Integer ndx : outputList) colnames[count++] = columnLabels[ndx]; for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = markerTestResults.get(i); count = 0; for (Integer ndx : outputList) table[i][count++] = result[ndx]; } StringBuilder tableName = new StringBuilder("GLM_marker_test_"); tableName.append(dataset.getName()); StringBuilder comments = new StringBuilder("Tests of Marker-Phenotype Association"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + ftestFile.getPath()); } TableReport markerTestReport = new SimpleTableReport("Marker Test", colnames, table); resultset.add(new Datum(tableName.toString(), markerTestReport, comments.toString())); int[] outputIndex; columnLabels = new String[] { "Trait", "Marker", "Obs", "Locus", "Locus_pos", "Chr", "Chr_pos", "Allele", "Estimate" }; if (hasAlleleNames) { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 7, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 7, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 7, 8 }; } } else { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 8 }; } } nrows = alleleEstimateResults.size(); table = new Object[nrows][]; numberOfColumns = outputIndex.length; colnames = new String[numberOfColumns]; for (int j = 0; j < numberOfColumns; j++) { colnames[j] = columnLabels[outputIndex[j]]; } for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = alleleEstimateResults.get(i); for (int j = 0; j < numberOfColumns; j++) { table[i][j] = result[outputIndex[j]]; } } tableName = new StringBuilder("GLM allele estimates for "); tableName.append(dataset.getName()); comments = new StringBuilder("Marker allele effect estimates\n"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + blueFile.getPath()); } TableReport alleleEstimateReport = new SimpleTableReport("Allele Estimates", colnames, table); resultset.add(new Datum(tableName.toString(), alleleEstimateReport, comments.toString())); fireProgress(0); return resultset; } 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 void testRoundTrip_1(String resource) throws Exception { long start1 = System.currentTimeMillis(); File originalFile = File.createTempFile("RoundTripTest", "testRoundTrip_1"); FileOutputStream fos = new FileOutputStream(originalFile); IOUtils.copy(getClass().getResourceAsStream(resource), fos); fos.close(); long start2 = System.currentTimeMillis(); IsoFile isoFile = new IsoFile(new FileInputStream(originalFile).getChannel()); long start3 = System.currentTimeMillis(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel wbc = Channels.newChannel(baos); long start4 = System.currentTimeMillis(); Walk.through(isoFile); long start5 = System.currentTimeMillis(); isoFile.getBox(wbc); wbc.close(); long start6 = System.currentTimeMillis(); System.err.println("Preparing tmp copy took: " + (start2 - start1) + "ms"); System.err.println("Parsing took : " + (start3 - start2) + "ms"); System.err.println("Writing took : " + (start6 - start3) + "ms"); System.err.println("Walking took : " + (start5 - start4) + "ms"); byte[] a = IOUtils.toByteArray(getClass().getResourceAsStream(resource)); byte[] b = baos.toByteArray(); Assert.assertArrayEquals(a, b); } Code Sample 2: public static void copyZip() { InputStream is; OutputStream os; String javacZip = ""; try { if ("windows".equalsIgnoreCase(Compilador.getSo())) { javacZip = "javacWin.zip"; is = UnZip.class.getResourceAsStream("javacWin.zip"); } else if ("linux".equalsIgnoreCase(Compilador.getSo())) { javacZip = "javacLinux.zip"; is = UnZip.class.getResourceAsStream("javacLinux.zip"); } is = UnZip.class.getResourceAsStream(javacZip); File tempZip = File.createTempFile("tempJavacJTraductor", ".zip"); tempZip.mkdir(); tempZip.deleteOnExit(); os = FileUtils.openOutputStream(tempZip); IOUtils.copy(is, os); is.close(); os.close(); extractZip(tempZip.getPath()); } catch (Exception ex) { JOptionPane.showMessageDialog(PseutemView.mainPanel, "Error al copiar los archivos temporales necesarios para ejecutar el programa:\n\n" + ex, "Error copiando.", JOptionPane.ERROR_MESSAGE); } }
11
Code Sample 1: public static void copyFile(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(); } Code Sample 2: public void dispatch(com.sun.star.util.URL aURL, com.sun.star.beans.PropertyValue[] aArguments) { if (aURL.Protocol.compareTo("org.openoffice.oosvn.oosvn:") == 0) { OoDocProperty docProperty = getProperty(); settings.setCancelFired(false); if (aURL.Path.compareTo("svnUpdate") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (NullPointerException ex) { new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; new DialogFileChooser(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = -1; if (logs.length == 0) { error("Sorry, the specified repository is empty."); return; } new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); if (settings.getCancelFired()) return; File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File[] tempFiles = tempDir.listFiles(); File anyOdt = null; File thisOdt = null; for (int j = 0; j < tempFiles.length; j++) { if (tempFiles[j].toString().endsWith(".odt")) anyOdt = tempFiles[j]; if (tempFiles[j].toString().equals(settings.getCheckoutDoc()) && settings.getCheckoutDoc() != null) thisOdt = tempFiles[j]; } if (thisOdt != null) anyOdt = thisOdt; String url; if (settings.getCheckoutDoc() == null || !settings.getCheckoutDoc().equals(anyOdt.getName())) { File newOdt = new File(settings.getCheckoutPath() + "/" + anyOdt.getName()); if (newOdt.exists()) newOdt.delete(); anyOdt.renameTo(newOdt); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } url = "file:///" + newOdt.getPath().replace("\\", "/"); svnInfo.renameTo(newSvnInfo); anyOdt = newOdt; loadDocumentFromUrl(url); settings.setCheckoutDoc(anyOdt.getName()); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } else { try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } url = "file:///" + anyOdt.getPath().replace("\\", "/"); XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, m_xFrame); PropertyValue property[] = new PropertyValue[1]; property[0] = new PropertyValue(); property[0].Name = "URL"; property[0].Value = url; XMultiServiceFactory xMSF = createProvider(); Object objDispatchHelper = m_xServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", m_xContext); XDispatchHelper xDispatchHelper = (XDispatchHelper) UnoRuntime.queryInterface(XDispatchHelper.class, objDispatchHelper); xDispatchHelper.executeDispatch(xDispatchProvider, ".uno:CompareDocuments", "", 0, property); } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnCommit") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Collection logs = svnWorker.getLogs(settings); long headRevision = svnWorker.getHeadRevisionNumber(logs); long committedRevision = -1; new DialogCommitMessage(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } if (headRevision == 0) { File impDir = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import"); if (impDir.exists()) if (deleteFileDir(impDir) == false) { error("Error while creating temporary import directory."); return; } if (!impDir.mkdirs()) { error("Error while creating temporary import directory."); return; } File impFile = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import/" + settings.getCheckoutDoc()); try { FileChannel srcChannel = new FileInputStream(settings.getCheckoutPath() + "/" + settings.getCheckoutDoc()).getChannel(); FileChannel dstChannel = new FileOutputStream(impFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { error("Error while importing file", ex); return; } final String checkoutPath = settings.getCheckoutPath(); try { settings.setCheckoutPath(impDir.toString()); committedRevision = svnWorker.importDirectory(settings, false).getNewRevision(); } catch (Exception ex) { settings.setCheckoutPath(checkoutPath); error("Error while importing file", ex); return; } settings.setCheckoutPath(checkoutPath); if (impDir.exists()) if (deleteFileDir(impDir) == false) error("Error while creating temporary import directory."); try { File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); svnInfo.renameTo(newSvnInfo); if (deleteFileDir(tempDir) == false) { error("Error while managing working copy"); } try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } catch (Exception ex) { error("Error while checking out a working copy for the location", ex); } showMessageBox("Import succesful", "Succesfully imported as revision no. " + committedRevision); return; } else { try { committedRevision = svnWorker.commit(settings, false).getNewRevision(); } catch (Exception ex) { error("Error while committing changes. If the file is not working copy, you must use 'Checkout / Update' first.", ex); } if (committedRevision == -1) { showMessageBox("Update - no changes", "No changes was made. Maybe you must just save the changes."); } else { showMessageBox("Commit succesfull", "Commited as revision no. " + committedRevision); } } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnHistory") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = settings.getCheckoutVersion(); settings.setCheckoutVersion(-99); new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); settings.setCheckoutVersion(checkVersion); } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("settings") == 0) { try { settings = getSerializedSettings(docProperty); } catch (NoSerializedSettingsException ex) { try { settings.setCheckout(docProperty.getDocURL()); } catch (Exception exx) { } } catch (Exception ex) { error("Error getting settings; maybe you" + " need to save your document." + " If this is your first" + " checkout of the document, use Checkout" + " function directly."); return; } new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when saving settings.", ex); } return; } if (aURL.Path.compareTo("about") == 0) { showMessageBox("OoSvn :: About", "Autor: �t�p�n Cenek (stepan@geek.cz)"); return; } } }
00
Code Sample 1: private Map fetchAdData(String url) throws ClientProtocolException, IOException { String app = "1"; String owner = "tx"; String session = ""; String sdk = "ad1.0"; String version = "txLove1.0"; String timestamp = String.valueOf(System.currentTimeMillis()); String sign = ""; String appSecret = "test"; Map<String, String> protocal = new HashMap<String, String>(); protocal.put(AuthUtils.AUTH_APP, app); protocal.put(AuthUtils.AUTH_OWNER, owner); protocal.put(AuthUtils.AUTH_SESSION, session); protocal.put(AuthUtils.SDK, sdk); protocal.put(AuthUtils.VERSION, version); protocal.put(AuthUtils.TIMESTAMP, timestamp); Map<String, String> parameter = new HashMap<String, String>(); parameter.put("uid", String.valueOf(user.getUserId())); parameter.put("ip", "0"); parameter.put("imsi", imsi); parameter.put("width", "0"); sign = AuthUtils.sign(protocal, parameter, appSecret); HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(url.toString()); request.setHeader(AuthUtils.AUTH_APP, app); request.setHeader(AuthUtils.AUTH_OWNER, owner); request.setHeader(AuthUtils.AUTH_SESSION, session); request.setHeader(AuthUtils.SDK, sdk); request.setHeader(AuthUtils.VERSION, version); request.setHeader(AuthUtils.TIMESTAMP, timestamp); request.setHeader(AuthUtils.SIGN, sign); HttpResponse response = client.execute(request); if (response.getStatusLine().getStatusCode() == 200) { BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = reader.readLine(); JSONObject object; Map map = new HashMap(); try { System.out.println("##################### line = " + line); object = new JSONObject(line); if (object != null) { System.out.println(object.toString()); map.put("imgAddress", object.getString("imgurl")); map.put("imgUrl", object.getString("url")); return map; } } catch (JSONException e) { e.printStackTrace(); } } return null; } Code Sample 2: public static void copyFile(File destFile, File src) throws IOException { File destDir = destFile.getParentFile(); File tempFile = new File(destFile + "_tmp"); destDir.mkdirs(); InputStream is = new FileInputStream(src); try { FileOutputStream os = new FileOutputStream(tempFile); try { byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); } finally { os.close(); } } finally { is.close(); } destFile.delete(); if (!tempFile.renameTo(destFile)) throw new IOException("Unable to rename " + tempFile + " to " + destFile); }
11
Code Sample 1: private void processBasicContent() { String[] packageNames = sourceCollector.getPackageNames(); for (int i = 0; i < packageNames.length; i++) { XdcSource[] sources = sourceCollector.getXdcSources(packageNames[i]); File dir = new File(outputDir, packageNames[i]); dir.mkdirs(); Set pkgDirs = new HashSet(); for (int j = 0; j < sources.length; j++) { XdcSource source = sources[j]; Properties patterns = source.getPatterns(); if (patterns != null) { tables.put("patterns", patterns); } pkgDirs.add(source.getFile().getParentFile()); DialectHandler dialectHandler = source.getDialectHandler(); Writer out = null; try { String sourceFilePath = source.getFile().getAbsolutePath(); source.setProcessingProperties(baseProperties, j > 0 ? sources[j - 1].getFileName() : null, j < sources.length - 1 ? sources[j + 1].getFileName() : null); String rootComment = XslUtils.transformToString(sourceFilePath, XSL_PKG + "/source-header.xsl", tables); source.setRootComment(rootComment); Document htmlDoc = XslUtils.transform(sourceFilePath, encoding, dialectHandler.getXslResourcePath(), tables); if (LOG.isInfoEnabled()) { LOG.info("Processing source file " + sourceFilePath); } out = IOUtils.getWriter(new File(dir, source.getFile().getName() + ".html"), docencoding); XmlUtils.printHtml(out, htmlDoc); if (sourceProcessor != null) { sourceProcessor.processSource(source, encoding, docencoding); } XdcSource.clearProcessingProperties(baseProperties); } catch (XmlException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } for (Iterator iter = pkgDirs.iterator(); iter.hasNext(); ) { File docFilesDir = new File((File) iter.next(), "xdc-doc-files"); if (docFilesDir.exists() && docFilesDir.isDirectory()) { File targetDir = new File(dir, "xdc-doc-files"); targetDir.mkdirs(); try { IOUtils.copyTree(docFilesDir, targetDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } } Code Sample 2: public static void copy(File src, File dest) throws IOException { if (!src.exists()) { throw new IOException(StaticUtils.format(OStrings.getString("LFC_ERROR_FILE_DOESNT_EXIST"), new Object[] { src.getAbsolutePath() })); } FileInputStream fis = new FileInputStream(src); dest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(dest); byte[] b = new byte[BUFSIZE]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
11
Code Sample 1: public final void testT4CClientWriter() throws Exception { InputStream is = ClassLoader.getSystemResourceAsStream(this.testFileName); T4CClientReader reader = new T4CClientReader(is, rc); File tmpFile = File.createTempFile("barde", ".log", this.tmpDir); System.out.println("tmp=" + tmpFile.getAbsolutePath()); T4CClientWriter writer = new T4CClientWriter(new FileOutputStream(tmpFile), rc); for (Message m = reader.read(); m != null; m = reader.read()) writer.write(m); writer.close(); InputStream fa = ClassLoader.getSystemResourceAsStream(this.testFileName); FileInputStream fb = new FileInputStream(tmpFile); for (int ba = fa.read(); ba != -1; ba = fa.read()) assertEquals(ba, fb.read()); } 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 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 ResourceMigratorBuilder createResourceMigratorBuilder(NotificationReporter reporter) { return new ResourceMigratorBuilder() { public ResourceMigrator getCompletedResourceMigrator() { return new ResourceMigrator() { public void migrate(InputMetadata meta, InputStream inputStream, OutputCreator outputCreator) throws IOException, ResourceMigrationException { OutputStream outputStream = outputCreator.createOutputStream(); IOUtils.copy(inputStream, outputStream); } }; } public void setTarget(Version version) { } public void startType(String typeName) { } public void setRegexpPathRecogniser(String re) { } public void setCustomPathRecogniser(PathRecogniser pathRecogniser) { } public void addRegexpContentRecogniser(Version version, String re) { } public void addCustomContentRecogniser(Version version, ContentRecogniser contentRecogniser) { } public XSLStreamMigratorBuilder createXSLStreamMigratorBuilder() { return null; } public void addStep(Version inputVersion, Version outputVersion, StreamMigrator streamMigrator) { } public void endType() { } }; }
00
Code Sample 1: public static String getURLContent(String urlStr) throws MalformedURLException, IOException { URL url = new URL(urlStr); log.info("url: " + url); URLConnection conn = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer buf = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { buf.append(inputLine); } in.close(); return buf.toString(); } Code Sample 2: public APIResponse delete(String id) throws Exception { APIResponse response = new APIResponse(); connection = (HttpURLConnection) new URL(url + "/api/item/delete/" + id).openConnection(); connection.setRequestMethod("DELETE"); connection.setConnectTimeout(TIMEOUT); connection.connect(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { response.setDone(true); response.setMessage("Item Deleted!"); } else { response.setDone(false); response.setMessage("Delete Item Error Code: Http (" + connection.getResponseCode() + ")"); } connection.disconnect(); return response; }