label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
public static List<String> extract(String zipFilePath, String destDirPath) throws IOException { List<String> list = null; ZipFile zip = new ZipFile(zipFilePath); try { Enumeration<? extends ZipEntry> entries = zip.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); File destFile = new File(destDirPath, entry.getName()); if (entry.isDirectory()) { destFile.mkdirs(); } else { InputStream in = zip.getInputStream(entry); OutputStream out = new FileOutputStream(destFile); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); try { out.close(); } catch (IOException ioe) { ioe.getMessage(); } try { in.close(); } catch (IOException ioe) { ioe.getMessage(); } } } if (list == null) { list = new ArrayList<String>(); } list.add(destFile.getAbsolutePath()); } return list; } finally { try { zip.close(); } catch (Exception e) { e.getMessage(); } } }
Code Sample 2:
public static void printResource(OutputStream os, String resourceName) throws IOException { InputStream is = null; try { is = ResourceLoader.loadResource(resourceName); if (is == null) { throw new IOException("Given resource not found!"); } IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); } }
|
00
|
Code Sample 1:
public static void main(String[] args) { FTPClient client = new FTPClient(); try { client.connect("192.168.1.10"); boolean login = client.login("a", "123456"); if (login) { System.out.println("Dang nhap thanh cong..."); boolean logout = client.logout(); if (logout) { System.out.println("Da Logout khoi FTP Server..."); } } else { System.out.println("Dang nhap that bai..."); } } catch (IOException e) { e.printStackTrace(); } finally { try { client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } }
Code Sample 2:
public static void printResource(OutputStream os, String resourceName) throws IOException { InputStream is = null; try { is = ResourceLoader.loadResource(resourceName); if (is == null) { throw new IOException("Given resource not found!"); } IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); } }
|
11
|
Code Sample 1:
private void exportJar(File root, List<File> list, Manifest manifest) throws Exception { JarOutputStream jarOut = null; FileInputStream fin = null; try { jarOut = new JarOutputStream(new FileOutputStream(jarFile), manifest); for (int i = 0; i < list.size(); i++) { String filename = list.get(i).getAbsolutePath(); filename = filename.substring(root.getAbsolutePath().length() + 1); fin = new FileInputStream(list.get(i)); JarEntry entry = new JarEntry(filename.replace('\\', '/')); jarOut.putNextEntry(entry); byte[] buf = new byte[4096]; int read; while ((read = fin.read(buf)) != -1) { jarOut.write(buf, 0, read); } jarOut.closeEntry(); jarOut.flush(); } } finally { if (fin != null) { try { fin.close(); } catch (Exception e) { ExceptionOperation.operate(e); } } if (jarOut != null) { try { jarOut.close(); } catch (Exception e) { } } } }
Code Sample 2:
public Object downloadFile(File destinationFile, URL[] urls, DownloadListener listener, Object checksum, long length, PRIORITY priority) throws DownloadException { URL url = urls[0]; if (!url.getProtocol().equalsIgnoreCase("http")) { throw new DownloadException(" Only HTTP is supported in this version "); } if (!destinationFile.exists()) { try { destinationFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); throw new DownloadException("Unable to download from URL : " + url.toString()); } } HeadMethod head = new HeadMethod(url.toString()); HttpClient httpClient = new HttpClient(); try { httpClient.executeMethod(head); Header[] headers = head.getResponseHeaders(); for (Header header : headers) { System.out.println(header); } Header header = head.getResponseHeader("Content-Length"); Object contentLength = header.getValue(); Long fileLength = Long.parseLong(contentLength.toString()); System.out.println(length + " : " + fileLength); GetMethod get = new GetMethod(url.toString()); httpClient.executeMethod(get); InputStream ins = get.getResponseBodyAsStream(); FileOutputStream fos = new FileOutputStream(destinationFile); IOUtils.copy(ins, fos); System.out.println(" DOWNLOADED FILE"); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
|
00
|
Code Sample 1:
public static String getResponseText(String url) throws MalformedURLException, IOException { URL m_url = new URL(url); URLConnection urlCconn = m_url.openConnection(); urlCconn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16"); urlCconn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); urlCconn.setRequestProperty("Accept-Language", "en-us,en;q=0.5"); urlCconn.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); urlCconn.setRequestProperty("Keep-Alive", "300"); urlCconn.setRequestProperty("Connection", "keep-alive"); return IOUtil.toString(urlCconn.getInputStream()); }
Code Sample 2:
public static void copy(File src, File dst) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { try { srcChannel.close(); } finally { dstChannel.close(); } } }
|
11
|
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 Vector Get() throws Exception { String query_str = BuildYahooQueryString(); if (query_str == null) return null; Vector result = new Vector(); HttpURLConnection urlc = null; try { URL url = new URL(URL_YAHOO_QUOTE + "?" + query_str + "&" + FORMAT); urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestMethod("GET"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", "text/html;charset=UTF-8"); if (urlc.getResponseCode() == 200) { InputStream in = urlc.getInputStream(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); String msg = null; while ((msg = reader.readLine()) != null) { ExchangeRate rate = ParseYahooData(msg); if (rate != null) result.add(rate); } } finally { if (reader != null) try { reader.close(); } catch (Exception e1) { } if (in != null) try { in.close(); } catch (Exception e1) { } } return result; } } finally { if (urlc != null) try { urlc.disconnect(); } catch (Exception e) { } } return null; }
|
00
|
Code Sample 1:
public static void main(String[] args) { try { String user = "techbeherca"; String targetUrl = "http://api.fanfou.com/statuses/user_timeline.xml?id=" + user; URL url = new URL(targetUrl); InputStream in = url.openStream(); ArrayList<MessageObj> list; if (in != null) { MessageListDOMParser parser = new MessageListDOMParser(); list = (ArrayList<MessageObj>) parser.parseXML(in); TransactionDAO dao = new TransactionDAO(); dao.insert(list); } } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public String encryptPassword(String clearPassword) throws NullPointerException { MessageDigest sha; try { sha = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new NullPointerException("NoSuchAlgorithmException: " + e.toString()); } sha.update(clearPassword.getBytes()); byte encryptedPassword[] = sha.digest(); sha = null; StringBuffer result = new StringBuffer(); for (int i = 0; i < encryptedPassword.length; i++) { result.append(Byte.toString(encryptedPassword[i])); } return (result.toString()); }
|
00
|
Code Sample 1:
private static void generateTIFF(Connection con, String category, String area_code, String topic_code, String timeseries, String diff_timeseries, Calendar time, String area_label, String raster_label, String image_label, String note, Rectangle2D bounds, Rectangle2D raster_bounds, String source_filename, String diff_filename, String legend_filename, String output_filename, int output_maximum_size) throws SQLException, IOException { Debug.println("ImageCropper.generateTIFF begin"); MapContext map_context = new MapContext("test", new Configuration()); try { Map map = new Map(map_context, area_label, new Configuration()); map.setCoordSys(ProjectionCategories.default_coordinate_system); map.setPatternOutline(new XPatternOutline(new XPatternPaint(Color.white))); String type = null; RasterLayer rlayer = getRasterLayer(map, raster_label, getLinuxPathEquivalent(source_filename), getLinuxPathEquivalent(diff_filename), type, getLinuxPathEquivalent(legend_filename)); map.addLayer(rlayer, true); map.setBounds2DImage(bounds, true); Dimension image_dim = null; image_dim = new Dimension((int) rlayer.raster.getDeviceBounds().getWidth() + 1, (int) rlayer.raster.getDeviceBounds().getHeight() + 1); if (output_maximum_size > 0) { double width_factor = image_dim.getWidth() / output_maximum_size; double height_factor = image_dim.getHeight() / output_maximum_size; double factor = Math.max(width_factor, height_factor); if (factor > 1.0) { image_dim.setSize(image_dim.getWidth() / factor, image_dim.getHeight() / factor); } } map.setImageDimension(image_dim); map.scale(); image_dim = new Dimension((int) map.getBounds2DImage().getWidth(), (int) map.getBounds2DImage().getHeight()); Image image = null; Graphics gr = null; image = ImageCreator.getImage(image_dim); gr = image.getGraphics(); try { map.paint(gr); } catch (Exception e) { Debug.println("map.paint error: " + e.getMessage()); } String tiff_filename = ""; try { tiff_filename = formatPath(category, timeseries, output_filename); new File(new_filename).mkdirs(); Debug.println("tiff_filename: " + tiff_filename); BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_BYTE_INDEXED); bi.createGraphics().drawImage(image, 0, 0, null); File f = new File(tiff_filename); FileOutputStream out = new FileOutputStream(f); TIFFEncodeParam param = new TIFFEncodeParam(); param.setCompression(TIFFEncodeParam.COMPRESSION_PACKBITS); TIFFImageEncoder encoder = (TIFFImageEncoder) TIFFCodec.createImageEncoder("tiff", out, param); encoder.encode(bi); out.close(); } catch (IOException e) { Debug.println("ImageCropper.generateTIFF TIFFCodec e: " + e.getMessage()); throw new IOException("GenerateTIFF.IOException: " + e); } PreparedStatement pstmt = null; try { String query = "select Proj_ID, AccessType_Code from project " + "where Proj_Code= '" + area_code.trim() + "'"; Statement stmt = null; ResultSet rs = null; int proj_id = -1; int access_code = -1; stmt = con.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { proj_id = rs.getInt(1); access_code = rs.getInt(2); } rs.close(); stmt.close(); String delete_raster = "delete from rasterlayer where " + "Raster_Name='" + tiff_name.trim() + "' and Group_Code='" + category.trim() + "' and Proj_ID =" + proj_id; Debug.println("***** delete_raster: " + delete_raster); pstmt = con.prepareStatement(delete_raster); boolean del = pstmt.execute(); pstmt.close(); String insert_raster = "insert into rasterlayer(Raster_Name, " + "Group_Code, Proj_ID, Raster_TimeCode, Raster_Xmin, " + "Raster_Ymin, Raster_Area_Xmin, Raster_Area_Ymin, " + "Raster_Visibility, Raster_Order, Raster_Path, " + "AccessType_Code, Raster_TimePeriod) values(?,?,?,?, " + "?,?,?,?,?,?,?,?,?)"; pstmt = con.prepareStatement(insert_raster); pstmt.setString(1, tiff_name); pstmt.setString(2, category); pstmt.setInt(3, proj_id); pstmt.setString(4, timeseries); pstmt.setDouble(5, raster_bounds.getX()); pstmt.setDouble(6, raster_bounds.getY()); pstmt.setDouble(7, raster_bounds.getWidth()); pstmt.setDouble(8, raster_bounds.getHeight()); pstmt.setString(9, "false"); int sequence = 0; if (tiff_name.endsWith("DP")) { sequence = 1; } else if (tiff_name.endsWith("DY")) { sequence = 2; } else if (tiff_name.endsWith("DA")) { sequence = 3; } pstmt.setInt(10, sequence); pstmt.setString(11, tiff_filename); pstmt.setInt(12, access_code); if (time == null) { pstmt.setNull(13, java.sql.Types.DATE); } else { pstmt.setDate(13, new java.sql.Date(time.getTimeInMillis())); } pstmt.executeUpdate(); } catch (SQLException e) { Debug.println("SQLException occurred e: " + e.getMessage()); con.rollback(); throw new SQLException("GenerateTIFF.SQLException: " + e); } finally { pstmt.close(); } } catch (Exception e) { Debug.println("ImageCropper.generateTIFF e: " + e.getMessage()); } Debug.println("ImageCropper.generateTIFF end"); }
Code Sample 2:
public static void messageDigestTest() { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update("computer".getBytes()); md.update("networks".getBytes()); System.out.println(new String(md.digest())); System.out.println(new String(md.digest("computernetworks".getBytes()))); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static String readUrlText(String urlString) throws IOException { URL url = new URL(urlString); InputStream stream = url.openStream(); StringBuilder buf = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(stream)); String str; while ((str = in.readLine()) != null) { buf.append(str); buf.append(System.getProperty("line.separator")); } } catch (IOException e) { System.out.println("Error reading text from URL [" + url + "]: " + e.toString()); throw e; } finally { if (in != null) { try { in.close(); } catch (IOException e) { System.out.println("Error closing after reading text from URL [" + url + "]: " + e.toString()); } } } return buf.toString(); }
Code Sample 2:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
|
11
|
Code Sample 1:
public static void printResource(OutputStream os, String resourceName) throws IOException { InputStream is = null; try { is = ResourceLoader.loadResource(resourceName); if (is == null) { throw new IOException("Given resource not found!"); } IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); } }
Code Sample 2:
public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); }
|
00
|
Code Sample 1:
private List<String> getRobots(String beginURL, String contextRoot) { List<String> vtRobots = new ArrayList<String>(); BufferedReader bfReader = null; try { URL urlx = new URL(beginURL + "/" + contextRoot + "/" + "robots.txt"); URLConnection urlConn = urlx.openConnection(); urlConn.setUseCaches(false); bfReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String sxLine = ""; while ((sxLine = bfReader.readLine()) != null) { if (sxLine.startsWith("Disallow:")) { vtRobots.add(sxLine.substring(10)); } } } catch (Exception e) { PetstoreUtil.getLogger().log(Level.SEVERE, "Exception" + e); vtRobots = null; } finally { try { if (bfReader != null) { bfReader.close(); } } catch (Exception ee) { } } return vtRobots; }
Code Sample 2:
public void init(File file) { InputStream is = null; ByteArrayOutputStream os = null; try { is = new FileInputStream(file); os = new ByteArrayOutputStream(); IOUtils.copy(is, os); } catch (Throwable e) { throw new VisualizerEngineException("Unexcpected exception while reading MDF file", e); } if (simulationEngine != null) simulationEngine.stopSimulation(); simulationEngine = new TrafficAsynchSimulationEngine(); simulationEngine.init(MDFReader.read(os.toByteArray())); simulationEngineThread = null; }
|
00
|
Code Sample 1:
public void readEntry(String name, InputStream input) throws Exception { File file = new File(this.directory, name); OutputStream output = new BufferedOutputStream(FileUtils.openOutputStream(file)); try { org.apache.commons.io.IOUtils.copy(input, output); } finally { output.close(); } }
Code Sample 2:
private void sendLocal() throws Exception { if (validParameters()) { URL url = new URL(storageUrlString); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); RequestUtils requestUtils = new RequestUtils(); requestUtils.preRequestAddParameter("senderObj", "QuotaSender"); requestUtils.preRequestAddParameter("beanNumbers", new String().valueOf(quotaBeans.size())); for (int vPos = 0; vPos < quotaBeans.size(); vPos++) { QuotaBean bean = (QuotaBean) quotaBeans.get(vPos); requestUtils.preRequestAddParameter("" + vPos + "#portalID", bean.getPortalID()); requestUtils.preRequestAddParameter("" + vPos + "#userID", bean.getUserID()); requestUtils.preRequestAddParameter("" + vPos + "#workflowID", bean.getWorkflowID()); requestUtils.preRequestAddParameter("" + vPos + "#runtimeID", bean.getRuntimeID()); requestUtils.preRequestAddParameter("" + vPos + "#plussQuotaSize", bean.getPlussQuotaSize().toString()); } requestUtils.preRequestAddFile("zipFileName", "dummyZipFileName.zip"); requestUtils.createPostRequest(); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + requestUtils.getBoundary()); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); httpURLConnection.setDoInput(true); try { httpURLConnection.connect(); OutputStream out = httpURLConnection.getOutputStream(); byte[] preBytes = requestUtils.getPreRequestStringBytes(); out.write(preBytes); out.flush(); out.write(new String("dummyFile").getBytes()); byte[] postBytes = requestUtils.getPostRequestStringBytes(); out.write(postBytes); out.flush(); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); in.readLine(); in.close(); if (HttpURLConnection.HTTP_OK != httpURLConnection.getResponseCode()) { throw new Exception("response not HTTP_OK !"); } } catch (Exception e) { e.printStackTrace(); throw new Exception("Cannot connect to: " + storageUrlString, e); } } else { throw new Exception("Not valid parameters: quotaBeans !"); } }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
00
|
Code Sample 1:
public static String generateMessageId(String plain) { byte[] cipher = new byte[35]; String messageId = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(plain.getBytes()); cipher = md5.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < cipher.length; i++) { String hex = Integer.toHexString(0xff & cipher[i]); if (hex.length() == 1) sb.append('0'); sb.append(hex); } StringBuffer pass = new StringBuffer(); pass.append(sb.substring(0, 6)); pass.append("H"); pass.append(sb.substring(6, 11)); pass.append("H"); pass.append(sb.substring(11, 21)); pass.append("H"); pass.append(sb.substring(21)); messageId = new String(pass); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return messageId; }
Code Sample 2:
private void initialize() { if (!initialized) { if (context.getJavadocLinks() != null) { for (String url : context.getJavadocLinks()) { if (!url.endsWith("/")) { url += "/"; } StringWriter writer = new StringWriter(); try { IOUtils.copy(new URL(url + "package-list").openStream(), writer); } catch (Exception e) { e.printStackTrace(); continue; } StringTokenizer tokenizer2 = new StringTokenizer(writer.toString()); while (tokenizer2.hasMoreTokens()) { javadocByPackage.put(tokenizer2.nextToken(), url); } } } initialized = true; } }
|
11
|
Code Sample 1:
private final void saveCopy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } to = null; from = null; }
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 String ReadURLStringAndWrite(URL url, String str) throws Exception { String stringToReverse = URLEncoder.encode(str, "UTF-8"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(stringToReverse); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String decodedString; String back = ""; while ((decodedString = in.readLine()) != null) { back += decodedString + "\n"; } in.close(); return back; }
Code Sample 2:
public static String getHighlightBaseLib() throws Exception { StringBuffer highlightKey = new StringBuffer(); highlightKey.append("<c color=\"" + COLOR_BASELIB + "\">\n\t"); URL url = AbstractRunner.class.getResource("baselib.js"); if (url != null) { InputStream is = url.openStream(); InputStreamReader reader = new InputStreamReader(is, "UTF-8"); BufferedReader bfReader = new BufferedReader(reader); String tmp = null; do { tmp = bfReader.readLine(); if (tmp != null) { if (tmp.indexOf("function") > -1) { highlightKey.append("<w>" + (tmp.substring(tmp.indexOf("function") + 8, tmp.indexOf("(")).trim()) + "</w>\n\t"); } } } while (tmp != null); bfReader.close(); reader.close(); is.close(); } highlightKey.append("</c>"); return highlightKey.toString(); }
|
11
|
Code Sample 1:
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
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(); }
|
11
|
Code Sample 1:
public static boolean insert(final Departamento ObjDepartamento) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into departamento " + "(nome, sala, telefone, id_orgao)" + " values (?, ?, ?, ?)"; pst = c.prepareStatement(sql); pst.setString(1, ObjDepartamento.getNome()); pst.setString(2, ObjDepartamento.getSala()); pst.setString(3, ObjDepartamento.getTelefone()); pst.setInt(4, (ObjDepartamento.getOrgao()).getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[DepartamentoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
Code Sample 2:
private static int ejecutaUpdate(String database, String SQL) throws Exception { int i = 0; DBConnectionManager dbm = null; Connection bd = null; try { dbm = DBConnectionManager.getInstance(); bd = dbm.getConnection(database); Statement st = bd.createStatement(); i = st.executeUpdate(SQL); bd.commit(); st.close(); dbm.freeConnection(database, bd); } catch (Exception e) { log.error("SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (bd == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { bd.rollback(); excep = new Exception("SQL Error: " + SQL + " error: " + e); dbm.freeConnection(database, bd); } throw excep; } return i; }
|
11
|
Code Sample 1:
protected boolean loadJarLibrary(final String jarLib) { final String tempLib = System.getProperty("java.io.tmpdir") + File.separator + jarLib; boolean copied = IOUtils.copyFile(jarLib, tempLib); if (!copied) { return false; } System.load(tempLib); return true; }
Code Sample 2:
@Override public void run() { try { FileChannel in = new FileInputStream(inputfile).getChannel(); long pos = 0; for (int i = 1; i <= noofparts; i++) { FileChannel out = new FileOutputStream(outputfile.getAbsolutePath() + "." + "v" + i).getChannel(); status.setText("Rozdělovač: Rozděluji část " + i + ".."); if (remainingsize >= splitsize) { in.transferTo(pos, splitsize, out); pos += splitsize; remainingsize -= splitsize; } else { in.transferTo(pos, remainingsize, out); } pb.setValue(100 * i / noofparts); out.close(); } in.close(); if (deleteOnFinish) new File(inputfile + "").delete(); status.setText("Rozdělovač: Hotovo.."); JOptionPane.showMessageDialog(null, "Rozděleno!", "Rozdělovač", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ex) { } }
|
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 Image getPluginImage(Object plugin, String name) { try { try { URL url = getPluginImageURL(plugin, name); if (m_URLImageMap.containsKey(url)) return m_URLImageMap.get(url); InputStream is = url.openStream(); Image image; try { image = getImage(is); m_URLImageMap.put(url, image); } finally { is.close(); } return image; } catch (Throwable e) { } } catch (Throwable e) { } return null; }
|
11
|
Code Sample 1:
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
Code Sample 2:
public static void copy(File sourceFile, File destinationFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(destinationFile).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); }
|
00
|
Code Sample 1:
public JSONObject getSourceGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph src = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { src = manager.getSourceGraph(); if (src != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.BLUES); factory.visit(src); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No source graph loaded."); } } catch (Exception e) { e.printStackTrace(); return JSONUtils.SimpleJSONError("Cannot load source graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); }
Code Sample 2:
public static String md5(String string) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString((result[i] & 0xFF) | 0x100).toLowerCase().substring(1, 3)); } return hexString.toString(); }
|
00
|
Code Sample 1:
private void headinfoThread() { try { URLConnection urlc = resource.url.openConnection(); resource.setFileSize(urlc.getContentLength()); resource.setDate(urlc.getLastModified()); } catch (IOException e) { System.out.println("Error ResourceConnection, downloading headinfo"); System.out.println(e); } }
Code Sample 2:
public LineIterator iterator() { LineIterator ret; final String charsetname; final Charset charset; final CharsetDecoder charsetDecoder; synchronized (this) { charsetname = this.charsetname; charset = this.charset; charsetDecoder = this.charsetDecoder; } try { if (charsetDecoder != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charsetDecoder); else if (charset != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charset); else if (charsetname != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, Charset.forName(charsetname)); else ret = new LineIterator(this, url.openStream(), returnNullUponEof, (Charset) null); synchronized (openedIterators) { openedIterators.add(ret); } return ret; } catch (IOException e) { throw new IllegalStateException(e); } }
|
11
|
Code Sample 1:
private static boolean genCustomerLocationsFileAndCustomerIndexFile(String completePath, String masterFile, String CustLocationsFileName, String CustIndexFileName) { try { TIntObjectHashMap CustInfoHash = new TIntObjectHashMap(480189, 1); File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + masterFile); FileChannel inC = new FileInputStream(inFile).getChannel(); File outFile1 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel outC1 = new FileOutputStream(outFile1, true).getChannel(); File outFile2 = new File(completePath + fSep + "SmartGRAPE" + fSep + CustLocationsFileName); FileChannel outC2 = new FileOutputStream(outFile2, true).getChannel(); int fileSize = (int) inC.size(); int totalNoDataRows = fileSize / 7; for (int i = 1; i <= totalNoDataRows; i++) { ByteBuffer mappedBuffer = ByteBuffer.allocate(7); inC.read(mappedBuffer); mappedBuffer.position(0); short movieName = mappedBuffer.getShort(); int customer = mappedBuffer.getInt(); byte rating = mappedBuffer.get(); mappedBuffer.clear(); if (CustInfoHash.containsKey(customer)) { TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); locations.add(i); CustInfoHash.put(customer, locations); } else { TIntArrayList locations = new TIntArrayList(); locations.add(i); CustInfoHash.put(customer, locations); } } int[] customers = CustInfoHash.keys(); Arrays.sort(customers); int count = 1; for (int i = 0; i < customers.length; i++) { int customer = customers[i]; TIntArrayList locations = (TIntArrayList) CustInfoHash.get(customer); int noRatingsForCust = locations.size(); ByteBuffer outBuf1 = ByteBuffer.allocate(12); outBuf1.putInt(customer); outBuf1.putInt(count); outBuf1.putInt(count + noRatingsForCust - 1); outBuf1.flip(); outC1.write(outBuf1); count += noRatingsForCust; for (int j = 0; j < locations.size(); j++) { ByteBuffer outBuf2 = ByteBuffer.allocate(4); outBuf2.putInt(locations.get(j)); outBuf2.flip(); outC2.write(outBuf2); } } inC.close(); outC1.close(); outC2.close(); return true; } catch (IOException e) { System.err.println(e); return false; } }
Code Sample 2:
public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
|
11
|
Code Sample 1:
public void overwriteFileTest() throws Exception { File filefrom = new File("/tmp/from.txt"); File fileto = new File("/tmp/to.txt"); InputStream from = null; OutputStream to = null; try { from = new FileInputStream(filefrom); to = new FileOutputStream(fileto); 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) { from.close(); } if (to != null) { to.close(); } } }
Code Sample 2:
public static void copy(String sourceFile, String targetFile) throws IOException { FileChannel sourceChannel = new FileInputStream(sourceFile).getChannel(); FileChannel targetChannel = new FileOutputStream(targetFile).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); targetChannel.close(); }
|
00
|
Code Sample 1:
private long getLastModified(Set resourcePaths, Map jarPaths) throws Exception { long lastModified = 0; Iterator paths = resourcePaths.iterator(); while (paths.hasNext()) { String path = (String) paths.next(); URL url = context.getServletContext().getResource(path); if (url == null) { log.debug("Null url " + path); break; } long lastM = url.openConnection().getLastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + path + " " + lastM); } } if (jarPaths != null) { paths = jarPaths.values().iterator(); while (paths.hasNext()) { File jarFile = (File) paths.next(); long lastM = jarFile.lastModified(); if (lastM > lastModified) lastModified = lastM; if (log.isDebugEnabled()) { log.debug("Last modified " + jarFile.getAbsolutePath() + " " + lastM); } } } return lastModified; }
Code Sample 2:
public boolean authenticate(String user, String pass) throws IOException { MessageDigest hash = null; try { MessageDigest.getInstance("BrokenMD4"); } catch (NoSuchAlgorithmException x) { throw new Error(x); } hash.update(new byte[4], 0, 4); try { hash.update(pass.getBytes("US-ASCII"), 0, pass.length()); hash.update(challenge.getBytes("US-ASCII"), 0, challenge.length()); } catch (java.io.UnsupportedEncodingException shouldNeverHappen) { } String response = Util.base64(hash.digest()); Util.writeASCII(out, user + " " + response + '\n'); String reply = Util.readLine(in); if (reply.startsWith(RSYNCD_OK)) { authReqd = false; return true; } connected = false; error = reply; return false; }
|
11
|
Code Sample 1:
public void processExplicitSchemaAndWSDL(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { HashMap services = configContext.getAxisConfiguration().getServices(); String filePart = req.getRequestURL().toString(); String schema = filePart.substring(filePart.lastIndexOf("/") + 1, filePart.length()); if ((services != null) && !services.isEmpty()) { Iterator i = services.values().iterator(); while (i.hasNext()) { AxisService service = (AxisService) i.next(); InputStream stream = service.getClassLoader().getResourceAsStream("META-INF/" + schema); if (stream != null) { OutputStream out = res.getOutputStream(); res.setContentType("text/xml"); IOUtils.copy(stream, out, true); return; } } } }
Code Sample 2:
private MimeTypesProvider() { File mimeTypesFile = new File(XPontusConstantsIF.XPONTUS_HOME_DIR, "mimes.properties"); try { if (!mimeTypesFile.exists()) { OutputStream os = null; InputStream is = getClass().getResourceAsStream("/net/sf/xpontus/configuration/mimetypes.properties"); os = FileUtils.openOutputStream(mimeTypesFile); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } provider = new XPontusMimetypesFileTypeMap(mimeTypesFile.getAbsolutePath()); MimetypesFileTypeMap.setDefaultFileTypeMap(provider); } catch (Exception err) { err.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void copyFiles(String strPath, String trgPath) { File src = new File(strPath); File trg = new File(trgPath); if (src.isDirectory()) { if (trg.exists() != true) trg.mkdirs(); String list[] = src.list(); for (int i = 0; i < list.length; i++) { String strPath_1 = src.getAbsolutePath() + SEPARATOR + list[i]; String trgPath_1 = trg.getAbsolutePath() + SEPARATOR + list[i]; copyFiles(strPath_1, trgPath_1); } } else { try { FileChannel srcChannel = new FileInputStream(strPath).getChannel(); FileChannel dstChannel = new FileOutputStream(trgPath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (FileNotFoundException e) { System.out.println("[Error] File not found: " + e.getMessage()); } catch (IOException e) { System.out.println("[Error] " + e.getMessage()); } } }
Code Sample 2:
private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
00
|
Code Sample 1:
public static StringBuffer readURLText(URL url, StringBuffer errorText) { StringBuffer page = new StringBuffer(""); String thisLine; try { BufferedReader source = new BufferedReader(new InputStreamReader(url.openStream())); while ((thisLine = source.readLine()) != null) { page.append(thisLine + "\n"); } return page; } catch (Exception e) { return errorText; } }
Code Sample 2:
public void writeTo(File f) throws IOException { if (state != STATE_OK) throw new IllegalStateException("Upload failed"); if (tempLocation == null) throw new IllegalStateException("File already saved"); if (f.isDirectory()) f = new File(f, filename); FileInputStream fis = new FileInputStream(tempLocation); FileOutputStream fos = new FileOutputStream(f); byte[] buf = new byte[BUFFER_SIZE]; try { int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } finally { deleteTemporaryFile(); fis.close(); fos.close(); } }
|
00
|
Code Sample 1:
private void updateSystem() throws IOException { String stringUrl="http://code.google.com/p/senai-pe-cronos/downloads/list"; try { url = new URL(stringUrl); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream is = url.openStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String linha = br.readLine(); while (linha != null) { linha = br.readLine(); if(linha.contains("/files/updateCronos-0-")){ String[] s=linha.split("-"); String[] v=s[4].split(".exe"); versao=v[0]; println("----"+versao); break; } } stringUrl="http://senai-pe-cronos.googlecode.com/files/updateCronos-0-"+versao+".exe"; UpdateCronos update=new UpdateCronos(); try { url = new URL(stringUrl); } catch (MalformedURLException ex) { ex.printStackTrace(); } System.out.println("versão:"+versao); if(Integer.parseInt(versao)>version){ File f = update.gravaArquivoDeURL(url,System.getProperty("user.dir"),String.valueOf(version),versao); if(update.isS()) { Runtime.getRuntime().exec(location+"\\update.exe"); System.exit(0); } } }
Code Sample 2:
public File createTemporaryFile() throws IOException { URL url = clazz.getResource(resource); if (url == null) { throw new IOException("No resource available from '" + clazz.getName() + "' for '" + resource + "'"); } String extension = getExtension(resource); String prefix = "resource-temporary-file-creator"; File file = File.createTempFile(prefix, extension); InputStream input = url.openConnection().getInputStream(); FileOutputStream output = new FileOutputStream(file); com.volantis.synergetics.io.IOUtils.copyAndClose(input, output); return file; }
|
11
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String contentId = req.getParameter(CONTENT_ID); String contentType = req.getParameter(CONTENT_TYPE); if (contentId == null || contentType == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Content id or content type not specified"); return; } try { switch(ContentType.valueOf(contentType)) { case IMAGE: resp.setContentType("image/jpeg"); break; case AUDIO: resp.setContentType("audio/mp3"); break; case VIDEO: resp.setContentType("video/mpeg"); break; default: throw new IllegalStateException("Invalid content type specified"); } } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid content type specified"); return; } String baseUrl = this.getServletContext().getInitParameter(BASE_URL); URL url = new URL(baseUrl + "/" + contentType.toLowerCase() + "/" + contentId); URLConnection conn = url.openConnection(); resp.setContentLength(conn.getContentLength()); IOUtils.copy(conn.getInputStream(), resp.getOutputStream()); }
Code Sample 2:
public static void saveZipComponents(ZipComponents zipComponents, File zipFile) throws FileNotFoundException, IOException, Exception { ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(zipFile)); for (ZipComponent comp : zipComponents.getComponents()) { ZipEntry newEntry = new ZipEntry(comp.getName()); zipOutStream.putNextEntry(newEntry); if (comp.isDirectory()) { } else { if (comp.getName().endsWith("document.xml") || comp.getName().endsWith("document.xml.rels")) { } InputStream inputStream = comp.getInputStream(); IOUtils.copy(inputStream, zipOutStream); inputStream.close(); } } zipOutStream.close(); }
|
00
|
Code Sample 1:
private ScrollingGraphicalViewer createGraphicalViewer(final Composite parent) { final ScrollingGraphicalViewer viewer = new ScrollingGraphicalViewer(); viewer.createControl(parent); _root = new EditRootEditPart(); viewer.setRootEditPart(_root); getEditDomain().addViewer(viewer); getSite().setSelectionProvider(viewer); viewer.setEditPartFactory(getEditPartFactory()); final KeyHandler keyHandler = new GraphicalViewerKeyHandler(viewer) { @SuppressWarnings("unchecked") @Override public boolean keyPressed(final KeyEvent event) { if (event.stateMask == SWT.MOD1 && event.keyCode == SWT.DEL) { final List<? extends EditorPart> objects = viewer.getSelectedEditParts(); if (objects == null || objects.isEmpty()) return true; final GroupRequest deleteReq = new GroupRequest(RequestConstants.REQ_DELETE); final CompoundCommand compoundCmd = new CompoundCommand("Delete"); for (int i = 0; i < objects.size(); i++) { final EditPart object = (EditPart) objects.get(i); deleteReq.setEditParts(object); final Command cmd = object.getCommand(deleteReq); if (cmd != null) compoundCmd.add(cmd); } getCommandStack().execute(compoundCmd); return true; } if (event.stateMask == SWT.MOD3 && (event.keyCode == SWT.ARROW_DOWN || event.keyCode == SWT.ARROW_LEFT || event.keyCode == SWT.ARROW_RIGHT || event.keyCode == SWT.ARROW_UP)) { final List<? extends EditorPart> objects = viewer.getSelectedEditParts(); if (objects == null || objects.isEmpty()) return true; final GroupRequest moveReq = new ChangeBoundsRequest(RequestConstants.REQ_MOVE); final CompoundCommand compoundCmd = new CompoundCommand("Move"); for (int i = 0; i < objects.size(); i++) { final EditPart object = (EditPart) objects.get(i); moveReq.setEditParts(object); final LocationCommand cmd = (LocationCommand) object.getCommand(moveReq); if (cmd != null) { cmd.setLocation(new Point(event.keyCode == SWT.ARROW_LEFT ? -1 : event.keyCode == SWT.ARROW_RIGHT ? 1 : 0, event.keyCode == SWT.ARROW_DOWN ? 1 : event.keyCode == SWT.ARROW_UP ? -1 : 0)); cmd.setRelative(true); compoundCmd.add(cmd); } } getCommandStack().execute(compoundCmd); return true; } return super.keyPressed(event); } }; keyHandler.put(KeyStroke.getPressed(SWT.F2, 0), getActionRegistry().getAction(GEFActionConstants.DIRECT_EDIT)); viewer.setKeyHandler(keyHandler); viewer.setContents(getEditorInput().getAdapter(NamedUuidEntity.class)); viewer.addDropTargetListener(createTransferDropTargetListener(viewer)); return viewer; }
Code Sample 2:
public void delete(String fileToDelete) throws IOException { FTPClient ftp = new FTPClient(); try { int reply = 0; ftp.connect(this.endpointURL, Config.getFtpPort()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp delete server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.enterLocalPassiveMode(); log.debug("Deleted: " + ftp.deleteFile(fileToDelete)); ftp.logout(); } catch (Exception e) { throw new IOException(e.getMessage()); } }
|
11
|
Code Sample 1:
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext context = getServletContext(); String forw = null; try { int maxUploadSize = 50000000; MultipartRequest multi = new MultipartRequest(request, ".", maxUploadSize); String descrizione = multi.getParameter("text"); File myFile = multi.getFile("uploadfile"); String filePath = multi.getOriginalFileName("uploadfile"); String path = "C:\\files\\"; try { FileInputStream inStream = new FileInputStream(myFile); FileOutputStream outStream = new FileOutputStream(path + myFile.getName()); while (inStream.available() > 0) { outStream.write(inStream.read()); } inStream.close(); outStream.close(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } forw = "../sendDoc.jsp"; request.setAttribute("contentType", context.getMimeType(path + myFile.getName())); request.setAttribute("text", descrizione); request.setAttribute("path", path + myFile.getName()); request.setAttribute("size", Long.toString(myFile.length()) + " Bytes"); RequestDispatcher rd = request.getRequestDispatcher(forw); rd.forward(request, response); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
public void copyFile(String oldPath, String newPath) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPath); if (oldfile.exists()) { InputStream inStream = new FileInputStream(oldPath); FileOutputStream fs = new FileOutputStream(newPath); byte[] buffer = new byte[1444]; while ((byteread = inStream.read(buffer)) != -1) { bytesum += byteread; fs.write(buffer, 0, byteread); } inStream.close(); fs.close(); } } catch (Exception e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } }
Code Sample 2:
private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } }
|
00
|
Code Sample 1:
private static void ftpTest() { FTPClient f = new FTPClient(); try { f.connect("oscomak.net"); System.out.print(f.getReplyString()); f.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String password = JOptionPane.showInputDialog("Enter password"); if (password == null || password.equals("")) { System.out.println("No password"); return; } try { f.login("oscomak_pointrel", password); System.out.print(f.getReplyString()); } catch (IOException e) { e.printStackTrace(); } try { String workingDirectory = f.printWorkingDirectory(); System.out.println("Working directory: " + workingDirectory); System.out.print(f.getReplyString()); } catch (IOException e1) { e1.printStackTrace(); } try { f.enterLocalPassiveMode(); System.out.print(f.getReplyString()); System.out.println("Trying to list files"); String[] fileNames = f.listNames(); System.out.print(f.getReplyString()); System.out.println("Got file list fileNames: " + fileNames.length); for (String fileName : fileNames) { System.out.println("File: " + fileName); } System.out.println(); System.out.println("done reading stream"); System.out.println("trying alterative way to read stream"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); f.retrieveFile(fileNames[0], outputStream); System.out.println("size: " + outputStream.size()); System.out.println(outputStream.toString()); System.out.println("done with alternative"); System.out.println("Trying to store file back"); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); boolean storeResult = f.storeFile("test.txt", inputStream); System.out.println("Done storing " + storeResult); f.disconnect(); System.out.print(f.getReplyString()); System.out.println("disconnected"); } catch (IOException e) { e.printStackTrace(); } }
Code Sample 2:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { FileChannel fc = new FileOutputStream("src/com/aaron/nio/data.txt").getChannel(); fc.write(ByteBuffer.wrap("dfsdf ".getBytes())); fc.close(); fc = new RandomAccessFile("src/com/aaron/nio/data.txt", "rw").getChannel(); fc.position(fc.size()); fc.write(ByteBuffer.wrap("中文的 ".getBytes())); fc.close(); fc = new FileInputStream("src/com/aaron/nio/data.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(1024); fc.read(buff); buff.flip(); while (buff.hasRemaining()) { System.out.print(buff.getChar()); } fc.close(); }
Code Sample 2:
public LocalizationSolver(String name, String serverIP, int portNum, String workDir) { this.info = new HashMap<String, Object>(); this.workDir = workDir; try { Socket solverSocket = new Socket(serverIP, portNum); this.fromServer = new Scanner(solverSocket.getInputStream()); this.toServer = new PrintWriter(solverSocket.getOutputStream(), true); this.toServer.println("login client abc"); this.toServer.println("solver " + name); System.out.println(this.fromServer.nextLine()); } catch (IOException e) { System.err.println(e); e.printStackTrace(); System.exit(1); } System.out.println("Localization Solver started with name: " + name); }
|
11
|
Code Sample 1:
public static String getMD5(final String text) { if (null == text) return null; final MessageDigest algorithm; try { algorithm = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } algorithm.reset(); algorithm.update(text.getBytes()); final byte[] digest = algorithm.digest(); final StringBuffer hexString = new StringBuffer(); for (byte b : digest) { String str = Integer.toHexString(0xFF & b); str = str.length() == 1 ? '0' + str : str; hexString.append(str); } return hexString.toString(); }
Code Sample 2:
public static String encode(String arg) { if (arg == null) { arg = ""; } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(arg.getBytes(JavaCenterHome.JCH_CHARSET)); } catch (Exception e) { e.printStackTrace(); } return toHex(md5.digest()); }
|
11
|
Code Sample 1:
public static void copy(File source, File destination) { try { FileInputStream fileInputStream = new FileInputStream(source); FileOutputStream fileOutputStream = new FileOutputStream(destination); FileChannel inputChannel = fileInputStream.getChannel(); FileChannel outputChannel = fileOutputStream.getChannel(); transfer(inputChannel, outputChannel, source.length(), 1024 * 1024 * 32, true, true); fileInputStream.close(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } }
Code Sample 2:
@RequestMapping("/download") public void download(HttpServletRequest request, HttpServletResponse response) { InputStream input = null; ServletOutputStream output = null; try { String savePath = request.getSession().getServletContext().getRealPath("/upload"); String fileType = ".log"; String dbFileName = "83tomcat日志测试哦"; String downloadFileName = dbFileName + fileType; String finalPath = "\\2011-12\\01\\8364b45f-244d-41b6-bbf48df32064a935"; downloadFileName = new String(downloadFileName.getBytes("GBK"), "ISO-8859-1"); File downloadFile = new File(savePath + finalPath); if (!downloadFile.getParentFile().exists()) { downloadFile.getParentFile().mkdirs(); } if (!downloadFile.isFile()) { FileUtils.touch(downloadFile); } response.setContentType("aapplication/vnd.ms-excel ;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("content-disposition", "attachment; filename=" + downloadFileName); input = new FileInputStream(downloadFile); output = response.getOutputStream(); IOUtils.copy(input, output); output.flush(); } catch (Exception e) { logger.error("Exception: ", e); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
|
00
|
Code Sample 1:
public void refreshFileItem(YahooInfo legroup) throws Exception { String lapage = new String(""); String ledir = new String(""); Pattern pat; Matcher mat; Pattern pat2; Matcher mat2; int data; URL myurl = new URL("http://groups.yahoo.com/mygroups"); URLConnection conn; URI myuri = new URI("http://groups.yahoo.com/mygroups"); YahooInfo yi; clearItem(legroup); for (int i = 0; i < UrlList.size(); i++) { if (UrlList.get(i).getGroup().equals(legroup.getGroup()) && UrlList.get(i).getDir().startsWith(legroup.getDir())) { if (UrlList.get(i).isGroup()) { System.out.print(UrlList.get(i).getGroup() + " : "); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); conn = myurl.openConnection(); conn.connect(); System.out.println(conn.getHeaderField(0).toString()); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<li> <a href=\"(.+?)\".*?>Files</a></li>"); mat = pat.matcher(lapage); if (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), "/", "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } } if (UrlList.get(i).isDir()) { System.out.println(UrlList.get(i).getGroup() + UrlList.get(i).getDir()); myuri = new URI(UrlList.get(i).getUrl()); myurl = new URL(UrlList.get(i).getUrl()); do { myurl = new URL(myurl.toString()); conn = myurl.openConnection(); conn.connect(); if (!Pattern.matches("HTTP/... 2.. .*", conn.getHeaderField(0).toString())) { System.out.println(conn.getHeaderField(0).toString()); return; } System.out.print("p"); InputStream in = conn.getInputStream(); lapage = ""; for (data = in.read(); data != -1; data = in.read()) lapage += (char) data; pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?/)\">(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { ledir = new String(UrlList.get(i).getDir()); pat2 = Pattern.compile("([A-Za-z0-9]+)"); mat2 = pat2.matcher(mat.group(2)); while (mat2.find()) { ledir += mat2.group(1); } ledir += "/"; yi = new YahooInfo(UrlList.get(i).getGroup(), ledir, "", myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } pat = Pattern.compile("<span class=\"title\">\n<a href=\"(.+?yahoofs.+?)\".*?>(.+?)</a>"); mat = pat.matcher(lapage); while (mat.find()) { yi = new YahooInfo(UrlList.get(i).getGroup(), UrlList.get(i).getDir(), mat.group(2), myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL().toString()); UrlList.add(yi); } System.out.println(""); pat = Pattern.compile("<a href=\"(.+?)\">Next"); mat = pat.matcher(lapage); myurl = null; if (mat.find()) { myurl = myuri.resolve(HTMLDecoder.decode(mat.group(1))).toURL(); } } while (myurl != null); } } } }
Code Sample 2:
private Document getResponse(HttpGet request) throws ClientProtocolException, IOException, ParserConfigurationException, IllegalStateException, SAXException, NoRoutesException { HttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() != HTTP_STATUS_OK) throw new ClientProtocolException("The HTTP request is wrong."); allResponse = EntityUtils.toString(response.getEntity()); String responseText = ""; switch(modeOption) { case DRIVING: try { responseText = allResponse.substring(allResponse.indexOf("<ol"), allResponse.indexOf("</ol>") + 5); } catch (Exception e) { throw new NoRoutesException(); } break; case WALKING: try { responseText = allResponse.substring(allResponse.indexOf("<ol"), allResponse.indexOf("</ol>") + 5); } catch (Exception e) { throw new NoRoutesException(); } break; case PUBLIC_TRANSIT: String responseWithErrors = ""; try { responseWithErrors = allResponse.substring(allResponse.indexOf("<div id=\"tsp\">"), allResponse.indexOf("<div class=\"ddwpt\" id=\"panel_ddw1\" oi=\"wi1\">")); } catch (Exception e) { throw new NoRoutesException(); } responseText = responseWithErrors.replaceAll(".gif\">", ".gif\"/>").replaceAll("colspan=2", "colspan=\"2\"").replaceAll("nowrap", "").replaceAll("«", "").replaceAll(" ", "").replaceAll("»", ""); break; } File xmlFile = new File("./data/temp/response.xml"); PrintWriter writer = new PrintWriter(xmlFile); writer.println(responseText); writer.close(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); return dBuilder.parse(xmlFile); }
|
00
|
Code Sample 1:
public static boolean buildCFItem2ItemStats(String outFileName, String movieAvgFileName, String custAvgFileName) { try { File infile = new File(completePath + fSep + "SmartGRAPE" + fSep + movieAvgFileName); FileChannel inC = new FileInputStream(infile).getChannel(); int size = (int) inC.size(); ByteBuffer map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TShortFloatHashMap movieAverages = new TShortFloatHashMap(17770, 1); inC.close(); while (map.hasRemaining()) { movieAverages.put(map.getShort(), map.getFloat()); } map = null; infile = new File(completePath + fSep + "SmartGRAPE" + fSep + custAvgFileName); inC = new FileInputStream(infile).getChannel(); size = (int) inC.size(); map = inC.map(FileChannel.MapMode.READ_ONLY, 0, size); TIntFloatHashMap custAverages = new TIntFloatHashMap(480189, 1); inC.close(); while (map.hasRemaining()) { custAverages.put(map.getInt(), map.getFloat()); } File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + outFileName); FileChannel outC = new FileOutputStream(outfile, true).getChannel(); short[] movies = CustomersAndRatingsPerMovie.keys(); Arrays.sort(movies); int noMovies = movies.length; for (int i = 0; i < noMovies - 1; i++) { short movie1 = movies[i]; TIntByteHashMap testMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie1); int[] customers1 = testMovieCustAndRatingsMap.keys(); Arrays.sort(customers1); System.out.println("Processing movie: " + movie1); for (int j = i + 1; j < noMovies; j++) { short movie2 = movies[j]; TIntByteHashMap otherMovieCustAndRatingsMap = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(movie2); int[] customers2 = otherMovieCustAndRatingsMap.keys(); TIntArrayList intersectSet = CustOverLapForTwoMoviesCustom(customers1, customers2); int count = 0; float diffRating = 0; float pearsonCorr = 0; float cosineCorr = 0; float adjustedCosineCorr = 0; float sumX = 0; float sumY = 0; float sumXY = 0; float sumX2 = 0; float sumY2 = 0; float sumXYPearson = 0; float sumX2Pearson = 0; float sumY2Pearson = 0; float sumXYACos = 0; float sumX2ACos = 0; float sumY2ACos = 0; if ((intersectSet.size() == 0) || (intersectSet == null)) { count = 0; diffRating = 0; } else { count = intersectSet.size(); for (int l = 0; l < count; l++) { int commonCust = intersectSet.getQuick(l); byte ratingX = testMovieCustAndRatingsMap.get(commonCust); sumX += ratingX; byte ratingY = otherMovieCustAndRatingsMap.get(commonCust); sumY += ratingY; sumX2 += ratingX * ratingX; sumY2 += ratingY * ratingY; sumXY += ratingX * ratingY; diffRating += ratingX - ratingY; sumXYPearson += (ratingX - movieAverages.get(movie1)) * (ratingY - movieAverages.get(movie2)); sumX2Pearson += Math.pow((ratingX - movieAverages.get(movie1)), 2); sumY2Pearson += Math.pow((ratingY - movieAverages.get(movie2)), 2); float custAverage = custAverages.get(commonCust); sumXYACos += (ratingX - custAverage) * (ratingY - custAverage); sumX2ACos += Math.pow((ratingX - custAverage), 2); sumY2ACos += Math.pow((ratingY - custAverage), 2); } } double pearsonDenominator = Math.sqrt(sumX2Pearson) * Math.sqrt(sumY2Pearson); if (pearsonDenominator == 0.0) { pearsonCorr = 0; } else { pearsonCorr = new Double(sumXYPearson / pearsonDenominator).floatValue(); } double adjCosineDenominator = Math.sqrt(sumX2ACos) * Math.sqrt(sumY2ACos); if (adjCosineDenominator == 0.0) { adjustedCosineCorr = 0; } else { adjustedCosineCorr = new Double(sumXYACos / adjCosineDenominator).floatValue(); } double cosineDenominator = Math.sqrt(sumX2) * Math.sqrt(sumY2); if (cosineDenominator == 0.0) { cosineCorr = 0; } else { cosineCorr = new Double(sumXY / cosineDenominator).floatValue(); } ByteBuffer buf = ByteBuffer.allocate(44); buf.putShort(movie1); buf.putShort(movie2); buf.putInt(count); buf.putFloat(diffRating); buf.putFloat(sumXY); buf.putFloat(sumX); buf.putFloat(sumY); buf.putFloat(sumX2); buf.putFloat(sumY2); buf.putFloat(pearsonCorr); buf.putFloat(adjustedCosineCorr); buf.putFloat(cosineCorr); buf.flip(); outC.write(buf); buf.clear(); } } outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Code Sample 2:
@Override protected RemoteInvocationResult doExecuteRequest(HttpInvokerClientConfiguration config, ByteArrayOutputStream baos) throws IOException, ClassNotFoundException { HttpPost postMethod = new HttpPost(config.getServiceUrl()); postMethod.setEntity(new ByteArrayEntity(baos.toByteArray())); HttpResponse rsp = httpClient.execute(postMethod); StatusLine sl = rsp.getStatusLine(); if (sl.getStatusCode() >= 300) { throw new IOException("Did not receive successful HTTP response: status code = " + sl.getStatusCode() + ", status message = [" + sl.getReasonPhrase() + "]"); } HttpEntity entity = rsp.getEntity(); InputStream responseBody = entity.getContent(); return readRemoteInvocationResult(responseBody, config.getCodebaseUrl()); }
|
00
|
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:
public static String URLtoString(URL url) throws IOException { String xml = null; if (url != null) { URLConnection con = url.openConnection(); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); InputStream is = con.getInputStream(); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); byte[] bytes = new byte[512]; for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) { buffer.write(bytes, 0, i); } xml = new String(buffer.toByteArray()); is.close(); buffer.close(); } return xml; }
|
00
|
Code Sample 1:
public static Vector<String> readFileFromURL(URL url) { Vector<String> text = new Vector<String>(); try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { text.add(line); } in.close(); } catch (Exception e) { return null; } return text; }
Code Sample 2:
private static String getRegistrationClasses() { CentralRegistrationClass c = new CentralRegistrationClass(); String name = c.getClass().getCanonicalName().replace('.', '/').concat(".class"); try { Enumeration<URL> urlEnum = c.getClass().getClassLoader().getResources("META-INF/MANIFEST.MF"); while (urlEnum.hasMoreElements()) { URL url = urlEnum.nextElement(); String file = url.getFile(); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); Manifest mf = jarConnection.getManifest(); Attributes attrs = (Attributes) mf.getAttributes(name); if (attrs != null) { String classes = attrs.getValue("RegistrationClasses"); return classes; } } } catch (IOException ex) { ex.printStackTrace(); } return ""; }
|
11
|
Code Sample 1:
@SmallTest public void testSha1() throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA-1"); int numTests = mTestData.length; for (int i = 0; i < numTests; i++) { digest.update(mTestData[i].input.getBytes()); byte[] hash = digest.digest(); String encodedHash = encodeHex(hash); assertEquals(encodedHash, mTestData[i].result); } }
Code Sample 2:
PasswordTableWindow(String login) { super(login + ", tecle a senha de uso �nico"); this.login = login; Error.log(4001, "Autentica��o etapa 3 iniciada."); Container container = getContentPane(); container.setLayout(new FlowLayout()); btnNumber = new JButton[10]; btnOK = new JButton("OK"); btnClear = new JButton("Limpar"); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(2, 10)); ResultSet rs; Statement stmt; String sql; Vector<Integer> result = new Vector<Integer>(); sql = "select key from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result.add(rs.getInt("key")); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r = rn.nextInt(); if (result.size() == 0) { rn = new Random(); Vector<Integer> passwordVector = new Vector<Integer>(); Vector<String> hashVector = new Vector<String>(); for (int i = 0; i < 10; i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < 10; i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < 10; i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } JOptionPane.showMessageDialog(null, "nova tabela de senhas criada para o usu�rio " + login + "."); Error.log(1002, "Sistema encerrado"); System.exit(0); } if (r < 0) r = r * (-1); int index = r % result.size(); if (index > result.size()) index = 0; key = result.get(index); labelKey = new JLabel("Chave n�mero " + key + " "); passwordField = new JPasswordField(12); ButtonHandler handler = new ButtonHandler(); for (int i = 0; i < 10; i++) { btnNumber[i] = new JButton("" + i); buttonPanel.add(btnNumber[i]); btnNumber[i].addActionListener(handler); } btnOK.addActionListener(handler); btnClear.addActionListener(handler); container.add(buttonPanel); container.add(passwordField); container.add(labelKey); container.add(btnOK); container.add(btnClear); setSize(325, 200); setVisible(true); }
|
11
|
Code Sample 1:
public void zipDocsetFiles(SaxHandler theXmlHandler, int theEventId, Attributes theAtts) throws BpsProcessException { ZipOutputStream myZipOut = null; BufferedInputStream myDocumentInputStream = null; String myFinalFile = null; String myTargetPath = null; String myTargetFileName = null; String myInputFileName = null; byte[] myBytesBuffer = null; int myLength = 0; try { myZipOut = new ZipOutputStream(new FileOutputStream(myFinalFile)); myZipOut.putNextEntry(new ZipEntry(myTargetPath + myTargetFileName)); myDocumentInputStream = new BufferedInputStream(new FileInputStream(myInputFileName)); while ((myLength = myDocumentInputStream.read(myBytesBuffer, 0, 4096)) != -1) myZipOut.write(myBytesBuffer, 0, myLength); myZipOut.closeEntry(); myZipOut.close(); } catch (FileNotFoundException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "FileNotFoundException while building zip dest file")); } catch (IOException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "IOException while building zip dest file")); } }
Code Sample 2:
public static void fileCopy(File src, File dest) throws IOException { IOException xforward = null; FileInputStream fis = null; FileOutputStream fos = null; FileChannel fcin = null; FileChannel fcout = null; try { fis = new FileInputStream(src); fos = new FileOutputStream(dest); fcin = fis.getChannel(); fcout = fos.getChannel(); final int MB32 = 32 * 1024 * 1024; long size = fcin.size(); long position = 0; while (position < size) { position += fcin.transferTo(position, MB32, fcout); } } catch (IOException xio) { xforward = xio; } finally { if (fis != null) try { fis.close(); fis = null; } catch (IOException xio) { } if (fos != null) try { fos.close(); fos = null; } catch (IOException xio) { } if (fcin != null && fcin.isOpen()) try { fcin.close(); fcin = null; } catch (IOException xio) { } if (fcout != null && fcout.isOpen()) try { fcout.close(); fcout = null; } catch (IOException xio) { } } if (xforward != null) { throw xforward; } }
|
00
|
Code Sample 1:
public static String sendGetRequest(String endpoint, String requestParameters) { String result = null; if (endpoint.startsWith("http://")) { try { StringBuffer data = new StringBuffer(); String urlStr = endpoint; if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line + "\n"); } rd.close(); result = sb.toString(); } catch (Exception e) { } } return result; }
Code Sample 2:
public static final boolean updateFDT(final String currentVersion, final String updateURL, boolean shouldUpdate, boolean noLock) throws Exception { final String partialURL = updateURL + (updateURL.endsWith("/") ? "" : "/") + "fdt.jar"; logger.log("Checking remote fdt.jar at URL: " + partialURL); String JVMVersion = "NotAvailable"; String JVMRuntimeVersion = "NotAvailable"; String OSVersion = "NotAvailable"; String OSName = "NotAvailable"; String OSArch = "NotAvailable"; try { JVMVersion = System.getProperty("java.vm.version"); } catch (Throwable t) { JVMVersion = "NotAvailable"; } try { JVMRuntimeVersion = System.getProperty("java.runtime.version"); } catch (Throwable t) { JVMRuntimeVersion = "NotAvailable"; } try { OSName = System.getProperty("os.name"); } catch (Throwable t) { OSName = "NotAvailable"; } try { OSArch = System.getProperty("os.arch"); } catch (Throwable t) { OSArch = "NotAvailable"; } try { OSVersion = System.getProperty("os.version"); } catch (Throwable t) { OSVersion = "NotAvailable"; } StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(partialURL); urlBuilder.append("?FDTCurrentVersion=").append(currentVersion); urlBuilder.append("&shouldUpdate=").append(shouldUpdate); urlBuilder.append("&tstamp=").append(System.currentTimeMillis()); urlBuilder.append("&java.vm.version=").append(JVMVersion); urlBuilder.append("&java.runtime.version=").append(JVMRuntimeVersion); urlBuilder.append("&os.name=").append(OSName); urlBuilder.append("&os.version=").append(OSVersion); urlBuilder.append("&os.arch=").append(OSArch); final Properties p = getFDTUpdateProperties(); if (p.getProperty("totalRead") == null) { p.put("totalRead", "0"); } if (p.getProperty("totalWrite") == null) { p.put("totalWrite", "0"); } checkAndSetInstanceID(p); if (p.getProperty("totalRead_rst") != null) { p.remove("totalRead_rst"); } if (p.getProperty("totalWrite_rst") != null) { p.remove("totalWrite_rst"); } if (p != null && p.size() > 0) { for (final Map.Entry<Object, Object> entry : p.entrySet()) { urlBuilder.append("&").append(entry.getKey()).append("=").append(entry.getValue()); } } final String finalPath = new URI(FDT.class.getProtectionDomain().getCodeSource().getLocation().toString()).getPath(); if (finalPath == null || finalPath.length() == 0) { throw new IOException("Cannot determine the path to current fdt jar"); } final File currentJar = new File(finalPath); if (!currentJar.exists()) { throw new IOException("Current fdt.jar path seems to be [ " + finalPath + " ] but the JVM cannot access it!"); } if (currentJar.isFile() && currentJar.canWrite()) { logger.log("\nCurrent fdt.jar path is: " + finalPath); } else { throw new IOException("Current fdt.jar path seems to be [ " + finalPath + " ] but it does not have write access!"); } File tmpUpdateFile = null; FileOutputStream fos = null; JarFile jf = null; InputStream connInputStream = null; try { tmpUpdateFile = File.createTempFile("fdt_update_tmp", ".jar"); tmpUpdateFile.deleteOnExit(); fos = new FileOutputStream(tmpUpdateFile); final URLConnection urlConnection = new URL(urlBuilder.toString()).openConnection(); urlConnection.setDefaultUseCaches(false); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(URL_CONNECTION_TIMEOUT); urlConnection.setReadTimeout(URL_CONNECTION_TIMEOUT); logger.log("Connecting ... "); urlConnection.connect(); connInputStream = urlConnection.getInputStream(); logger.log("OK"); byte[] buff = new byte[8192]; int count = 0; while ((count = connInputStream.read(buff)) > 0) { fos.write(buff, 0, count); } fos.flush(); jf = new JarFile(tmpUpdateFile); final Manifest mf = jf.getManifest(); final Attributes attr = mf.getMainAttributes(); final String remoteVersion = attr.getValue("Implementation-Version"); if (remoteVersion == null || remoteVersion.trim().length() == 0) { throw new Exception("Cannot read the version from the downloaded jar...Cannot compare versions!"); } if (currentVersion.equals(remoteVersion.trim())) { return false; } logger.log("Remote FDT version: " + remoteVersion + " Local FDT version: " + currentVersion + ". Update available."); if (shouldUpdate) { try { final String parent = currentJar.getParent(); if (parent == null) { logger.log("Unable to determine parent dir for: " + currentJar); throw new IOException("Unable to determine parent dir for: " + currentJar); } final File parentDir = new File(parent); if (!parentDir.canWrite()) { logger.log(Level.WARNING, "[ WARNING CHECK ] The OS reported that is unable to write in parent dir: " + parentDir + " continue anyway; the call might be broken."); } final File bkpJar = new File(parentDir.getPath() + File.separator + "fdt_" + Config.FDT_FULL_VERSION + ".jar"); boolean bDel = bkpJar.exists(); if (bDel) { bDel = bkpJar.delete(); if (!bDel) { logger.log("[ WARNING ] Unable to delete backup jar with the same version: " + bkpJar + " ... will continue"); } else { logger.log("[ INFO ] Backup jar (same version as the update) " + bkpJar + " delete it."); } } boolean renameSucced = currentJar.renameTo(bkpJar); if (!renameSucced) { logger.log(Level.WARNING, "Unable to create backup: " + bkpJar + " for current FDT before update."); } else { logger.log("Backing up old FDT succeeded: " + bkpJar); } } catch (Throwable t) { logger.log(Level.WARNING, "Unable to create a backup for current FDT before update. Exception: ", t); } copyFile2File(tmpUpdateFile, currentJar, noLock); } return true; } finally { closeIgnoringExceptions(connInputStream); closeIgnoringExceptions(fos); if (tmpUpdateFile != null) { try { tmpUpdateFile.delete(); } catch (Throwable ignore) { } } } }
|
00
|
Code Sample 1:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String version = req.getParameter("version"); String cdn = req.getParameter("cdn"); String dependencies = req.getParameter("dependencies"); String optimize = req.getParameter("optimize"); String cacheFile = null; String result = null; boolean isCached = false; Boolean isError = true; if (!version.equals("1.3.2")) { result = "invalid version: " + version; } if (!cdn.equals("google") && !cdn.equals("aol")) { result = "invalide CDN type: " + cdn; } if (!optimize.equals("comments") && !optimize.equals("shrinksafe") && !optimize.equals("none") && !optimize.equals("shrinksafe.keepLines")) { result = "invalid optimize type: " + optimize; } if (!dependencies.matches("^[\\w\\-\\,\\s\\.]+$")) { result = "invalid dependency list: " + dependencies; } try { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { result = e.getMessage(); } if (result == null) { md.update(dependencies.getBytes()); String digest = (new BASE64Encoder()).encode(md.digest()).replace('+', '~').replace('/', '_').replace('=', '_'); cacheFile = cachePath + "/" + version + "/" + cdn + "/" + digest + "/" + optimize + ".js"; File file = new File(cacheFile); if (file.exists()) { isCached = true; isError = false; } } if (result == null && !isCached) { BuilderContextAction contextAction = new BuilderContextAction(builderPath, version, cdn, dependencies, optimize); ContextFactory.getGlobal().call(contextAction); Exception exception = contextAction.getException(); if (exception != null) { result = exception.getMessage(); } else { result = contextAction.getResult(); FileUtil.writeToFile(cacheFile, result, null, true); isError = false; } } } catch (Exception e) { result = e.getMessage(); } res.setCharacterEncoding("utf-8"); if (isError) { result = result.replaceAll("\\\"", "\\\""); result = "<html><head><script type=\"text/javascript\">alert(\"" + result + "\");</script></head><body></body></html>"; PrintWriter writer = res.getWriter(); writer.append(result); } else { res.setHeader("Content-Type", "application/x-javascript"); res.setHeader("Content-disposition", "attachment; filename=dojo.js"); res.setHeader("Content-Encoding", "gzip"); File file = new File(cacheFile); BufferedInputStream in = new java.io.BufferedInputStream(new DataInputStream(new FileInputStream(file))); OutputStream out = res.getOutputStream(); byte[] bytes = new byte[64000]; int bytesRead = 0; while (bytesRead != -1) { bytesRead = in.read(bytes); if (bytesRead != -1) { out.write(bytes, 0, bytesRead); } } } }
Code Sample 2:
public boolean saveNote(NoteData n) { String query; try { conn.setAutoCommit(false); Statement stmt = null; ResultSet rset = null; stmt = conn.createStatement(); query = "select * from notes where noteid = " + n.getID(); rset = stmt.executeQuery(query); if (rset.next()) { query = "UPDATE notes SET title = '" + escapeCharacters(n.getTitle()) + "', keywords = '" + escapeCharacters(n.getKeywords()) + "' WHERE noteid = " + n.getID(); try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; PreparedStatement pstmt = conn.prepareStatement("UPDATE fielddata SET data = ? WHERE noteid = ? AND fieldid = ?"); try { while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(1, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(1, f.getData()); } pstmt.setInt(2, n.getID()); pstmt.setInt(3, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } query = "DELETE FROM links WHERE (note1id = " + n.getID() + " OR note2id = " + n.getID() + ")"; try { stmt.execute(query); } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> associations = n.getAssociations(); ListIterator<Link> itr = associations.listIterator(); Link association = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?, ?)"); try { while (itr.hasNext()) { association = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, association.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } else { query = "INSERT INTO notes (templateid, title, keywords) VALUES (" + n.getTemplate().getID() + ", '" + escapeCharacters(n.getTitle()) + "', '" + escapeCharacters(n.getKeywords()) + "')"; try { stmt.executeUpdate(query); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); conn.setAutoCommit(true); return false; } LinkedList<FieldData> fields = n.getFields(); ListIterator<FieldData> iter = fields.listIterator(0); FieldData f = null; n.setID(Integer.parseInt(executeMySQLGet("SELECT LAST_INSERT_ID()"))); PreparedStatement pstmt; try { pstmt = conn.prepareStatement("INSERT INTO fielddata (noteid, fieldid, data) VALUES (?,?,?)"); while (iter.hasNext()) { f = iter.next(); if (f instanceof FieldDataImage) { System.out.println("field is an image."); pstmt.setBytes(3, ((FieldDataImage) f).getDataBytes()); } else { System.out.println("field is not an image"); pstmt.setString(3, f.getData()); } pstmt.setInt(1, n.getID()); pstmt.setInt(2, f.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } Vector<Link> assoc = n.getAssociations(); Iterator<Link> itr = assoc.listIterator(); Link l = null; pstmt = conn.prepareStatement("INSERT INTO links (note1id, note2id) VALUES (?,?)"); try { while (itr.hasNext()) { l = itr.next(); pstmt.setInt(1, n.getID()); pstmt.setInt(2, l.getID()); pstmt.execute(); } } catch (SQLException e) { conn.rollback(); conn.setAutoCommit(true); e.printStackTrace(); return false; } } conn.commit(); conn.setAutoCommit(true); } catch (SQLException ex) { ex.printStackTrace(); return false; } return true; }
|
11
|
Code Sample 1:
public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; }
Code Sample 2:
public static String calcCRC(String phrase) { StringBuffer crcCalc = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(phrase.getBytes()); byte[] tabDigest = md.digest(); for (int i = 0; i < tabDigest.length; i++) { String octet = "0" + Integer.toHexString(tabDigest[i]); crcCalc.append(octet.substring(octet.length() - 2)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return crcCalc.toString(); }
|
00
|
Code Sample 1:
public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException { try { URL url = new URL(uri.toString()); final URLConnection urlConnection = url.openConnection(); InputStream result = urlConnection.getInputStream(); Map<Object, Object> response = getResponse(options); if (response != null) { response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, urlConnection.getLastModified()); } return result; } catch (RuntimeException exception) { throw new Resource.IOWrappedException(exception); } }
Code Sample 2:
private void doIt() throws Throwable { int numCachedTiles = 0; try { List<MapTile> backTiles = new ArrayList<MapTile>(); final LatLngRectangle bounds = new LatLngRectangle(new LatLngPoint(south, west), new LatLngPoint(north, east)); final String backMapGuid = "gst"; final XFile dstDir = new XFile(new XFile(Configuration.getInstance().getPublicMapStorage().toString()), backMapGuid); dstDir.mkdir(); for (int z = Math.min(Tile.getOptimalZoom(bounds, 768), 9); z <= 17; z++) { final Tile tileStart = new Tile(bounds.getSouthWest().getLat(), bounds.getSouthWest().getLng(), z); final Tile tileEnd = new Tile(bounds.getNorthEast().getLat(), bounds.getNorthEast().getLng(), z); for (double y = tileEnd.getTileCoord().getY(); y <= tileStart.getTileCoord().getY(); y++) for (double x = tileStart.getTileCoord().getX(); x <= tileEnd.getTileCoord().getX(); x++) { NASAMapTile tile = new NASAMapTile((int) x, (int) y, z); XFile file = new XFile(dstDir, tile.toKeyString()); if (file.exists() && file.isFile()) continue; backTiles.add(tile); } } logger.info(backTiles.size() + " tiles to cache"); for (MapTile tile : backTiles) { InputStream in = null; OutputStream out = null; final URL url = new URL(tile.getPath()); try { int i = 4; while (--i > 0) { final XFile outFile = new XFile(dstDir, tile.toKeyString()); final URLConnection conn = url.openConnection(); if (conn == null || !conn.getContentType().startsWith("image")) { logger.error("onearth.jpl.nasa.gov service returns non-image file, " + "content-type='" + conn.getContentType() + "'"); Thread.sleep(1000L * (long) Math.pow(2, 8 - i)); continue; } in = conn.getInputStream(); if (in != null) { out = new XFileOutputStream(outFile); IOUtils.copy(in, out); break; } else throw new IllegalStateException("opened stream is null"); } } finally { if (out != null) { out.flush(); out.close(); } if (in != null) in.close(); } if (++numCachedTiles % 10 == 0) { logger.info(numCachedTiles + " tiles cached"); Thread.sleep(sleep); } } } catch (Throwable e) { logger.error("map tile caching has failed: ", e); throw e; } }
|
00
|
Code Sample 1:
private static <T> Collection<T> loadFromServices(Class<T> interf) throws Exception { ClassLoader classLoader = DSServiceLoader.class.getClassLoader(); Enumeration<URL> e = classLoader.getResources("META-INF/services/" + interf.getName()); Collection<T> services = new ArrayList<T>(); while (e.hasMoreElements()) { URL url = e.nextElement(); InputStream is = url.openStream(); try { BufferedReader r = new BufferedReader(new InputStreamReader(is, "UTF-8")); while (true) { String line = r.readLine(); if (line == null) { break; } int comment = line.indexOf('#'); if (comment >= 0) { line = line.substring(0, comment); } String name = line.trim(); if (name.length() == 0) { continue; } Class<?> clz = Class.forName(name, true, classLoader); Class<? extends T> impl = clz.asSubclass(interf); Constructor<? extends T> ctor = impl.getConstructor(); T svc = ctor.newInstance(); services.add(svc); } } finally { is.close(); } } return services; }
Code Sample 2:
private static int ejecutaUpdate(String database, String SQL) throws Exception { int i = 0; DBConnectionManager dbm = null; Connection bd = null; try { dbm = DBConnectionManager.getInstance(); bd = dbm.getConnection(database); Statement st = bd.createStatement(); i = st.executeUpdate(SQL); bd.commit(); st.close(); dbm.freeConnection(database, bd); } catch (Exception e) { log.error("SQL error: " + SQL, e); Exception excep; if (dbm == null) excep = new Exception("Could not obtain pool object DbConnectionManager"); else if (bd == null) excep = new Exception("The Db connection pool could not obtain a database connection"); else { bd.rollback(); excep = new Exception("SQL Error: " + SQL + " error: " + e); dbm.freeConnection(database, bd); } throw excep; } return i; }
|
00
|
Code Sample 1:
public void removerQuestaoMultiplaEscolha(QuestaoMultiplaEscolha multiplaEscolha) throws ClassNotFoundException, SQLException { this.criaConexao(false); String sql = "DELETE FROM \"Disciplina\" " + " WHERE ID_Disciplina = ? )"; PreparedStatement stmt = null; try { stmt = connection.prepareStatement(sql); stmt.executeUpdate(); connection.commit(); } catch (SQLException e) { connection.rollback(); throw e; } finally { try { stmt.close(); this.fechaConexao(); } catch (SQLException e) { throw e; } } }
Code Sample 2:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session == null) { log.warn("HttpProxyServlet: no session"); response.setStatus(404); return; } User user = (User) session.getAttribute("user"); if (user == null) { log.warn("HttpProxyServlet: user not logged in"); response.setStatus(404); return; } String target = null; if (request.getPathInfo() != null && !request.getPathInfo().equals("")) { target = "http:/" + request.getPathInfo() + "?" + request.getQueryString(); log.info("HttpProxyServlet: target=" + target); } else { log.warn("HttpProxyServlet: missing pathInfo"); response.setStatus(404); return; } InputStream is = null; ServletOutputStream out = null; try { URL url = new URL(target); URLConnection uc = url.openConnection(); response.setContentType(uc.getContentType()); is = uc.getInputStream(); out = response.getOutputStream(); byte[] buf = new byte[4096]; int bytesRead; while ((bytesRead = is.read(buf)) != -1) { out.write(buf, 0, bytesRead); } } catch (MalformedURLException e) { log.warn("HttpProxyServlet: malformed URL"); response.setStatus(404); } catch (IOException e) { log.warn("HttpProxyServlet: I/O exception"); response.setStatus(404); } finally { if (is != null) { is.close(); } if (out != null) { out.close(); } } }
|
00
|
Code Sample 1:
public static Model downloadModel(String url) { Model model = ModelFactory.createDefaultModel(); try { URLConnection connection = new URL(url).openConnection(); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestProperty("Accept", "application/rdf+xml, */*;q=.1"); httpConnection.setRequestProperty("Accept-Language", "en"); } InputStream in = connection.getInputStream(); model.read(in, url); in.close(); return model; } catch (MalformedURLException e) { logger.debug("Unable to download model from " + url, e); throw new RuntimeException(e); } catch (IOException e) { logger.debug("Unable to download model from " + url, e); throw new RuntimeException(e); } }
Code Sample 2:
void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
|
11
|
Code Sample 1:
public static String encodePassword(String password) { try { MessageDigest messageDiegest = MessageDigest.getInstance("SHA-1"); messageDiegest.update(password.getBytes("UTF-8")); return Base64.encodeToString(messageDiegest.digest(), false); } catch (NoSuchAlgorithmException e) { log.error("Exception while encoding password"); throw new Error(e); } catch (UnsupportedEncodingException e) { log.error("Exception while encoding password"); throw new Error(e); } }
Code Sample 2:
private String hash(String message) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new AssertionError("Can't find the SHA1 algorithm in the java.security package"); } String saltString = String.valueOf(12345); md.update(saltString.getBytes()); md.update(message.getBytes()); byte[] digestBytes = md.digest(); StringBuffer digestSB = new StringBuffer(); for (int i = 0; i < digestBytes.length; i++) { int lowNibble = digestBytes[i] & 0x0f; int highNibble = (digestBytes[i] >> 4) & 0x0f; digestSB.append(Integer.toHexString(highNibble)); digestSB.append(Integer.toHexString(lowNibble)); } String digestStr = digestSB.toString().trim(); return digestStr; }
|
00
|
Code Sample 1:
public void googleImageSearch(String start) { try { String u = "http://images.google.com/images?q=" + custom + start; if (u.contains(" ")) { u = u.replace(" ", "+"); } URL url = new URL(u); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); BufferedReader readIn = new BufferedReader(new InputStreamReader(httpcon.getInputStream())); googleImages.clear(); String text = ""; String lin = ""; while ((lin = readIn.readLine()) != null) { text += lin; } readIn.close(); if (text.contains("\n")) { text = text.replace("\n", ""); } String[] array = text.split("\\Qhref=\"/imgres?imgurl=\\E"); for (String s : array) { if (s.startsWith("http://") || s.startsWith("https://") && s.contains("&")) { String s1 = s.substring(0, s.indexOf("&")); googleImages.add(s1); } } } catch (Exception ex4) { MusicBoxView.showErrorDialog(ex4); } jButton4.setEnabled(true); jButton2.setEnabled(true); getContentPane().remove(jLabel1); ImageIcon icon; try { icon = new ImageIcon(new URL(googleImages.elementAt(googleImageLocation))); int h = icon.getIconHeight(); int w = icon.getIconWidth(); jLabel1.setSize(w, h); jLabel1.setIcon(icon); add(jLabel1, BorderLayout.CENTER); } catch (MalformedURLException ex) { MusicBoxView.showErrorDialog(ex); jLabel1.setIcon(MusicBoxView.noImage); } add(jPanel1, BorderLayout.PAGE_END); pack(); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public String contentType() { if (_contentType != null) { return (String) _contentType; } String uti = null; URL url = url(); System.out.println("OKIOSIDManagedObject.contentType(): url = " + url + "\n"); if (url != null) { String contentType = null; try { contentType = url.openConnection().getContentType(); } catch (java.io.IOException e) { System.out.println("OKIOSIDManagedObject.contentType(): couldn't open URL connection!\n"); return UTType.Item; } if (contentType != null) { System.out.println("OKIOSIDManagedObject.contentType(): contentType = " + contentType + "\n"); uti = UTType.preferredIdentifierForTag(UTType.MIMETypeTagClass, contentType, null); } if (uti == null) { uti = UTType.Item; } } else { uti = UTType.Item; } _contentType = uti; System.out.println("OKIOSIDManagedObject.contentType(): uti = " + uti + "\n"); return uti; }
Code Sample 2:
public Document getWsdlDomResource(String aResourceName) throws SdlException { logger.debug("getWsdlDomResource() " + aResourceName); InputStream in = null; try { URL url = getDeploymentContext().getResourceURL(aResourceName); if (url == null) { logger.error("url is null"); return null; } else { logger.debug("loading wsdl document " + aResourceName); in = url.openStream(); return getSdlParser().loadWsdlDocument(in, null); } } catch (Throwable t) { logger.error("Error: " + t + " for " + aResourceName); throw new SdlDeploymentException(MessageFormat.format("unable to load: {0} from {1}", new Object[] { aResourceName, getDeploymentContext().getDeploymentLocation() }), t); } finally { SdlCloser.close(in); } }
|
00
|
Code Sample 1:
public void startElement(String uri, String tag, String qName, org.xml.sax.Attributes attributes) throws SAXException { wabclient.Attributes prop = new wabclient.Attributes(attributes); try { if (tag.equals("window")) startWindow(prop); else if (tag.equals("splitpanel")) startSplitPanel(prop); else if (tag.equals("desktoppane")) startDesktopPane(prop); else if (tag.equals("tabcontrol")) startTabcontrol(prop); else if (tag.equals("panel")) startPanel(prop); else if (tag.equals("statusbar")) startStatusbar(prop); else if (tag.equals("toolbar")) startToolbar(prop); else if (tag.equals("toolbarbutton")) startToolbarbutton(prop); else if (tag.equals("menu")) startMenu(prop); else if (tag.equals("menuitem")) startMenuitem(prop); else if (tag.equals("separator")) menu.addSeparator(); else if (tag.equals("choice")) startChoice(prop); else if (tag.equals("list")) startList(prop); else if (tag.equals("option")) startOption(prop); else if (tag.equals("label")) startLabel(prop); else if (tag.equals("button")) startButton(prop); else if (tag.equals("groupbox")) startGroupbox(prop); else if (tag.equals("radiobutton")) startRadioButton(prop); else if (tag.equals("checkbox")) startCheckbox(prop); else if (tag.equals("image")) startImage(prop); else if (tag.equals("textarea")) startTextArea(prop); else if (tag.equals("singlelineedit")) startSingleLineEdit(prop); else if (tag.equals("treeview")) startTreeview(prop); else if (tag.equals("treeitem")) startTreeitem(prop); else if (tag.equals("table")) startTable(prop); else if (tag.equals("header")) startHeader(prop); else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.addRow(); } else if (tag.equals("column")) { columnNumber++; if (prop == null) { System.err.println("table.column without properties"); return; } String value = prop.getValue("value", ""); model.setValueAt(value, rowNumber - 1, columnNumber - 1); } else if (tag.equals("rmbmenuitem")) { if (prop == null) { System.err.println("datawindow.menuitem without properties"); return; } String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); JMenuItem mi = new JMenuItem(label); mi.setActionCommand(action); mi.addActionListener(win); rmbmenu.add(mi); } else if (tag.equals("rmbseparator")) { rmbmenu.addSeparator(); } else if (tag.equals("script")) { win.beginScript(); String url = prop.getValue("src"); if (url.length() > 0) { try { BufferedReader r = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String buffer; while (true) { buffer = r.readLine(); if (buffer == null) break; win.script += buffer + "\n"; } r.close(); win.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[win] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } }
Code Sample 2:
private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); }
|
00
|
Code Sample 1:
private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } }
Code Sample 2:
@Override public void onClick(View v) { username = textusername.getText().toString(); password = textpassword.getText().toString(); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new name_value("uname", username)); nameValuePairs.add(new name_value("upass", password)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.gotrackit.net/server/check_user.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line = "0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } if (result.contains("reject")) { Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; String wrong = "Invalid Username or Password"; Toast toast = Toast.makeText(context, wrong, duration); toast.show(); } else { MyApp uid = (MyApp) getApplicationContext(); uid.setStringValue(result); Intent myintent = new Intent(v.getContext(), UserMap.class); startActivityForResult(myintent, 0); } }
|
00
|
Code Sample 1:
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { PositionParser pp; Database.init("XIDResult"); pp = new PositionParser("01:33:50.904+30:39:35.79"); String url = "http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script="; String script = "format object \"%IDLIST[%-30*]|-%COO(A)|%COO(D)|%OTYPELIST(S)\"\n"; String tmp = ""; script += pp.getPosition() + " radius=1m"; url += URLEncoder.encode(script, "ISO-8859-1"); URL simurl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(simurl.openStream())); String boeuf; boolean data_found = false; JSONObject retour = new JSONObject(); JSONArray dataarray = new JSONArray(); JSONArray colarray = new JSONArray(); JSONObject jsloc = new JSONObject(); jsloc.put("sTitle", "ID"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Position"); colarray.add(jsloc); jsloc = new JSONObject(); jsloc.put("sTitle", "Type"); colarray.add(jsloc); retour.put("aoColumns", colarray); int datasize = 0; while ((boeuf = in.readLine()) != null) { if (data_found) { String[] fields = boeuf.trim().split("\\|", -1); int pos = fields.length - 1; if (pos >= 3) { String type = fields[pos]; pos--; String dec = fields[pos]; pos--; String ra = fields[pos]; String id = ""; for (int i = 0; i < pos; i++) { id += fields[i]; if (i < (pos - 1)) { id += "|"; } } if (id.length() <= 30) { JSONArray darray = new JSONArray(); darray.add(id.trim()); darray.add(ra + " " + dec); darray.add(type.trim()); dataarray.add(darray); datasize++; } } } else if (boeuf.startsWith("::data")) { data_found = true; } } retour.put("aaData", dataarray); retour.put("iTotalRecords", datasize); retour.put("iTotalDisplayRecords", datasize); System.out.println(retour.toJSONString()); in.close(); }
Code Sample 2:
public final String encrypt(final String plaintext, final String salt) { if (plaintext == null) { throw new NullPointerException(); } if (salt == null) { throw new NullPointerException(); } try { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update((plaintext + salt).getBytes("UTF-8")); return new BASE64Encoder().encode(md.digest()); } catch (NoSuchAlgorithmException e) { throw new EncryptionException(e); } catch (UnsupportedEncodingException e) { throw new EncryptionException(e); } }
|
00
|
Code Sample 1:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { try { String req1xml = jTextArea1.getText(); java.net.URL url = new java.net.URL("http://217.34.8.235:8080/newgenlibctxt/PatronServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); urlconn.setRequestProperty("Content-type", "text/xml; charset=UTF-8"); java.io.OutputStream os = urlconn.getOutputStream(); java.util.zip.CheckedOutputStream cos = new java.util.zip.CheckedOutputStream(os, new java.util.zip.Adler32()); java.util.zip.GZIPOutputStream gop = new java.util.zip.GZIPOutputStream(cos); java.io.OutputStreamWriter dos = new java.io.OutputStreamWriter(gop, "UTF-8"); System.out.println(req1xml); try { java.io.FileOutputStream pw = new java.io.FileOutputStream("C:/log.txt"); pw.write(req1xml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } dos.write(req1xml); dos.flush(); dos.close(); System.out.println("url conn: " + urlconn.getContentEncoding() + " " + urlconn.getContentType()); java.io.InputStream ios = urlconn.getInputStream(); java.util.zip.CheckedInputStream cis = new java.util.zip.CheckedInputStream(ios, new java.util.zip.Adler32()); java.util.zip.GZIPInputStream gip = new java.util.zip.GZIPInputStream(cis); java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(gip)); String reqxml = ""; while (br.ready()) { String line = br.readLine(); reqxml += line; } try { java.io.FileOutputStream pw = new java.io.FileOutputStream("C:/log3.txt"); pw.write(reqxml.getBytes()); pw.flush(); pw.close(); } catch (Exception exp) { exp.printStackTrace(); } } catch (Exception exp) { exp.printStackTrace(); } }
Code Sample 2:
public void upgradeSingleFileModelToDirectory(File modelFile) throws IOException { byte[] buf = new byte[8192]; int bytesRead = 0; File backupModelFile = new File(modelFile.getPath() + ".bak"); FileInputStream oldModelIn = new FileInputStream(modelFile); FileOutputStream backupModelOut = new FileOutputStream(backupModelFile); while ((bytesRead = oldModelIn.read(buf)) >= 0) { backupModelOut.write(buf, 0, bytesRead); } backupModelOut.close(); oldModelIn.close(); buf = null; modelFile.delete(); modelFile.mkdir(); BufferedReader oldModelsBuff = new BomStrippingInputStreamReader(new FileInputStream(backupModelFile), "UTF-8"); File metaDataFile = new File(modelFile, ConstantParameters.FILENAMEOFModelMetaData); BufferedWriter metaDataBuff = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(metaDataFile), "UTF-8")); for (int i = 0; i < 8; i++) { metaDataBuff.write(oldModelsBuff.readLine()); metaDataBuff.write('\n'); } metaDataBuff.close(); int classIndex = 1; BufferedWriter modelWriter = null; String line = null; while ((line = oldModelsBuff.readLine()) != null) { if (line.startsWith("Class=") && line.contains("numTraining=") && line.contains("numPos=")) { if (modelWriter != null) { modelWriter.close(); } File nextModel = new File(modelFile, String.format(ConstantParameters.FILENAMEOFPerClassModel, Integer.valueOf(classIndex++))); modelWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(nextModel), "UTF-8")); } modelWriter.write(line); modelWriter.write('\n'); } if (modelWriter != null) { modelWriter.close(); } }
|
00
|
Code Sample 1:
public static long[] getUids(String myUid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(UIDS_URI); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() == 200) { String res = EntityUtils.toString(response.getEntity()); JSONArray result = new JSONArray(res); long[] friends = new long[result.length()]; long uid = Long.parseLong(myUid); for (int i = 0; i < result.length(); i++) { if (uid != result.getLong(i)) { friends[i] = result.getLong(i); } } return friends; } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
Code Sample 2:
private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText(Messages.getString("gui.AdministracionResorces.6")); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonImagen; }
|
11
|
Code Sample 1:
public static String getMD5Hash(String in) { StringBuffer result = new StringBuffer(32); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(in.getBytes()); Formatter f = new Formatter(result); for (byte b : md5.digest()) { f.format("%02x", b); } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return result.toString(); }
Code Sample 2:
private boolean setupDatabase() { if (DoInstallationTasks.DEBUG_DB) { System.out.println("About to setup database"); } if (installer.getRootDBUsername() != null && installer.getRootDBUsername().length() > 1 && installer.getRootDBPassword() != null && installer.getRootDBPassword().length() > 1) { if (DoInstallationTasks.DEBUG_DB) { System.out.println("Going to call doDBRootPortions"); } if (!doDBRootPortions(installer.getPachyDBHost(), installer.getPachyDBPort(), installer.getPachyDBName(), installer.getPachyDBUsername(), installer.getPachyDBPassword(), installer.getRootDBUsername(), installer.getRootDBPassword())) { System.err.println("Root work not able to be completed, " + "not continuing."); return false; } if (DoInstallationTasks.DEBUG_DB) { System.out.println("Back from call to doDBRootPortions"); } } if (DoInstallationTasks.DEBUG_DB) { System.out.println("Going to open SQL files"); } Connection conn = getDBConnection(installer.getPachyDBHost(), installer.getPachyDBPort(), installer.getPachyDBName(), installer.getPachyDBUsername(), installer.getPachyDBPassword()); if (conn == null) { return false; } Statement stmt = null; boolean havePachy20 = false; try { stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM PRESENTATION LIMIT 1"); if (rs.next()) { havePachy20 = true; } if (!havePachy20) { rs = stmt.executeQuery("SELECT * FROM SCREEN LIMIT 1"); if (rs.next()) { havePachy20 = true; } } } catch (SQLException sqle) { System.err.println("Error doing check for presentation, means " + "2.0 doesn't exist"); System.out.println("SQLException: " + sqle.getMessage()); System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("VendorError: " + sqle.getErrorCode()); } finally { try { stmt.close(); } catch (SQLException sqlex) { } } if (havePachy20) { Object[] options = { Pachyderm21Installer.ISTRINGS.getString("dialog.abort"), Pachyderm21Installer.ISTRINGS.getString("dialog.keep"), Pachyderm21Installer.ISTRINGS.getString("dialog.overwrite") }; int result = JOptionPane.showOptionDialog(this.installer, Pachyderm21Installer.ISTRINGS.getString("dit.pachy20msg"), Pachyderm21Installer.ISTRINGS.getString("dit.pachy20title"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == 0) { System.out.println("Aborted by user before doing database"); return false; } else if (result == 2) { havePachy20 = false; } } else { Object[] options = { Pachyderm21Installer.ISTRINGS.getString("dialog.continue"), Pachyderm21Installer.ISTRINGS.getString("dialog.abort") }; int result = JOptionPane.showOptionDialog(this.installer, Pachyderm21Installer.ISTRINGS.getString("dit.nopachy20msg"), Pachyderm21Installer.ISTRINGS.getString("dit.nopachy20title"), JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == 1) { System.out.println("Aborted by user before doing database"); return false; } } boolean dbError = false; if (havePachy20) { try { java.util.Date d = new java.util.Date(); stmt = conn.createStatement(); stmt.executeUpdate("RENAME TABLE APDEFAULT TO APDEFAULT_2_0_" + d.getTime()); } catch (SQLException sqle) { System.err.println("Error doing check for presentation, " + "means 2.0 doesn't exist"); System.out.println("SQLException: " + sqle.getMessage()); System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("VendorError: " + sqle.getErrorCode()); dbError = true; } finally { try { stmt.close(); } catch (SQLException sqlex) { } } } if (dbError) { return false; } try { stmt = conn.createStatement(); stmt.executeUpdate("START TRANSACTION"); InputStreamReader isr = new InputStreamReader(getClass().getResourceAsStream("apdefaults.sql")); LineNumberReader lnr = new LineNumberReader(isr); String linein; while ((linein = lnr.readLine()) != null) { if (linein.trim().length() > 0) { String lineout = replaceTemplateVariables(linein); stmt.executeUpdate(lineout); } } stmt.executeUpdate("COMMIT"); lnr.close(); } catch (SQLException sqle) { System.err.println("error doing apdefaults.sql template"); System.out.println("sqlexception: " + sqle.getMessage()); System.out.println("sqlstate: " + sqle.getSQLState()); System.out.println("vendorerror: " + sqle.getErrorCode()); if (stmt != null) { try { stmt.executeUpdate("ROLLBACK"); } catch (SQLException sqlex) { } } dbError = true; } catch (Exception e) { System.err.println("Error doing apdefaults.sql template"); e.printStackTrace(System.err); if (stmt != null) { try { stmt.executeUpdate("ROLLBACK"); } catch (SQLException sqlex) { } } dbError = true; } finally { try { stmt.close(); } catch (SQLException sqlex) { } } if (dbError) { return false; } try { stmt = conn.createStatement(); stmt.executeUpdate("START TRANSACTION"); InputStreamReader isr = new InputStreamReader(getClass().getResourceAsStream("Pachyderm21.sql")); LineNumberReader lnr = new LineNumberReader(isr); String linein; while ((linein = lnr.readLine()) != null) { if (linein.trim().length() > 0) { String lineout = replaceTemplateVariables(linein); if (DoInstallationTasks.DEBUG) { System.out.println("line #" + lnr.getLineNumber()); } stmt.executeUpdate(lineout); } } stmt.executeUpdate("COMMIT"); lnr.close(); } catch (SQLException sqle) { System.err.println("error doing pachyderm21.sql template"); System.out.println("sqlexception: " + sqle.getMessage()); System.out.println("sqlstate: " + sqle.getSQLState()); System.out.println("vendorerror: " + sqle.getErrorCode()); if (stmt != null) { try { stmt.executeUpdate("ROLLBACK"); } catch (SQLException sqlex) { } } dbError = true; } catch (Exception e) { System.err.println("error doing pachyderm21.sql template"); e.printStackTrace(System.err); if (stmt != null) { try { stmt.executeUpdate("ROLLBACK"); } catch (SQLException sqlex) { } } dbError = true; } finally { try { stmt.close(); } catch (SQLException sqlex) { } } if (dbError) { return false; } if (!havePachy20) { try { stmt = conn.createStatement(); stmt.executeUpdate("START TRANSACTION"); InputStreamReader isr = new InputStreamReader(getClass().getResourceAsStream("Pachyderm" + "21new.sql")); LineNumberReader lnr = new LineNumberReader(isr); String linein; while ((linein = lnr.readLine()) != null) { if (linein.trim().length() > 0) { String lineout = replaceTemplateVariables(linein); if (DoInstallationTasks.DEBUG) { System.out.println("Line #" + lnr.getLineNumber()); } stmt.executeUpdate(lineout); } } stmt.executeUpdate("COMMIT"); lnr.close(); } catch (SQLException sqle) { System.err.println("Error doing Pachyderm21new.sql template"); System.out.println("SQLException: " + sqle.getMessage()); System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("VendorError: " + sqle.getErrorCode()); if (stmt != null) { try { stmt.executeUpdate("ROLLBACK"); } catch (SQLException sqlex) { } } dbError = true; } catch (Exception e) { System.err.println("Error doing Pachyderm21.sql template"); e.printStackTrace(System.err); if (stmt != null) { try { stmt.executeUpdate("ROLLBACK"); } catch (SQLException sqlex) { } } dbError = true; } finally { try { stmt.close(); } catch (SQLException sqlex) { } } } PreparedStatement ps = null; PreparedStatement ps1 = null; PreparedStatement ps2 = null; PreparedStatement ps3 = null; try { String adminPassword = installer.getAdminPassword(); MessageDigest _md = MessageDigest.getInstance("MD5"); _md.update(adminPassword.getBytes("UTF-8")); byte[] md5 = _md.digest(); ps = conn.prepareStatement("UPDATE AUTHRECORD set PASSWORD=? " + "WHERE USERNAME='administrator'"); ps.setBytes(1, md5); int numupdates = ps.executeUpdate(); if (DEBUG) System.out.println("Changing admin password, " + "numUpdates = " + numupdates); Vector<AdminData> v = installer.getAdditionalAdminAccounts(); String customPropertiesSPFPre = "{\n \"CXMultiValueArchive\" = {" + "\n \"class\" = " + "\"ca.ucalgary.apollo.core." + "CXMutableMultiValue\";\n " + "\"values\" = (\n " + "{\n \"class\" = \"ca.ucalgary." + "apollo.core.CXMultiValue$Value\";\n" + " \"identifier\" = \"0\";\n " + "\"label\" = \"work\";\n " + "\"value\" = \""; String customPropertiesSPFPost = "\";\n }\n );\n \"identCounter\" = \"1\";\n };\n}"; if (v.size() > 0) { ps = conn.prepareStatement("INSERT INTO `APPERSON` VALUES " + "(NULL,NULL,NULL,NOW(),NULL,NULL," + "?,?,NULL,NULL,NULL,NULL,NULL," + "NULL,?,NULL,NULL,NULL,NULL,NOW()," + "NULL,NULL,NULL,NULL,NULL,NULL,?," + "NULL,NULL,NULL,NULL,NULL)"); ps1 = conn.prepareStatement("INSERT INTO `AUTHRECORD` VALUES " + "(?,'pachyderm',?,NULL)"); ps2 = conn.prepareStatement("INSERT INTO `AUTHMAP` " + "(external_id,external_realm," + "map_id,person_id) " + "VALUES (?,'pachyderm',?,?)"); ps3 = conn.prepareStatement("INSERT INTO `GROUPPERSONJOIN` " + "(group_id,person_id) " + "VALUES(1, ?)"); } for (int i = 0; i < v.size(); ++i) { AdminData ad = (AdminData) v.elementAt(i); _md = MessageDigest.getInstance("MD5"); _md.update(ad.getPassword().getBytes("UTF-8")); md5 = _md.digest(); ps.setString(1, customPropertiesSPFPre + ad.getEmail() + customPropertiesSPFPost); ps.setString(2, ad.getFirstName()); ps.setString(3, ad.getLastName()); ps.setInt(4, i + 2); numupdates = ps.executeUpdate(); if (numupdates == 1) { ps1.setBytes(1, md5); ps1.setString(2, ad.getUsername()); ps1.executeUpdate(); ps2.setString(1, ad.getUsername() + "@pachyderm"); ps2.setInt(2, i + 2); ps2.setInt(3, i + 2); ps2.executeUpdate(); ps3.setInt(1, i + 2); ps3.executeUpdate(); } } } catch (SQLException sqle) { System.err.println("Error doing Pachyderm21new.sql template"); System.out.println("SQLException: " + sqle.getMessage()); System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("VendorError: " + sqle.getErrorCode()); dbError = true; } catch (Exception e) { System.err.println("Error doing Pachyderm21.sql template"); e.printStackTrace(System.err); dbError = true; } finally { if (ps != null) { try { ps.close(); } catch (SQLException sqlex) { } } if (ps1 != null) { try { ps1.close(); } catch (SQLException sqlex) { } } if (ps2 != null) { try { ps2.close(); } catch (SQLException sqlex) { } } } return true; }
|
11
|
Code Sample 1:
@Test public void testCopy_readerToOutputStream_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); fail(); } catch (NullPointerException ex) { } }
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 static String readURL(String urlStr, boolean debug) { if (debug) System.out.print(" trying: " + urlStr + "\n"); URL url = null; try { url = new URL(urlStr); } catch (java.net.MalformedURLException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } HttpURLConnection huc = null; try { huc = (HttpURLConnection) url.openConnection(); } catch (IOException e) { System.out.print("test failed: using URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentType = huc.getContentType(); if (contentType == null || contentType.indexOf("text/xml") < 0) { System.out.print("*** Warning *** Content-Type not set to text/xml"); System.out.print('\n'); System.out.print(" Content-type: "); System.out.print(contentType); System.out.print('\n'); } InputStream urlStream = null; try { urlStream = huc.getInputStream(); } catch (java.io.IOException e) { System.out.print("test failed: opening URL: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } BufferedReader in = new BufferedReader(new InputStreamReader(urlStream)); boolean xml = true; String href = null, inputLine = null; StringBuffer content = new StringBuffer(), stylesheet = null; Transformer transformer = null; try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading first line of response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } if (inputLine == null) { System.out.print("test failed: No input read from URL"); System.out.print('\n'); return null; } if (!inputLine.startsWith("<?xml ")) { xml = false; content.append(inputLine); } if (xml) { int offset = inputLine.indexOf('>'); if (offset + 2 < inputLine.length()) { inputLine = inputLine.substring(offset + 1); offset = inputLine.indexOf('<'); if (offset > 0) inputLine = inputLine.substring(offset); } else try { inputLine = in.readLine(); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } content.append(inputLine); } try { while ((inputLine = in.readLine()) != null) content.append(inputLine); } catch (java.io.IOException e) { System.out.print("test failed: reading response: "); System.out.print(e.getMessage()); System.out.print('\n'); return null; } String contentStr = content.toString(); if (transformer != null) { StreamSource streamXMLRecord = new StreamSource(new StringReader(contentStr)); StringWriter xmlRecordWriter = new StringWriter(); try { transformer.transform(streamXMLRecord, new StreamResult(xmlRecordWriter)); System.out.print(" successfully applied stylesheet '"); System.out.print(href); System.out.print("'"); System.out.print('\n'); } catch (javax.xml.transform.TransformerException e) { System.out.print("unable to apply stylesheet '"); System.out.print(href); System.out.print("'to response: "); System.out.print(e.getMessage()); System.out.print('\n'); e.printStackTrace(); } } return contentStr; }
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:
protected int doExecuteInsert(PreparedStatement statement, Table data) throws SQLException { ResultSet rs = null; int result = -1; try { lastError = null; result = statement.executeUpdate(); if (!isAutoCommit()) connection.commit(); rs = statement.getGeneratedKeys(); while (rs.next()) { FieldUtils.setValue(data, data.key, rs.getObject(1)); } } catch (SQLException ex) { if (!isAutoCommit()) { lastError = ex; connection.rollback(); LogUtils.log(Level.SEVERE, "Transaction is being rollback. Error: " + ex.toString()); } else { throw ex; } } finally { if (statement != null) statement.close(); if (rs != null) rs.close(); } return result; }
Code Sample 2:
protected N save(String sql, Object[] args) { Connection conn = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); this.setParameters(pstmt, args); pstmt.executeUpdate(); conn.commit(); conn.setAutoCommit(true); rs = pstmt.getGeneratedKeys(); return (N) rs.getObject(1); } catch (SQLException e) { try { if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } } catch (SQLException ex) { ex.printStackTrace(); } throw new JdbcDaoException(e.getMessage(), e); } finally { JdbcUtils.free(rs, pstmt, conn); } }
|
00
|
Code Sample 1:
public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; }
Code Sample 2:
public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } }
|
11
|
Code Sample 1:
@Override @Transactional public FileData store(FileData data, InputStream stream) { try { FileData file = save(data); file.setPath(file.getGroup() + File.separator + file.getId()); file = save(file); File folder = new File(PATH, file.getGroup()); if (!folder.exists()) folder.mkdirs(); File filename = new File(folder, file.getId() + ""); IOUtils.copyLarge(stream, new FileOutputStream(filename)); return file; } catch (IOException e) { throw new ServiceException("storage", e); } }
Code Sample 2:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
|
11
|
Code Sample 1:
private String mkSid() { String temp = toString(); MessageDigest messagedigest = null; try { messagedigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } messagedigest.update(temp.getBytes()); byte digest[] = messagedigest.digest(); String chk = ""; for (int i = 0; i < digest.length; i++) { String s = Integer.toHexString(digest[i] & 0xFF); chk += ((s.length() == 1) ? "0" + s : s); } return chk.toString(); }
Code Sample 2:
public String calculateDigest(String str) { StringBuffer s = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); for (byte d : digest) { s.append(Integer.toHexString((int) (d & 0xff))); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return s.toString(); }
|
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:
private void getPage(final String path, final String dataToSend, final GetPageCallback callback) { runner.add(new Runnable() { @Override public void run() { String url = "http://" + resources.getString(R.string.host) + path; HttpUriRequest req; if (dataToSend == null) { req = new HttpGet(url); } else { req = new HttpPost(url); try { ((HttpPost) req).setEntity(new StringEntity(dataToSend)); } catch (UnsupportedEncodingException e) { Logger.getLogger(JSBridge.class.getName()).log(Level.SEVERE, "Unsupported encoding.", e); } } req.addHeader("Cookie", getAuthCookie(false)); try { HttpResponse response = httpclient.execute(req); Logger.getLogger(JSBridge.class.getName()).log(Level.INFO, "Response status is '" + response.getStatusLine() + "'."); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { BufferedReader in = new BufferedReader(new InputStreamReader(instream)); StringBuilder b = new StringBuilder(); String line; boolean first = true; while ((line = in.readLine()) != null) { b.append(line); if (first) { first = false; } else { b.append("\r\n"); } } in.close(); callback.success(b.toString()); return; } catch (RuntimeException ex) { throw ex; } finally { instream.close(); } } } catch (ClientProtocolException e) { Logger.getLogger(JSBridge.class.getName()).log(Level.SEVERE, "HTTP protocol violated.", e); } catch (IOException e) { Logger.getLogger(JSBridge.class.getName()).log(Level.WARNING, "Could not load '" + path + "'.", e); } Logger.getLogger(JSBridge.class.getName()).log(Level.INFO, "Calling error from JSBridge.getPage because of previous errors."); callback.error(); } }); }
|
11
|
Code Sample 1:
public static void copyFile(String source, String destination, TimeSlotTracker timeSlotTracker) { LOG.info("copying [" + source + "] to [" + destination + "]"); BufferedInputStream sourceStream = null; BufferedOutputStream destStream = null; try { File destinationFile = new File(destination); if (destinationFile.exists()) { destinationFile.delete(); } sourceStream = new BufferedInputStream(new FileInputStream(source)); destStream = new BufferedOutputStream(new FileOutputStream(destinationFile)); int readByte; while ((readByte = sourceStream.read()) > 0) { destStream.write(readByte); } Object[] arg = { destinationFile.getName() }; String msg = timeSlotTracker.getString("datasource.xml.copyFile.copied", arg); LOG.fine(msg); } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } finally { try { if (destStream != null) { destStream.close(); } if (sourceStream != null) { sourceStream.close(); } } catch (Exception e) { Object[] expArgs = { e.getMessage() }; String expMsg = timeSlotTracker.getString("datasource.xml.copyFile.exception", expArgs); timeSlotTracker.errorLog(expMsg); timeSlotTracker.errorLog(e); } } }
Code Sample 2:
public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
|
00
|
Code Sample 1:
public static void copyFile(File src, File dst) { try { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dst); try { byte[] buf = new byte[1024]; int i = 0; while ((i = fis.read(buf)) != -1) fos.write(buf, 0, i); } catch (IOException e) { throw e; } finally { if (fis != null) fis.close(); if (fos != null) fos.close(); } } catch (IOException e) { logger.error("Error coping file from " + src + " to " + dst, e); } }
Code Sample 2:
public String mdHesla(String password) { String hashword = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); hashword = hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } return hashword; }
|
11
|
Code Sample 1:
public static String SHA1(String text) { try { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
Code Sample 2:
private byte[] digestPassword(byte[] salt, String password) throws AuthenticationException { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); return md.digest(); } catch (Exception e) { throw new AuthenticationException(MESSAGE_CONFIGURATION_ERROR_KEY, e); } }
|
11
|
Code Sample 1:
public synchronized boolean copyTmpDataFile(String fpath) throws IOException { if (tmpDataOutput != null) tmpDataOutput.close(); tmpDataOutput = null; if (tmpDataFile == null) return false; File nfp = new File(fpath); if (nfp.exists()) nfp.delete(); FileInputStream src = new FileInputStream(tmpDataFile); FileOutputStream dst = new FileOutputStream(nfp); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = src.read(buffer)) != -1) dst.write(buffer, 0, bytesRead); src.close(); dst.close(); return true; }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
|
00
|
Code Sample 1:
protected Document loadDocument() throws MalformedURLException, DocumentException, IOException { if (jiraFilterURL.startsWith("file")) { URL url = getSourceURL(); return parseDocument(url); } else { HttpClient httpClient = new DefaultHttpClient(); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("os_username", jiraUser)); formparams.add(new BasicNameValuePair("os_password", jiraPassword)); formparams.add(new BasicNameValuePair("os_cookie", "true")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); HttpPost post = new HttpPost(getJiraRootUrl() + "/secure/login.jsp"); post.setEntity(entity); HttpResponse response = httpClient.execute(post); response.getEntity().consumeContent(); String url_str = StringEscapeUtils.unescapeXml(jiraFilterURL); HttpGet get = new HttpGet(url_str); response = httpClient.execute(get); return parseDocument(response.getEntity().getContent()); } }
Code Sample 2:
InputStream selectSource(String item) { if (item.endsWith(".pls")) { item = fetch_pls(item); if (item == null) return null; } else if (item.endsWith(".m3u")) { item = fetch_m3u(item); if (item == null) return null; } if (!item.endsWith(".ogg")) { return null; } InputStream is = null; URLConnection urlc = null; try { URL url = null; if (running_as_applet) url = new URL(getCodeBase(), item); else url = new URL(item); urlc = url.openConnection(); is = urlc.getInputStream(); current_source = url.getProtocol() + "://" + url.getHost() + ":" + url.getPort() + url.getFile(); } catch (Exception ee) { System.err.println(ee); } if (is == null && !running_as_applet) { try { is = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + item); current_source = null; } catch (Exception ee) { System.err.println(ee); } } if (is == null) return null; System.out.println("Select: " + item); { boolean find = false; for (int i = 0; i < cb.getItemCount(); i++) { String foo = (String) (cb.getItemAt(i)); if (item.equals(foo)) { find = true; break; } } if (!find) { cb.addItem(item); } } int i = 0; String s = null; String t = null; udp_port = -1; udp_baddress = null; while (urlc != null && true) { s = urlc.getHeaderField(i); t = urlc.getHeaderFieldKey(i); if (s == null) break; i++; if (t != null && t.equals("udp-port")) { try { udp_port = Integer.parseInt(s); } catch (Exception ee) { System.err.println(ee); } } else if (t != null && t.equals("udp-broadcast-address")) { udp_baddress = s; } } return is; }
|
00
|
Code Sample 1:
private void writeFile(String name, URL url) throws IOException { Location location = resourcesHome.resolve(name); InputStream input = url.openStream(); OutputStream output = location.getOutputStream(); try { byte buf[] = new byte[1024]; int read; while (true) { read = input.read(buf); if (read == -1) break; output.write(buf, 0, read); } } finally { try { input.close(); } finally { output.close(); } } }
Code Sample 2:
protected synchronized Long putModel(String table, String linkTable, String type, TupleBinding binding, LocatableModel model) { try { if (model.getId() != null && !"".equals(model.getId())) { ps7.setInt(1, Integer.parseInt(model.getId())); ps7.execute(); ps6.setInt(1, Integer.parseInt(model.getId())); ps6.execute(); } if (persistenceMethod == PostgreSQLStore.BYTEA) { ps1.setString(1, model.getContig()); ps1.setInt(2, model.getStartPosition()); ps1.setInt(3, model.getStopPosition()); ps1.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); ps1.setBytes(5, objData.getData()); ps1.executeUpdate(); } else if (persistenceMethod == PostgreSQLStore.OID || persistenceMethod == PostgreSQLStore.FIELDS) { ps1b.setString(1, model.getContig()); ps1b.setInt(2, model.getStartPosition()); ps1b.setInt(3, model.getStopPosition()); ps1b.setString(4, type); DatabaseEntry objData = new DatabaseEntry(); binding.objectToEntry(model, objData); int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE); LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE); obj.write(objData.getData()); obj.close(); ps1b.setInt(5, oid); ps1b.executeUpdate(); } ResultSet rs = null; PreparedStatement ps = conn.prepareStatement("select currval('" + table + "_" + table + "_id_seq')"); rs = ps.executeQuery(); int modelId = -1; if (rs != null) { if (rs.next()) { modelId = rs.getInt(1); } } rs.close(); ps.close(); for (String key : model.getTags().keySet()) { int tagId = -1; if (tags.get(key) != null) { tagId = tags.get(key); } else { ps2.setString(1, key); rs = ps2.executeQuery(); if (rs != null) { while (rs.next()) { tagId = rs.getInt(1); } } rs.close(); } if (tagId < 0) { ps3.setString(1, key); ps3.setString(2, model.getTags().get(key)); ps3.executeUpdate(); rs = ps4.executeQuery(); if (rs != null) { if (rs.next()) { tagId = rs.getInt(1); tags.put(key, tagId); } } rs.close(); } ps5.setInt(1, tagId); ps5.executeUpdate(); } conn.commit(); return (new Long(modelId)); } catch (SQLException e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } catch (Exception e) { try { conn.rollback(); } catch (SQLException e2) { e2.printStackTrace(); } e.printStackTrace(); System.err.println(e.getMessage()); } return (null); }
|
00
|
Code Sample 1:
@Override public EntrySet read(EntrySet set) throws ReadFailedException { if (!SourceCache.contains(url)) { SSL.certify(url); try { super.setParser(Parser.detectParser(url.openStream(), url)); final PipedInputStream in = new PipedInputStream(); final PipedOutputStream forParser = new PipedOutputStream(in); new Thread(new Runnable() { public void run() { try { OutputStream out = SourceCache.startCaching(url); InputStream is = url.openStream(); byte[] buffer = new byte[100000]; while (true) { int amountRead = is.read(buffer); if (amountRead == -1) { break; } forParser.write(buffer, 0, amountRead); out.write(buffer, 0, amountRead); } forParser.close(); out.close(); SourceCache.finish(url); } catch (IOException e) { e.printStackTrace(); } } }).start(); super.setIos(in); } catch (Exception e) { throw new ReadFailedException(e); } return super.read(set); } else { try { return SourceCache.get(url).read(set); } catch (IOException e) { throw new ReadFailedException(e); } } }
Code Sample 2:
public void unpack(File destDirectory, boolean delete) { if (delete) delete(destDirectory); if (destDirectory.exists()) throw new ContentPackageException("Destination directory already exists."); this.destDirectory = destDirectory; this.manifestFile = new File(destDirectory, MANIFEST_FILE_NAME); try { if (zipInputStream == null) zipInputStream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { File destFile = new File(destDirectory, zipEntry.getName()); destFile.getParentFile().mkdirs(); if (!zipEntry.isDirectory()) { BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(destFile), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int length; while ((length = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) output.write(buffer, 0, length); output.close(); zipInputStream.closeEntry(); } } zipInputStream.close(); } catch (IOException ex) { throw new ContentPackageException(ex); } }
|
00
|
Code Sample 1:
public static void pingSearchEngine(String engineURL) throws MalformedURLException, UnsupportedEncodingException { if ((ConfigurationManager.getProperty("http.proxy.host") != null) && (ConfigurationManager.getProperty("http.proxy.port") != null)) { System.setProperty("proxySet", "true"); System.setProperty("proxyHost", ConfigurationManager.getProperty("http.proxy.host")); System.getProperty("proxyPort", ConfigurationManager.getProperty("http.proxy.port")); } String sitemapURL = ConfigurationManager.getProperty("dspace.url") + "/sitemap"; URL url = new URL(engineURL + URLEncoder.encode(sitemapURL, "UTF-8")); try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer resp = new StringBuffer(); while ((inputLine = in.readLine()) != null) { resp.append(inputLine).append("\n"); } in.close(); if (connection.getResponseCode() == 200) { log.info("Pinged " + url.toString() + " successfully"); } else { log.warn("Error response pinging " + url.toString() + ":\n" + resp); } } catch (IOException e) { log.warn("Error pinging " + url.toString(), e); } }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
00
|
Code Sample 1:
public byte[] getDigest(OMProcessingInstruction pi, String digestAlgorithm) throws OMException { byte[] digest = new byte[0]; try { MessageDigest md = MessageDigest.getInstance(digestAlgorithm); md.update((byte) 0); md.update((byte) 0); md.update((byte) 0); md.update((byte) 7); md.update(pi.getTarget().getBytes("UnicodeBigUnmarked")); md.update((byte) 0); md.update((byte) 0); md.update(pi.getValue().getBytes("UnicodeBigUnmarked")); digest = md.digest(); } catch (NoSuchAlgorithmException e) { throw new OMException(e); } catch (UnsupportedEncodingException e) { throw new OMException(e); } return digest; }
Code Sample 2:
private int saveToTempTable(ArrayList cons, String tempTableName, boolean truncateFirst) throws SQLException { if (truncateFirst) { this.executeUpdate("TRUNCATE TABLE " + tempTableName); Categories.dataDb().debug("TABLE " + tempTableName + " TRUNCATED."); } PreparedStatement ps = null; int rows = 0; try { String insert = "INSERT INTO " + tempTableName + " VALUES (?)"; ps = this.conn.prepareStatement(insert); for (int i = 0; i < cons.size(); i++) { ps.setLong(1, ((Long) cons.get(i)).longValue()); rows = ps.executeUpdate(); if ((i % 500) == 0) { this.conn.commit(); } } this.conn.commit(); } catch (SQLException sqle) { this.conn.rollback(); throw sqle; } finally { if (ps != null) { ps.close(); } } return rows; }
|
11
|
Code Sample 1:
@Override public void execute() throws ProcessorExecutionException { try { if (getSource().getPaths() == null || getSource().getPaths().size() == 0 || getDestination().getPaths() == null || getDestination().getPaths().size() == 0) { throw new ProcessorExecutionException("No input and/or output paths specified."); } String temp_dir_prefix = getDestination().getPath().getParent().toString() + "/bcc_" + getDestination().getPath().getName() + "_"; SequenceTempDirMgr dirMgr = new SequenceTempDirMgr(temp_dir_prefix, context); dirMgr.setSeqNum(0); Path tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to AdjSetVertex"); Transformer transformer = new OutAdjVertex2AdjSetVertexTransformer(); transformer.setConf(context); transformer.setSrcPath(getSource().getPath()); tmpDir = dirMgr.getTempDir(); transformer.setDestPath(tmpDir); transformer.setMapperNum(getMapperNum()); transformer.setReducerNum(getReducerNum()); transformer.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": Transform input to LabeledAdjSetVertex"); Vertex2LabeledTransformer l_transformer = new Vertex2LabeledTransformer(); l_transformer.setConf(context); l_transformer.setSrcPath(tmpDir); tmpDir = dirMgr.getTempDir(); l_transformer.setDestPath(tmpDir); l_transformer.setMapperNum(getMapperNum()); l_transformer.setReducerNum(getReducerNum()); l_transformer.setOutputValueClass(LabeledAdjSetVertex.class); l_transformer.execute(); Graph src; Graph dest; Path path_to_remember = tmpDir; System.out.println("++++++>" + dirMgr.getSeqNum() + ": SpanningTreeRootChoose"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); GraphAlgorithm choose_root = new SpanningTreeRootChoose(); choose_root.setConf(context); choose_root.setSource(src); choose_root.setDestination(dest); choose_root.setMapperNum(getMapperNum()); choose_root.setReducerNum(getReducerNum()); choose_root.execute(); Path the_file = new Path(tmpDir.toString() + "/part-00000"); FileSystem client = FileSystem.get(context); if (!client.exists(the_file)) { throw new ProcessorExecutionException("Did not find the chosen vertex in " + the_file.toString()); } FSDataInputStream input_stream = client.open(the_file); ByteArrayOutputStream output_stream = new ByteArrayOutputStream(); IOUtils.copyBytes(input_stream, output_stream, context, false); String the_line = output_stream.toString(); String root_vertex_id = the_line.substring(SpanningTreeRootChoose.SPANNING_TREE_ROOT.length()).trim(); input_stream.close(); output_stream.close(); System.out.println("++++++> Chosen the root of spanning tree = " + root_vertex_id); while (true) { System.out.println("++++++>" + dirMgr.getSeqNum() + " Generate the spanning tree rooted at : (" + root_vertex_id + ") from " + tmpDir); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); path_to_remember = tmpDir; GraphAlgorithm spanning = new SpanningTreeGenerate(); spanning.setConf(context); spanning.setSource(src); spanning.setDestination(dest); spanning.setMapperNum(getMapperNum()); spanning.setReducerNum(getReducerNum()); spanning.setParameter(ConstantLabels.ROOT_ID, root_vertex_id); spanning.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + " Test spanning convergence"); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm conv_tester = new SpanningConvergenceTest(); conv_tester.setConf(context); conv_tester.setSource(src); conv_tester.setDestination(dest); conv_tester.setMapperNum(getMapperNum()); conv_tester.setReducerNum(getReducerNum()); conv_tester.execute(); long vertexes_out_of_tree = MRConsoleReader.getMapOutputRecordNum(conv_tester.getFinalStatus()); System.out.println("++++++> number of vertexes out of the spanning tree = " + vertexes_out_of_tree); if (vertexes_out_of_tree == 0) { break; } } System.out.println("++++++> From spanning tree to sets of edges"); src = new Graph(Graph.defaultGraph()); src.setPath(path_to_remember); tmpDir = dirMgr.getTempDir(); dest = new Graph(Graph.defaultGraph()); dest.setPath(tmpDir); GraphAlgorithm tree2set = new Tree2EdgeSet(); tree2set.setConf(context); tree2set.setSource(src); tree2set.setDestination(dest); tree2set.setMapperNum(getMapperNum()); tree2set.setReducerNum(getReducerNum()); tree2set.execute(); long map_input_records_num = -1; long map_output_records_num = -2; Stack<Path> expanding_stack = new Stack<Path>(); do { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorJoin"); GraphAlgorithm minorjoin = new EdgeSetMinorJoin(); minorjoin.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorjoin.setSource(src); minorjoin.setDestination(dest); minorjoin.setMapperNum(getMapperNum()); minorjoin.setReducerNum(getReducerNum()); minorjoin.execute(); expanding_stack.push(tmpDir); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetJoin"); GraphAlgorithm join = new EdgeSetJoin(); join.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); join.setSource(src); join.setDestination(dest); join.setMapperNum(getMapperNum()); join.setReducerNum(getReducerNum()); join.execute(); map_input_records_num = MRConsoleReader.getMapInputRecordNum(join.getFinalStatus()); map_output_records_num = MRConsoleReader.getMapOutputRecordNum(join.getFinalStatus()); System.out.println("++++++> map in/out : " + map_input_records_num + "/" + map_output_records_num); } while (map_input_records_num != map_output_records_num); while (expanding_stack.size() > 0) { System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetExpand"); GraphAlgorithm expand = new EdgeSetExpand(); expand.setConf(context); src = new Graph(Graph.defaultGraph()); src.addPath(expanding_stack.pop()); src.addPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); expand.setSource(src); expand.setDestination(dest); expand.setMapperNum(getMapperNum()); expand.setReducerNum(getReducerNum()); expand.execute(); System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetMinorExpand"); GraphAlgorithm minorexpand = new EdgeSetMinorExpand(); minorexpand.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); tmpDir = dirMgr.getTempDir(); dest.setPath(tmpDir); minorexpand.setSource(src); minorexpand.setDestination(dest); minorexpand.setMapperNum(getMapperNum()); minorexpand.setReducerNum(getReducerNum()); minorexpand.execute(); } System.out.println("++++++>" + dirMgr.getSeqNum() + ": EdgeSetSummarize"); GraphAlgorithm summarize = new EdgeSetSummarize(); summarize.setConf(context); src = new Graph(Graph.defaultGraph()); src.setPath(tmpDir); dest = new Graph(Graph.defaultGraph()); dest.setPath(getDestination().getPath()); summarize.setSource(src); summarize.setDestination(dest); summarize.setMapperNum(getMapperNum()); summarize.setReducerNum(getReducerNum()); summarize.execute(); dirMgr.deleteAll(); } catch (IOException e) { throw new ProcessorExecutionException(e); } catch (IllegalAccessException e) { throw new ProcessorExecutionException(e); } }
Code Sample 2:
private void copyFile(File s, File d) throws IOException { d.getParentFile().mkdirs(); FileChannel inChannel = new FileInputStream(s).getChannel(); FileChannel outChannel = new FileOutputStream(d).getChannel(); int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } inChannel.close(); outChannel.close(); d.setLastModified(s.lastModified()); }
|
11
|
Code Sample 1:
private void fileCopy(final File src, final File dest) throws IOException { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
Code Sample 2:
private static FileChannel getFileChannel(File file, boolean isOut, boolean append) throws OpenR66ProtocolSystemException { FileChannel fileChannel = null; try { if (isOut) { FileOutputStream fileOutputStream = new FileOutputStream(file.getPath(), append); fileChannel = fileOutputStream.getChannel(); if (append) { try { fileChannel.position(file.length()); } catch (IOException e) { } } } else { if (!file.exists()) { throw new OpenR66ProtocolSystemException("File does not exist"); } FileInputStream fileInputStream = new FileInputStream(file.getPath()); fileChannel = fileInputStream.getChannel(); } } catch (FileNotFoundException e) { throw new OpenR66ProtocolSystemException("File not found", e); } return fileChannel; }
|
11
|
Code Sample 1:
@Override public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.reset(); digest.update(((String) salt).getBytes("UTF-8")); String encodedRawPass = new String(digest.digest(rawPass.getBytes("UTF-8"))); return encodedRawPass.equals(encPass); } catch (Throwable e) { throw new DataAccessException("Error al codificar la contrase�a", e) { private static final long serialVersionUID = -302443565702455874L; }; } }
Code Sample 2:
public void actionPerformed(java.awt.event.ActionEvent e) { try { setStatus(DigestSignTask.RESET, ""); if (e.getSource() == sd) if (retriveEncodedDigestFromServer()) setStatus(DigestSignTask.RESET, "Inserire il pin e battere INVIO per firmare."); if (e.getSource() == pwd) { initStatus(0, DigestSignTask.SIGN_MAXIMUM); if (detectCardAndCriptoki()) { dsTask = new DigestSignTask(getCryptokiLib(), getSignerLabel(), log); timer = new Timer(ONE_SECOND, new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { setStatus(dsTask.getCurrent(), dsTask.getMessage()); if (dsTask.done()) { timer.stop(); progressBar.setValue(progressBar.getMinimum()); if (dsTask.getCurrent() == DigestSignTask.SIGN_DONE) { Toolkit.getDefaultToolkit().beep(); setEncryptedDigest(dsTask.getEncryptedDigest()); returnEncryptedDigestToForm(); setCertificate(dsTask.getCertificate()); returnCertificateToForm(); if (getSubmitAfterSigning()) { submitForm(); } } enableControls(true); } } }); sign(); } } if (e.getSource() == enc) { log.println("\nCalculating digest ...\n"); java.security.MessageDigest md5 = java.security.MessageDigest.getInstance("MD5"); md5.update(dataArea.getText().getBytes("UTF8")); byte[] digest = md5.digest(); log.println("digest:\n" + formatAsHexString(digest)); log.println("Done."); setEncodedDigest(encodeFromBytes(digest)); returnDigestToForm(); } if (e.getSource() == ld) retriveEncodedDigestFromForm(); if (e.getSource() == led) retriveEncryptedDigestFromForm(); if (e.getSource() == v) { verify(); } } catch (Exception ex) { log.println(ex.toString()); } finally { pwd.setText(""); } }
|
00
|
Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
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; }
|
11
|
Code Sample 1:
private boolean passwordMatches(String user, String plainPassword, String scrambledPassword) { MessageDigest md; byte[] temp_digest, pass_digest; byte[] hex_digest = new byte[35]; byte[] scrambled = scrambledPassword.getBytes(); try { md = MessageDigest.getInstance("MD5"); md.update(plainPassword.getBytes("US-ASCII")); md.update(user.getBytes("US-ASCII")); temp_digest = md.digest(); Utils.bytesToHex(temp_digest, hex_digest, 0); md.update(hex_digest, 0, 32); md.update(salt.getBytes()); pass_digest = md.digest(); Utils.bytesToHex(pass_digest, hex_digest, 3); hex_digest[0] = (byte) 'm'; hex_digest[1] = (byte) 'd'; hex_digest[2] = (byte) '5'; for (int i = 0; i < hex_digest.length; i++) { if (scrambled[i] != hex_digest[i]) { return false; } } } catch (Exception e) { logger.error(e); } return true; }
Code Sample 2:
public static String getPasswordHash(String password) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes()); byte[] byteData = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < byteData.length; i++) { sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { logger.log(Level.SEVERE, "Unknow error in hashing password", e); return "Unknow error, check system log"; } }
|
11
|
Code Sample 1:
private static String GetSHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return LoginHttpPostProcessor.ConvertToHex(sha1hash); }
Code Sample 2:
private byte[] digestPassword(byte[] salt, String password) throws AuthenticationException { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF8")); return md.digest(); } catch (Exception e) { throw new AuthenticationException(MESSAGE_CONFIGURATION_ERROR_KEY, e); } }
|
11
|
Code Sample 1:
public static String crypt(String str) { if (str == null || str.length() == 0) { throw new IllegalArgumentException("String to encript cannot be null or zero length"); } StringBuffer hexString = new StringBuffer(); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } 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])); } } return hexString.toString(); }
Code Sample 2:
private String md5(String value) { String md5Value = "1"; try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(value.getBytes()); md5Value = getHex(digest.digest()); } catch (Exception e) { e.printStackTrace(); } return md5Value; }
|
11
|
Code Sample 1:
public void store(String path, InputStream stream) throws IOException { toIgnore.add(normalizePath(path)); ZipEntry entry = new ZipEntry(path); zipOutput.putNextEntry(entry); IOUtils.copy(stream, zipOutput); zipOutput.closeEntry(); }
Code Sample 2:
public void xtestURL1() throws Exception { URL url = new URL(IOTest.URL); InputStream inputStream = url.openStream(); OutputStream outputStream = new FileOutputStream("C:/Temp/testURL1.mp4"); IOUtils.copy(inputStream, outputStream); inputStream.close(); outputStream.close(); }
|
00
|
Code Sample 1:
public static String crypt(String strPassword, String strSalt) { try { StringTokenizer st = new StringTokenizer(strSalt, "$"); st.nextToken(); byte[] abyPassword = strPassword.getBytes(); byte[] abySalt = st.nextToken().getBytes(); MessageDigest _md = MessageDigest.getInstance("MD5"); _md.update(abyPassword); _md.update(MAGIC.getBytes()); _md.update(abySalt); MessageDigest md2 = MessageDigest.getInstance("MD5"); md2.update(abyPassword); md2.update(abySalt); md2.update(abyPassword); byte[] abyFinal = md2.digest(); for (int n = abyPassword.length; n > 0; n -= 16) { _md.update(abyFinal, 0, n > 16 ? 16 : n); } abyFinal = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; for (int j = 0, i = abyPassword.length; i != 0; i >>>= 1) { if ((i & 1) == 1) _md.update(abyFinal, j, 1); else _md.update(abyPassword, j, 1); } StringBuffer sbPasswd = new StringBuffer(); sbPasswd.append(MAGIC); sbPasswd.append(new String(abySalt)); sbPasswd.append('$'); abyFinal = _md.digest(); for (int n = 0; n < 1000; n++) { MessageDigest md3 = MessageDigest.getInstance("MD5"); if ((n & 1) != 0) md3.update(abyPassword); else md3.update(abyFinal); if ((n % 3) != 0) md3.update(abySalt); if ((n % 7) != 0) md3.update(abyPassword); if ((n & 1) != 0) md3.update(abyFinal); else md3.update(abyPassword); abyFinal = md3.digest(); } int[] anFinal = new int[] { (abyFinal[0] & 0x7f) | (abyFinal[0] & 0x80), (abyFinal[1] & 0x7f) | (abyFinal[1] & 0x80), (abyFinal[2] & 0x7f) | (abyFinal[2] & 0x80), (abyFinal[3] & 0x7f) | (abyFinal[3] & 0x80), (abyFinal[4] & 0x7f) | (abyFinal[4] & 0x80), (abyFinal[5] & 0x7f) | (abyFinal[5] & 0x80), (abyFinal[6] & 0x7f) | (abyFinal[6] & 0x80), (abyFinal[7] & 0x7f) | (abyFinal[7] & 0x80), (abyFinal[8] & 0x7f) | (abyFinal[8] & 0x80), (abyFinal[9] & 0x7f) | (abyFinal[9] & 0x80), (abyFinal[10] & 0x7f) | (abyFinal[10] & 0x80), (abyFinal[11] & 0x7f) | (abyFinal[11] & 0x80), (abyFinal[12] & 0x7f) | (abyFinal[12] & 0x80), (abyFinal[13] & 0x7f) | (abyFinal[13] & 0x80), (abyFinal[14] & 0x7f) | (abyFinal[14] & 0x80), (abyFinal[15] & 0x7f) | (abyFinal[15] & 0x80) }; to64(sbPasswd, anFinal[0] << 16 | anFinal[6] << 8 | anFinal[12], 4); to64(sbPasswd, anFinal[1] << 16 | anFinal[7] << 8 | anFinal[13], 4); to64(sbPasswd, anFinal[2] << 16 | anFinal[8] << 8 | anFinal[14], 4); to64(sbPasswd, anFinal[3] << 16 | anFinal[9] << 8 | anFinal[15], 4); to64(sbPasswd, anFinal[4] << 16 | anFinal[10] << 8 | anFinal[5], 4); to64(sbPasswd, anFinal[11], 2); return sbPasswd.toString(); } catch (NoSuchAlgorithmException e) { return null; } }
Code Sample 2:
public void create() throws IOException { FileChannel fc = new FileInputStream(sourceFile).getChannel(); for (RangeArrayElement element : array) { FileChannel fc_ = fc.position(element.starting()); File part = new File(destinationDirectory, "_0x" + Long.toHexString(element.starting()) + ".partial"); FileChannel partfc = new FileOutputStream(part).getChannel(); partfc.transferFrom(fc_, 0, element.getSize()); partfc.force(true); partfc.close(); } fc.close(); }
|
00
|
Code Sample 1:
protected List<? extends SearchResult> searchVideo(String words, int number, int offset, CancelMonitor cancelMonitor) { List<VideoSearchResult> resultsList = new ArrayList<>(); try { // set up the HTTP request factory HttpTransport transport = new NetHttpTransport(); HttpRequestFactory factory = transport.createRequestFactory(new HttpRequestInitializer() { @Override public void initialize(HttpRequest request) { // set the parser JsonCParser parser = new JsonCParser(); parser.jsonFactory = JSON_FACTORY; request.addParser(parser); // set up the Google headers GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("OGLExplorer/1.0"); headers.gdataVersion = "2"; request.headers = headers; } }); // build the YouTube URL YouTubeUrl url = new YouTubeUrl("https://gdata.youtube.com/feeds/api/videos"); url.maxResults = number; url.words = words; url.startIndex = offset + 1; // build HttpRequest request = factory.buildGetRequest(url); // execute HttpResponse response = request.execute(); VideoFeed feed = response.parseAs(VideoFeed.class); if (feed.items == null) { return null; } // browse result and convert them to the local generic object model for (int i = 0; i < feed.items.size() && !cancelMonitor.isCanceled(); i++) { Video result = feed.items.get(i); VideoSearchResult modelResult = new VideoSearchResult(offset + i + 1); modelResult.setTitle(result.title); modelResult.setDescription(result.description); modelResult.setThumbnailURL(new URL(result.thumbnail.lowThumbnailURL)); modelResult.setPath(result.player.defaultUrl); resultsList.add(modelResult); } } catch (Exception e) { e.printStackTrace(); } if (cancelMonitor.isCanceled()) { return null; } return resultsList; }
Code Sample 2:
public static int[] bubbleSortOtimizado(int... a) { boolean swapped; int n = a.length - 2; do { swapped = false; for (int i = 0; i <= n; i++) { if (a[i] > a[i + 1]) { int tmp = a[i]; a[i] = a[i + 1]; a[i + 1] = tmp; swapped = true; } } n = n - 1; } while (swapped); return a; }
|
00
|
Code Sample 1:
public static String upLoadImg(File pic, String uid) throws Throwable { System.out.println("开始上传======================================================="); HttpPost post = getHttpPost(getUploadUrl(uid), uid); FileBody file = new FileBody(pic, "image/jpg"); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("pic1", file); post.setEntity(reqEntity); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); post.abort(); if (status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_MOVED_PERMANENTLY) { String newuri = response.getHeaders("location")[0].getValue(); System.out.println(newuri); return newuri.substring(newuri.indexOf("pid=") + 4, newuri.indexOf("&token=")); } return null; }
Code Sample 2:
public InputStream getDaoConfig(String connectionType) throws IOException { URL url = null; if (connectionType.equals(SQL.ORACLE)) { url = DBCreateConfig.class.getResource("oracle.xml"); } else if (connectionType.equals(SQL.SQL2K)) { url = DBCreateConfig.class.getResource("sql2k.xml"); } return url.openStream(); }
|
00
|
Code Sample 1:
private void doLogin(String password) throws LoginFailedException, IncorrectPasswordException { final long mgr = Constants.MANAGER; Data data, response; try { response = sendAndWait(new Request(mgr)).get(0); MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 hash not supported."); } byte[] challenge = response.getBytes(); md.update(challenge); md.update(password.getBytes(Data.STRING_ENCODING)); try { data = Data.valueOf(md.digest()); response = sendAndWait(new Request(mgr).add(0, data)).get(0); } catch (ExecutionException ex) { throw new IncorrectPasswordException(); } setLoginMessage(response.getString()); response = sendAndWait(new Request(mgr).add(0, getLoginData())).get(0); ID = response.getWord(); registerSettings(); } catch (InterruptedException ex) { throw new LoginFailedException(ex); } catch (ExecutionException ex) { throw new LoginFailedException(ex); } catch (IOException ex) { throw new LoginFailedException(ex); } }
Code Sample 2:
public boolean setRecipeToTimetable(int recipeId, Timestamp time, int meal) { System.out.println("setRecipeToTimetable"); PreparedStatement statement = null; StringBuffer query = new StringBuffer("insert into timetable (recipe_id, time, meal) values (?,?,?)"); try { conn = getConnection(); statement = conn.prepareStatement(query.toString()); statement.setInt(1, recipeId); statement.setTimestamp(2, time); statement.setInt(3, meal); statement.executeUpdate(); conn.commit(); } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { } MainFrame.appendStatusText("Error when trying to execute sql: " + e.getMessage()); } finally { try { if (statement != null) statement.close(); statement = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } return true; }
|
11
|
Code Sample 1:
public static void copyFile(String original, String destination) throws Exception { File original_file = new File(original); File destination_file = new File(destination); if (!original_file.exists()) throw new Exception("File with path " + original + " does not exist."); if (destination_file.exists()) throw new Exception("File with path " + destination + " already exists."); FileReader in = new FileReader(original_file); FileWriter out = new FileWriter(destination_file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
Code Sample 2:
public static void copy(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
|
11
|
Code Sample 1:
private void transformFile(File input, File output, Cipher cipher, boolean compress, String progressMessage) throws IOException { FileInputStream fileInputStream = new FileInputStream(input); InputStream inputStream; if (progressMessage != null) { inputStream = new ProgressMonitorInputStream(null, progressMessage, fileInputStream); } else { inputStream = fileInputStream; } FilterInputStream is = new BufferedInputStream(inputStream); FilterOutputStream os = new BufferedOutputStream(new FileOutputStream(output)); FilterInputStream fis; FilterOutputStream fos; if (compress) { fis = is; fos = new GZIPOutputStream(new CipherOutputStream(os, cipher)); } else { fis = new GZIPInputStream(new CipherInputStream(is, cipher)); fos = os; } byte[] buffer = new byte[cipher.getBlockSize() * blocksInBuffer]; int readLength = fis.read(buffer); while (readLength != -1) { fos.write(buffer, 0, readLength); readLength = fis.read(buffer); } if (compress) { GZIPOutputStream gos = (GZIPOutputStream) fos; gos.finish(); } fos.close(); fis.close(); }
Code Sample 2:
public void visit(BosMember member) throws BosException { String relative = AddressingUtil.getRelativePath(member.getDataSourceUri(), baseUri); URL resultUrl; try { resultUrl = new URL(outputUrl, relative); File resultFile = new File(resultUrl.toURI()); resultFile.getParentFile().mkdirs(); log.info("Creating result file \"" + resultFile.getAbsolutePath() + "\"..."); IOUtils.copy(member.getInputStream(), new FileOutputStream(resultFile)); } catch (Exception e) { throw new BosException(e); } }
|
00
|
Code Sample 1:
public static void saveFileFromURL(URL url, File destinationFile) throws IOException { FileOutputStream fo = new FileOutputStream(destinationFile); InputStream is = url.openStream(); byte[] data = new byte[1024]; int bytecount = 0; do { fo.write(data, 0, bytecount); bytecount = is.read(data); } while (bytecount > 0); fo.flush(); fo.close(); }
Code Sample 2:
public void test1() throws Exception { String senha = "minhaSenha"; MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(senha.getBytes()); byte[] bytes = digest.digest(); BASE64Encoder encoder = new BASE64Encoder(); String senhaCodificada = encoder.encode(bytes); System.out.println("Senha : " + senha); System.out.println("Senha SHA1: " + senhaCodificada); }
|
00
|
Code Sample 1:
private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
00
|
Code Sample 1:
public boolean compile(URL url) { try { final InputStream stream = url.openStream(); final InputSource input = new InputSource(stream); input.setSystemId(url.toString()); return compile(input, _className); } catch (IOException e) { _parser.reportError(Constants.FATAL, new ErrorMsg(e)); return false; } }
Code Sample 2:
public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; inputLine = in.readLine(); String dist_metric = in.readLine(); File outFile = new File("data.txt"); FileWriter outw = new FileWriter(outFile); outw.write(inputLine); outw.close(); File sample_coords = new File("sample_coords.txt"); sample_coords.delete(); File sp_coords = new File("sp_coords.txt"); sp_coords.delete(); try { System.out.println("Running python script..."); System.out.println("Command: " + "python l19test.py " + "\"" + dist_metric + "\""); Process pr = Runtime.getRuntime().exec("python l19test.py " + dist_metric); BufferedReader br = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Process Exit Value: " + exitVal); System.out.println("done."); } catch (Exception e) { System.out.println("Unable to run python script for PCoA analysis"); } File myFile = new File("sp_coords.txt"); byte[] mybytearray = new byte[(new Long(myFile.length())).intValue()]; FileInputStream fis = new FileInputStream(myFile); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); for (int i = 0; i < myFile.length(); i++) { out.writeByte(fis.read()); } myFile = new File("sample_coords.txt"); mybytearray = new byte[(int) myFile.length()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); myFile = new File("evals.txt"); mybytearray = new byte[(new Long(myFile.length())).intValue()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); out.flush(); out.close(); in.close(); clientSocket.close(); serverSocket.close(); }
Code Sample 2:
protected Object openDialogBox(Control cellEditorWindow) { FileDialog dialog = new FileDialog(parent.getShell(), SWT.OPEN); dialog.setFilterExtensions(new String[] { "*.jpg;*.JPG;*.JPEG;*.gif;*.GIF;*.png;*.PNG", "*.jpg;*.JPG;*.JPEG", "*.gif;*.GIF", "*.png;*.PNG" }); dialog.setFilterNames(new String[] { "All", "Joint Photographic Experts Group (JPEG)", "Graphics Interchange Format (GIF)", "Portable Network Graphics (PNG)" }); String imagePath = dialog.open(); if (imagePath == null) return null; IProject project = ProjectManager.getInstance().getCurrentProject(); String projectFolderPath = project.getLocation().toOSString(); File imageFile = new File(imagePath); String fileName = imageFile.getName(); ImageData imageData = null; try { imageData = new ImageData(imagePath); } catch (SWTException e) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } if (imageData == null) { UserErrorException error = new UserErrorException(PropertyHandler.getInstance().getProperty("_invalid_image_title"), PropertyHandler.getInstance().getProperty("_invalid_image_text")); UserErrorService.INSTANCE.showError(error); return null; } File copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + fileName); if (copiedImageFile.exists()) { Path path = new Path(copiedImageFile.getPath()); copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString() + "." + path.getFileExtension()); } try { copiedImageFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); copiedImageFile = null; } if (copiedImageFile == null) { copiedImageFile = new File(projectFolderPath + File.separator + imageFolderPath + File.separator + UUID.randomUUID().toString()); try { copiedImageFile.createNewFile(); } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } } FileReader in = null; FileWriter out = null; try { in = new FileReader(imageFile); out = new FileWriter(copiedImageFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return ""; } return imageFolderPath + File.separator + copiedImageFile.getName(); }
|
11
|
Code Sample 1:
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
Code Sample 2:
private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } long time = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream fos = null; FileChannel input = null; FileChannel output = null; try { fis = new FileInputStream(srcFile); fos = new FileOutputStream(destFile); input = fis.getChannel(); output = fos.getChannel(); long size = input.size(); long pos = 0; long count = 0; while (pos < size && continueWriting(pos, size)) { count = (size - pos) > FIFTY_MB ? FIFTY_MB : (size - pos); pos += output.transferFrom(input, pos, count); } } finally { output.close(); IOUtils.closeQuietly(fos); input.close(); IOUtils.closeQuietly(fis); } if (srcFile.length() != destFile.length()) { if (DiskManager.isLocked()) throw new IOException("Copy stopped since VtM was working"); else throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } else { time = System.currentTimeMillis() - time; long speed = (destFile.length() / time) / 1000; DiskManager.addDiskSpeed(speed); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
|
11
|
Code Sample 1:
@Test public void testCopy_readerToOutputStream() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, false, true); IOUtils.copy(reader, out); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
Code Sample 2:
public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
|
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 static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
|
11
|
Code Sample 1:
public static String getWebContent(String remoteUrl) { StringBuffer sb = new StringBuffer(); try { java.net.URL url = new java.net.URL(remoteUrl); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { sb.append(line); } in.close(); } catch (Exception e) { logger.error("获取远程网址内容失败 - " + remoteUrl, e); } return sb.toString(); }
Code Sample 2:
private Image retrievePdsImage(double lat, double lon) { imageDone = false; try { StringBuffer urlBuff = new StringBuffer(psdUrl + psdCgi + "?"); urlBuff.append("DATA_SET_NAME=" + dataSet); urlBuff.append("&VERSION=" + version); urlBuff.append("&PIXEL_TYPE=" + pixelType); urlBuff.append("&PROJECTION=" + projection); urlBuff.append("&STRETCH=" + stretch); urlBuff.append("&GRIDLINE_FREQUENCY=" + gridlineFrequency); urlBuff.append("&SCALE=" + URLEncoder.encode(scale)); urlBuff.append("&RESOLUTION=" + resolution); urlBuff.append("&LATBOX=" + latbox); urlBuff.append("&LONBOX=" + lonbox); urlBuff.append("&BANDS_SELECTED=" + bandsSelected); urlBuff.append("&LAT=" + lat); urlBuff.append("&LON=" + lon); URL url = new URL(urlBuff.toString()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String result = null; String line; String imageSrc; int count = 0; while ((line = in.readLine()) != null) { if (count == 6) result = line; count++; } int startIndex = result.indexOf("<TH COLSPAN=2 ROWSPAN=2><IMG SRC = \"") + 36; int endIndex = result.indexOf("\"", startIndex); imageSrc = result.substring(startIndex, endIndex); URL imageUrl = new URL(imageSrc); return (Toolkit.getDefaultToolkit().getImage(imageUrl)); } catch (MalformedURLException e) { } catch (IOException e) { } return null; }
|
00
|
Code Sample 1:
@Override public InputStream getResourceAsStream(String path) { try { URL url = this.getResource(path); if (url == null) return null; return url.openStream(); } catch (Exception e) { log(e.getMessage(), e); return null; } }
Code Sample 2:
public void bubbleSort(int[] arr) { BasicProcessor.getInstance().getStartBlock(); BasicProcessor.getInstance().getVarDeclaration(); boolean swapped = true; BasicProcessor.getInstance().getVarDeclaration(); int j = 0; BasicProcessor.getInstance().getVarDeclaration(); int tmp; { BasicProcessor.getInstance().getWhileStatement(); while (swapped) { BasicProcessor.getInstance().getStartBlock(); swapped = false; j++; { BasicProcessor.getInstance().getForStatement(); for (int i = 0; i < arr.length - j; i++) { BasicProcessor.getInstance().getStartBlock(); { BasicProcessor.getInstance().getIfStatement(); if (arr[i] > arr[i + 1]) { BasicProcessor.getInstance().getStartBlock(); tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); } } BasicProcessor.getInstance().getEndBlock(); }
|
11
|
Code Sample 1:
public static void copyFile(String target, String source) { try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { ExceptionHelper.showErrorDialog(e); } }
Code Sample 2:
public static void main(String[] args) { String inFile = "test_data/blobs.png"; String outFile = "ReadWriteTest.png"; itkImageFileReaderUC2_Pointer reader = itkImageFileReaderUC2.itkImageFileReaderUC2_New(); itkImageFileWriterUC2_Pointer writer = itkImageFileWriterUC2.itkImageFileWriterUC2_New(); reader.SetFileName(inFile); writer.SetFileName(outFile); writer.SetInput(reader.GetOutput()); writer.Update(); }
|
00
|
Code Sample 1:
public void testStorageByteArray() throws Exception { TranslationResponseInMemory r = new TranslationResponseInMemory(2048, "UTF-8"); { OutputStream output = r.getOutputStream(); output.write("This is an example".getBytes("UTF-8")); output.write(" and another one.".getBytes("UTF-8")); assertEquals("This is an example and another one.", r.getText()); } { InputStream input = r.getInputStream(); StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer, "UTF-8"); } finally { input.close(); writer.close(); } assertEquals("This is an example and another one.", writer.toString()); } { OutputStream output = r.getOutputStream(); output.write(" and another line".getBytes("UTF-8")); assertEquals("This is an example and another one. and another line", r.getText()); } { Writer output = r.getWriter(); output.write(" and write some more"); assertEquals("This is an example and another one. and another line and write some more", r.getText()); } { r.addText(" and even more."); assertEquals("This is an example and another one. and another line and write some more and even more.", r.getText()); } assertFalse(r.hasEnded()); r.setEndState(ResponseStateOk.getInstance()); assertTrue(r.hasEnded()); try { r.getOutputStream(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } try { r.getWriter(); fail("Previous line should throw IOException as result closed."); } catch (IOException e) { } }
Code Sample 2:
static InputStream getUrlStream(String url) throws IOException { System.out.print("getting : " + url + " ... "); long start = System.currentTimeMillis(); URLConnection c = new URL(url).openConnection(); InputStream is = c.getInputStream(); System.out.print((System.currentTimeMillis() - start) + "ms\n"); return is; }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.