label
class label 2
classes | source_code
stringlengths 398
72.9k
|
|---|---|
11
|
Code Sample 1:
private void doPOST(HttpURLConnection connection, InputStream inputXML) throws MessageServiceException { try { OutputStream requestStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.copyAndClose(inputXML, requestStream); connection.connect(); } catch (IOException e) { throw new MessageServiceException(e.getMessage(), 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(); } }
|
11
|
Code Sample 1:
private void copyFile(String inputPath, String basis, String filename) throws GLMRessourceFileException { try { FileChannel inChannel = new FileInputStream(new File(inputPath)).getChannel(); File target = new File(basis, filename); FileChannel outChannel = new FileOutputStream(target).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { throw new GLMRessourceFileException(7); } }
Code Sample 2:
protected static URL[] createUrls(URL jarUrls[]) { ArrayList<URL> additionalUrls = new ArrayList<URL>(Arrays.asList(jarUrls)); for (URL ju : jarUrls) { try { JarFile jar = new JarFile(ju.getFile()); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { JarEntry j = entries.nextElement(); if (j.isDirectory()) continue; if (j.getName().startsWith("lib/") && j.getName().endsWith(".jar")) { URL url = new URL("jar:" + ju.getProtocol() + ":" + ju.getFile() + "!/" + j.getName()); InputStream is = url.openStream(); File tmpFile = File.createTempFile("SCDeploy", ".jar"); FileOutputStream fos = new FileOutputStream(tmpFile); IOUtils.copy(is, fos); is.close(); fos.close(); additionalUrls.add(new URL("file://" + tmpFile.getAbsolutePath())); } } } catch (IOException e) { } } return additionalUrls.toArray(new URL[] {}); }
|
11
|
Code Sample 1:
protected void doRestoreOrganize() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TABLE; String strSelQuery = "SELECT organize_id,organize_type_id,organize_name,organize_manager," + "organize_describe,work_type,show_order,position_x,position_y " + "FROM " + Common.ORGANIZE_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TABLE + " " + "(organize_id,organize_type_id,organize_name,organize_manager," + "organize_describe,work_type,show_order,position_x,position_y) " + "VALUES (?,?,?,?,?,?,?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("organize_id")); ps.setString(2, result.getString("organize_type_id")); ps.setString(3, result.getString("organize_name")); ps.setString(4, result.getString("organize_manager")); ps.setString(5, result.getString("organize_describe")); ps.setString(6, result.getString("work_type")); ps.setInt(7, result.getInt("show_order")); ps.setInt(8, result.getInt("position_x")); ps.setInt(9, result.getInt("position_y")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganize(): ERROR Inserting data " + "in T_SYS_ORGANIZE INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganize(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganize(): SQLException while committing or rollback"); } }
Code Sample 2:
protected void doRestoreOrganizeType() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_TABLE; String strSelQuery = "SELECT organize_type_id,organize_type_name,width " + "FROM " + Common.ORGANIZE_TYPE_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_TABLE + " " + "(organize_type_id,organize_type_name,width) " + "VALUES (?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("organize_type_id")); ps.setString(2, result.getString("organize_type_name")); ps.setInt(3, result.getInt("width")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): SQLException while committing or rollback"); } }
|
00
|
Code Sample 1:
static final void saveModule(Module module, DBConnector connector) throws IOException { String type = "pre"; if (module.isPreModule()) type = "pre"; else if (module.isPostModule()) type = "post"; else if (module.isExceptionModule()) type = "exception"; else throw new IllegalArgumentException("Module must be of a known type."); Properties props = module.getState(); Connection con = null; PreparedStatement ps = null; Statement st = null; try { con = connector.getDB(); con.setAutoCommit(false); st = con.createStatement(); st.executeUpdate("DELETE FROM instance where id=" + module.getId()); st.executeUpdate("DELETE FROM instance_property where instance_id=" + module.getId()); ps = con.prepareStatement("INSERT INTO instance VALUES (?, ?, ?, ?)"); ps.setInt(1, module.getId()); ps.setBoolean(2, module.getActive()); ps.setString(3, module.getClass().getName()); ps.setString(4, type); ps.executeUpdate(); ps.close(); ps = con.prepareStatement("INSERT INTO instance_property values(?, ?, ?)"); for (Enumeration<Object> keys = props.keys(); keys.hasMoreElements(); ) { String key = (String) keys.nextElement(); String value = props.getProperty(key); ps.setInt(1, module.getId()); ps.setString(2, key); ps.setString(3, value); ps.addBatch(); } ps.executeBatch(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } throw new IOException(e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (SQLException ignore) { } } if (ps != null) { try { ps.close(); } catch (SQLException ignore) { } } if (con != null) { try { con.close(); } catch (SQLException ignore) { } } } }
Code Sample 2:
@SuppressWarnings("deprecation") private void loadClassFilesFromJar() { IPackageFragmentRoot packageFragmentRoot = (IPackageFragmentRoot) getJavaElement(); File jarFile = packageFragmentRoot.getResource().getLocation().toFile(); try { URL url = jarFile.toURL(); URLConnection u = url.openConnection(); ZipInputStream inputStream = new ZipInputStream(u.getInputStream()); ZipEntry entry = inputStream.getNextEntry(); while (null != entry) { if (entry.getName().endsWith(".class")) { ClassParser parser = new ClassParser(inputStream, entry.getName()); Repository.addClass(parser.parse()); } entry = inputStream.getNextEntry(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
|
11
|
Code Sample 1:
public boolean copy(File src, File dest, byte[] b) { if (src.isDirectory()) { String[] ss = src.list(); for (int i = 0; i < ss.length; i++) if (!copy(new File(src, ss[i]), new File(dest, ss[i]), b)) return false; return true; } delete(dest); dest.getParentFile().mkdirs(); try { FileInputStream fis = new FileInputStream(src); try { FileOutputStream fos = new FileOutputStream(dest); try { int read; while ((read = fis.read(b)) != -1) fos.write(b, 0, read); } finally { try { fos.close(); } catch (IOException ignore) { } register(dest); } } finally { fis.close(); } if (log.isDebugEnabled()) log.debug("Success: M-COPY " + src + " -> " + dest); return true; } catch (IOException e) { log.error("Failed: M-COPY " + src + " -> " + dest, e); return false; } }
Code Sample 2:
public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); while (in.read(buff) != -1) { PrintUtil.prt("%%%"); buff.flip(); out.write(buff); buff.clear(); } }
|
11
|
Code Sample 1:
void serialize(ZipOutputStream out) throws IOException { if ("imsmanifest.xml".equals(getFullName())) return; out.putNextEntry(new ZipEntry(getFullName())); IOUtils.copy(getDataStream(), out); out.closeEntry(); }
Code Sample 2:
protected void copy(File src, File dest) throws IOException { if (src.isDirectory() && dest.isFile()) throw new IOException("Cannot copy a directory to a file"); if (src.isDirectory()) { File newDir = new File(dest, src.getName()); if (!newDir.mkdirs()) throw new IOException("Cannot create a new Directory"); File[] entries = src.listFiles(); for (int i = 0; i < entries.length; ++i) copy(entries[i], newDir); return; } if (dest.isDirectory()) { File newFile = new File(dest, src.getName()); newFile.createNewFile(); copy(src, newFile); return; } try { if (src.length() == 0) { dest.createNewFile(); return; } FileChannel fc = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); long transfered = 0; long totalLength = src.length(); while (transfered < totalLength) { long num = fc.transferTo(transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException("Error while copying"); transfered += num; } dstChannel.close(); fc.close(); } catch (IOException e) { if (os.equals("Unix")) { _logger.fine("Trying to use cp to copy file..."); File cp = new File("/usr/bin/cp"); if (!cp.exists()) cp = new File("/bin/cp"); if (!cp.exists()) cp = new File("/usr/local/bin/cp"); if (!cp.exists()) cp = new File("/sbin/cp"); if (!cp.exists()) cp = new File("/usr/sbin/cp"); if (!cp.exists()) cp = new File("/usr/local/sbin/cp"); if (cp.exists()) { Process cpProcess = Runtime.getRuntime().exec(cp.getAbsolutePath() + " '" + src.getAbsolutePath() + "' '" + dest.getAbsolutePath() + "'"); int errCode; try { errCode = cpProcess.waitFor(); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
|
11
|
Code Sample 1:
public void resumereceive(HttpServletRequest req, HttpServletResponse resp, SessionCommand command) { setHeader(resp); try { logger.debug("ResRec: Resume a 'receive' session with session id " + command.getSession() + " this client already received " + command.getLen() + " bytes"); File tempFile = new File(this.getSyncWorkDirectory(req), command.getSession() + ".smodif"); if (!tempFile.exists()) { logger.debug("ResRec: the file doesn't exist, so we created it by serializing the entities"); try { OutputStream fos = new FileOutputStream(tempFile); syncServer.getServerModifications(command.getSession(), fos); fos.close(); } catch (ImogSerializationException mse) { logger.error(mse.getMessage(), mse); } } InputStream fis = new FileInputStream(tempFile); fis.skip(command.getLen()); resp.setContentLength(fis.available()); while (fis.available() > 0) { resp.getOutputStream().write(fis.read()); } resp.getOutputStream().flush(); resp.flushBuffer(); fis.close(); } catch (IOException ioe) { logger.error(ioe.getMessage()); } }
Code Sample 2:
private void trainDepParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractDepParser parser = null; OneVsAllDecoder decoder = null; if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, s_featureXml); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, s_featureXml); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, ENTRY_LEXICA); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, ENTRY_LEXICA); } else if (flag == ShiftPopParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train conditional"); decoder = new OneVsAllDecoder(m_model); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, t_map, decoder); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = null; DepTree tree; int n; if (s_format.equals(AbstractReader.FORMAT_DEP)) reader = new DepReader(s_trainFile, true); else if (s_format.equals(AbstractReader.FORMAT_CONLLX)) reader = new CoNLLXReader(s_trainFile, true); parser.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { parser.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- parsing: " + n); if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("- saving"); parser.saveTags(ENTRY_LEXICA); t_xml = parser.getDepFtrXml(); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE || flag == ShiftPopParser.FLAG_TRAIN_BOOST) { a_yx = parser.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_PARSER)); PrintStream fout = new PrintStream(zout); fout.print(s_depParser); fout.flush(); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_LEXICA)); IOUtils.copy(new FileInputStream(ENTRY_LEXICA), zout); zout.closeArchiveEntry(); if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) t_map = parser.getDepFtrMap(); } }
|
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:
@Test public void testWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
|
00
|
Code Sample 1:
public GGMunicipalities getListMunicipalities() throws IllegalStateException, GGException, Exception { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("method", "gg.photos.geo.getListMunicipality")); qparams.add(new BasicNameValuePair("key", this.key)); String url = REST_URL + "?" + URLEncodedUtils.format(qparams, "UTF-8"); URI uri = new URI(url); HttpGet httpget = new HttpGet(uri); HttpResponse response = httpClient.execute(httpget); int status = response.getStatusLine().getStatusCode(); errorCheck(response, status); InputStream content = response.getEntity().getContent(); GGMunicipalities municipalities = JAXB.unmarshal(content, GGMunicipalities.class); return municipalities; }
Code Sample 2:
private static void findDictionary() { java.net.URL url = Translator.class.getResource("Translator.class"); String location = url.getFile(); String dictionaryName = (String) Settings.getDefault().getSetting("dictionary"); InputStream inputStream; try { if (location.indexOf(".jar!") == -1) inputStream = new FileInputStream(location.substring(0, location.indexOf("Translator.class")) + dictionaryName); else { JarFile jarFile; if (location.indexOf("rachota.sourceforge.net") != -1) { String fileName = location.substring(0, location.indexOf("!/") + 2); url = new URL("jar:http://rachota.sourceforge.net/rachota_22.jar!/"); JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); jarFile = jarConnection.getJarFile(); } else { String fileName = System.getProperty("os.name").indexOf("Windows") == -1 ? "/" : ""; fileName = fileName + location.substring(6, location.indexOf(".jar") + 4); fileName = Tools.replaceAll(fileName, "%20", " "); jarFile = new JarFile(fileName); } ZipEntry entry = jarFile.getEntry("org/cesilko/rachota/core/" + dictionaryName); if (entry == null) { entry = jarFile.getEntry("org/cesilko/rachota/core/Dictionary_en_US.properties"); Settings.getDefault().setSetting("dictionary", "Dictionary_en_US.properties"); } inputStream = jarFile.getInputStream(entry); } dictionary = new PropertyResourceBundle(inputStream); } catch (Exception e) { System.out.println("Error: Reading from " + dictionaryName + " dictionary failed."); e.printStackTrace(); } }
|
11
|
Code Sample 1:
public static void copy(File inputFile, File target) throws IOException { if (!inputFile.exists()) return; OutputStream output = new FileOutputStream(target); InputStream input = new BufferedInputStream(new FileInputStream(inputFile)); int b; while ((b = input.read()) != -1) output.write(b); output.close(); input.close(); }
Code Sample 2:
public static void copyFile(File src, File dst) throws IOException { if (T.t) T.info("Copying " + src + " -> " + dst + "..."); FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dst); byte buf[] = new byte[40 * KB]; int read; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); } out.flush(); out.close(); in.close(); if (T.t) T.info("File copied."); }
|
11
|
Code Sample 1:
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); }
Code Sample 2:
private File uploadToTmp() { if (fileFileName == null) { return null; } File tmpFile = dataDir.tmpFile(shortname, fileFileName); log.debug("Uploading dwc archive file for new resource " + shortname + " to " + tmpFile.getAbsolutePath()); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(file); output = new FileOutputStream(tmpFile); IOUtils.copy(input, output); output.flush(); log.debug("Uploaded file " + fileFileName + " with content-type " + fileContentType); } catch (IOException e) { log.error(e); return null; } finally { if (output != null) { IOUtils.closeQuietly(output); } if (input != null) { IOUtils.closeQuietly(input); } } return tmpFile; }
|
00
|
Code Sample 1:
public static String upload_file(String sessionid, String localFilePath, String remoteTagPath) { String jsonstring = "If you see this message, there is some problem inside the function:upload_file()"; String srcPath = localFilePath; String uploadUrl = "https://s2.cloud.cm/rpc/json/?session_id=" + sessionid + "&c=Storage&m=upload_file&tag=" + remoteTagPath; String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; try { URL url = new URL(uploadUrl); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + end); dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + srcPath.substring(srcPath.lastIndexOf("/") + 1) + "\"" + end); dos.writeBytes(end); FileInputStream fis = new FileInputStream(srcPath); byte[] buffer = new byte[8192]; int count = 0; while ((count = fis.read(buffer)) != -1) { dos.write(buffer, 0, count); } fis.close(); dos.writeBytes(end); dos.writeBytes(twoHyphens + boundary + twoHyphens + end); dos.flush(); InputStream is = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(is, "utf-8"); BufferedReader br = new BufferedReader(isr); jsonstring = br.readLine(); dos.close(); is.close(); return jsonstring; } catch (Exception e) { e.printStackTrace(); } return jsonstring; }
Code Sample 2:
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
|
11
|
Code Sample 1:
private String generateStorageDir(String stringToBeHashed) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(stringToBeHashed.getBytes()); byte[] hashedKey = digest.digest(); return Util.encodeArrayToHexadecimalString(hashedKey); }
Code Sample 2:
public static String md5(String str) { StringBuffer buf = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] data = new byte[32]; md.update(str.getBytes(md5Encoding), 0, str.length()); data = md.digest(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while (two_halfs++ < 1); } } catch (Exception e) { errorLog("{Malgn.md5} " + e.getMessage()); } return buf.toString(); }
|
11
|
Code Sample 1:
public static void copyFile(File sourceFile, String toDir, boolean create, boolean overwrite) throws FileNotFoundException, IOException { FileInputStream source = null; FileOutputStream destination = null; byte[] buffer; int bytes_read; File toFile = new File(toDir); if (create && !toFile.exists()) toFile.mkdirs(); if (toFile.exists()) { File destFile = new File(toDir + "/" + sourceFile.getName()); try { if (!destFile.exists() || overwrite) { source = new FileInputStream(sourceFile); destination = new FileOutputStream(destFile); buffer = new byte[1024]; while (true) { bytes_read = source.read(buffer); if (bytes_read == -1) break; destination.write(buffer, 0, bytes_read); } } } catch (Exception exx) { exx.printStackTrace(); } finally { if (source != null) try { source.close(); } catch (IOException e) { } if (destination != null) try { destination.close(); } catch (IOException e) { } } } }
Code Sample 2:
public void merge(VMImage image, VMSnapShot another) throws VMException { if (path == null || another.getPath() == null) throw new VMException("EmuVMSnapShot is NULL!"); logging.debug(LOG_NAME, "merge images " + path + " and " + another.getPath()); File target = new File(path); File src = new File(another.getPath()); if (target.isDirectory() || src.isDirectory()) return; try { FileInputStream in = new FileInputStream(another.getPath()); FileChannel inChannel = in.getChannel(); FileOutputStream out = new FileOutputStream(path, true); FileChannel outChannel = out.getChannel(); outChannel.transferFrom(inChannel, 0, inChannel.size()); outChannel.close(); inChannel.close(); } catch (IOException e) { throw new VMException(e); } }
|
11
|
Code Sample 1:
public void encryptFile(String originalFile, String encryptedFile, String password) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(originalFile); out = new CipherOutputStream(new FileOutputStream(encryptedFile), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
Code Sample 2:
@Test public void testCascadeTraining() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("parity8.train"), new FileOutputStream(temp)); Fann fann = new FannShortcut(8, 1); Trainer trainer = new Trainer(fann); float desiredError = .00f; float mse = trainer.cascadeTrain(temp.getPath(), 30, 1, desiredError); assertTrue("" + mse, mse <= desiredError); }
|
11
|
Code Sample 1:
public void testWriteThreadsNoCompression() throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.loadProfiles(CommandLineProcessorFactory.PROFILE.DB, CommandLineProcessorFactory.PROFILE.REST_CLIENT, CommandLineProcessorFactory.PROFILE.COLLECTOR); final LocalLogFileWriter writer = (LocalLogFileWriter) bootstrap.getBean(LogFileWriter.class); writer.init(); writer.setCompressionCodec(null); File fileInput = new File(baseDir, "testWriteOneFile/input"); fileInput.mkdirs(); File fileOutput = new File(baseDir, "testWriteOneFile/output"); fileOutput.mkdirs(); writer.setBaseDir(fileOutput); int fileCount = 100; int lineCount = 100; File[] inputFiles = createInput(fileInput, fileCount, lineCount); ExecutorService exec = Executors.newFixedThreadPool(fileCount); final CountDownLatch latch = new CountDownLatch(fileCount); for (int i = 0; i < fileCount; i++) { final File file = inputFiles[i]; final int count = i; exec.submit(new Callable<Boolean>() { @Override public Boolean call() throws Exception { FileStatus.FileTrackingStatus status = FileStatus.FileTrackingStatus.newBuilder().setFileDate(System.currentTimeMillis()).setDate(System.currentTimeMillis()).setAgentName("agent1").setFileName(file.getName()).setFileSize(file.length()).setLogType("type1").build(); BufferedReader reader = new BufferedReader(new FileReader(file)); try { String line = null; while ((line = reader.readLine()) != null) { writer.write(status, new ByteArrayInputStream((line + "\n").getBytes())); } } finally { IOUtils.closeQuietly(reader); } LOG.info("Thread[" + count + "] completed "); latch.countDown(); return true; } }); } latch.await(); exec.shutdown(); LOG.info("Shutdown thread service"); writer.close(); File[] outputFiles = fileOutput.listFiles(); assertNotNull(outputFiles); File testCombinedInput = new File(baseDir, "combinedInfile.txt"); testCombinedInput.createNewFile(); FileOutputStream testCombinedInputOutStream = new FileOutputStream(testCombinedInput); try { for (File file : inputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedInputOutStream); } } finally { testCombinedInputOutStream.close(); } File testCombinedOutput = new File(baseDir, "combinedOutfile.txt"); testCombinedOutput.createNewFile(); FileOutputStream testCombinedOutOutStream = new FileOutputStream(testCombinedOutput); try { System.out.println("----------------- " + testCombinedOutput.getAbsolutePath()); for (File file : outputFiles) { FileInputStream f1In = new FileInputStream(file); IOUtils.copy(f1In, testCombinedOutOutStream); } } finally { testCombinedOutOutStream.close(); } FileUtils.contentEquals(testCombinedInput, testCombinedOutput); }
Code Sample 2:
public void testCreate() throws Exception { File f = File.createTempFile("DiskCacheItemTest", "tmp"); f.deleteOnExit(); try { DiskCacheItem i = new DiskCacheItem(f); i.setLastModified(200005L); i.setTranslationCount(11); i.setEncoding("GB2312"); i.setHeader(new ResponseHeaderImpl("Test2", new String[] { "Value3", "Value4" })); i.setHeader(new ResponseHeaderImpl("Test1", new String[] { "Value1", "Value2" })); byte[] chineseText = new byte[] { -42, -48, -46, -30, 87, 101, 98, 46, 99, 111, 109, 32, -54, -57, -46, -69, -72, -10, -61, -26, -49, -14, -42, -48, -50, -60, -45, -61, -69, -89, -95, -94, -67, -23, -55, -36, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -42, -48, -50, -60, -51, -8, -43, -66, -93, -84, -54, -57, -46, -69, -68, -36, -51, -88, -49, -14, -74, -85, -73, -67, -75, -60, -51, -8, -62, -25, -57, -59, -63, -70, -93, -84, -53, -4, -75, -60, -60, -65, -75, -60, -44, -38, -45, -38, -80, -17, -42, -6, -78, -69, -74, -49, -73, -94, -43, -71, -41, -77, -76, -13, -75, -60, -58, -13, -46, -75, -68, -28, -67, -8, -48, -48, -49, -32, -69, -91, -63, -86, -49, -75, -67, -45, -76, -91, -95, -93, -50, -46, -61, -57, -49, -32, -48, -59, -93, -84, -42, -48, -50, -60, -45, -61, -69, -89, -67, -85, -69, -31, -51, -88, -71, -3, -79, -66, -51, -8, -43, -66, -93, -84, -43, -46, -75, -67, -45, -48, -71, -40, -46, -47, -45, -21, -42, -48, -71, -6, -58, -13, -46, -75, -67, -88, -63, -94, -70, -49, -41, -9, -67, -69, -51, -7, -71, -40, -49, -75, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -93, -84, -69, -14, -45, -48, -46, -30, -45, -21, -42, -48, -71, -6, 32, -58, -13, -46, -75, -67, -8, -48, -48, -70, -49, -41, -9, -67, -69, -51, -7, -75, -60, -46, -30, -76, -13, -64, -5, -58, -13, -46, -75, -75, -60, -45, -48, -45, -61, -48, -59, -49, -94, -41, -54, -63, -49, -95, -93 }; { InputStream input = new ByteArrayInputStream(chineseText); try { i.setContentAsStream(input); } finally { input.close(); } } assertEquals("GB2312", i.getEncoding()); assertEquals(200005L, i.getLastModified()); assertEquals(11, i.getTranslationCount()); assertFalse(i.isCached()); i.updateAfterAllContentUpdated(null, null); { assertEquals(3, i.getHeaders().size()); int ii = 0; for (ResponseHeader h : i.getHeaders()) { ii++; if (ii == 1) { assertEquals("Content-Length", h.getName()); assertEquals("[279]", Arrays.toString(h.getValues())); } else if (ii == 2) { assertEquals("Test1", h.getName()); assertEquals("[Value1, Value2]", Arrays.toString(h.getValues())); } else if (ii == 3) { assertEquals("Test2", h.getName()); assertEquals("[Value3, Value4]", Arrays.toString(h.getValues())); } } } { FileInputStream input = new FileInputStream(f); StringWriter w = new StringWriter(); try { IOUtils.copy(input, w, "GB2312"); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(w); } assertEquals(new String(chineseText, "GB2312"), w.toString()); } { FileInputStream input = new FileInputStream(f); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } assertTrue(Arrays.equals(chineseText, output.toByteArray())); } } finally { f.delete(); } }
|
00
|
Code Sample 1:
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int remainingWorkUnits = 10; monitor.beginTask("New Modulo Project Creation", remainingWorkUnits); IWorkspace ws = ResourcesPlugin.getWorkspace(); newProject = fMainPage.getProjectHandle(); IProjectDescription description = ws.newProjectDescription(newProject.getName()); String[] natures = { JavaCore.NATURE_ID, ModuloLauncherPlugin.NATURE_ID }; description.setNatureIds(natures); ICommand command = description.newCommand(); command.setBuilderName(JavaCore.BUILDER_ID); ICommand[] commands = { command }; description.setBuildSpec(commands); IJavaProject jproject = JavaCore.create(newProject); ModuloProject modProj = new ModuloProject(); modProj.setJavaProject(jproject); try { newProject.create(description, new SubProgressMonitor(monitor, 1)); newProject.open(new SubProgressMonitor(monitor, 1)); IFolder srcFolder = newProject.getFolder("src"); IFolder javaFolder = srcFolder.getFolder("java"); IFolder buildFolder = newProject.getFolder("build"); IFolder classesFolder = buildFolder.getFolder("classes"); modProj.createFolder(srcFolder); modProj.createFolder(javaFolder); modProj.createFolder(buildFolder); modProj.createFolder(classesFolder); IPath buildPath = newProject.getFolder("build/classes").getFullPath(); jproject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(newProject.getFolder("src/java").getFullPath()), JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)), JavaCore.newContainerEntry(new Path(ModuloClasspathContainer.CONTAINER_ID)) }; jproject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); ModuleDefinition definition = new ModuleDefinition(); definition.setId(fModuloPage.getPackageName()); definition.setVersion(new VersionNumber(1, 0, 0)); definition.setMetaName(fModuloPage.getModuleName()); definition.setMetaDescription("The " + fModuloPage.getModuleName() + " Module."); definition.setModuleClassName(fModuloPage.getPackageName() + "." + fModuloPage.getModuleClassName()); if (fModuloPage.isConfigSelectioned()) definition.setConfigurationClassName(fModuloPage.getPackageName() + "." + fModuloPage.getConfigClassName()); if (fModuloPage.isStatSelectioned()) definition.setStatisticsClassName(fModuloPage.getPackageName() + "." + fModuloPage.getStatClassName()); modProj.setDefinition(definition); modProj.createPackage(); modProj.createModuleXML(); modProj.createMainClass(); if (fModuloPage.isConfigSelectioned()) modProj.createConfigClass(); if (fModuloPage.isStatSelectioned()) modProj.createStatClass(); modProj.createModuleProperties(); modProj.createMessagesProperties(); IFolder binFolder = newProject.getFolder("bin"); binFolder.delete(true, new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { e.printStackTrace(); } finally { monitor.done(); } }
Code Sample 2:
public static void saveChangeLink(URL url, OutputStream os) { try { BufferedInputStream is = new BufferedInputStream(url.openStream()); int i; while ((i = is.read()) != -1) if ((char) i == '<') { String s = readTag(is); String s1 = convertTag(url, s); os.write(s1.getBytes()); } else { os.write((byte) i); } } catch (Exception _ex) { } }
|
11
|
Code Sample 1:
private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } }
Code Sample 2:
private static final void copyFile(File srcFile, File destDir, byte[] buffer) { try { File destFile = new File(destDir, srcFile.getName()); InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); int bytesRead; while ((bytesRead = in.read(buffer)) != -1) out.write(buffer, 0, bytesRead); in.close(); out.close(); } catch (IOException ioe) { System.err.println("Couldn't copy file '" + srcFile + "' to directory '" + destDir + "'"); } }
|
11
|
Code Sample 1:
public static Properties parse() { try { String userHome = System.getProperty("user.home"); File dsigFolder = new File(userHome, ".dsig"); if (!dsigFolder.exists() && !dsigFolder.mkdir()) { throw new IOException("Could not create .dsig folder in user home directory"); } File settingsFile = new File(dsigFolder, "settings.properties"); if (!settingsFile.exists()) { InputStream is = UserHomeSettingsParser.class.getResourceAsStream("/defaultSettings.properties"); if (is != null) { IOUtils.copy(is, new FileOutputStream(settingsFile)); } } if (settingsFile.exists()) { Properties p = new Properties(); FileInputStream fis = new FileInputStream(settingsFile); p.load(fis); IOUtils.closeQuietly(fis); return p; } } catch (IOException e) { logger.warn("Error while initialize settings", e); } return null; }
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:
public static boolean copy(File source, File dest) { 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); if (in != null) in.close(); if (out != null) out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
Code Sample 2:
public void compressImage(InputStream input, OutputStream output, DjatokaEncodeParam params) throws DjatokaException { if (params == null) params = new DjatokaEncodeParam(); File inputFile = null; try { inputFile = File.createTempFile("tmp", ".tif"); IOUtils.copyStream(input, new FileOutputStream(inputFile)); if (params.getLevels() == 0) { ImageRecord dim = ImageRecordUtils.getImageDimensions(inputFile.getAbsolutePath()); params.setLevels(ImageProcessingUtils.getLevelCount(dim.getWidth(), dim.getHeight())); dim = null; } } catch (IOException e1) { logger.error("Unexpected file format; expecting uncompressed TIFF", e1); throw new DjatokaException("Unexpected file format; expecting uncompressed TIFF"); } String out = STDOUT; File winOut = null; if (isWindows) { try { winOut = File.createTempFile("pipe_", ".jp2"); } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } out = winOut.getAbsolutePath(); } String command = getKduCompressCommand(inputFile.getAbsolutePath(), out, params); logger.debug("compressCommand: " + command); Runtime rt = Runtime.getRuntime(); try { final Process process = rt.exec(command, envParams, new File(env)); if (out.equals(STDOUT)) { IOUtils.copyStream(process.getInputStream(), output); } else if (isWindows) { FileInputStream fis = new FileInputStream(out); IOUtils.copyStream(fis, output); fis.close(); } process.waitFor(); if (process != null) { String errorCheck = null; try { errorCheck = new String(IOUtils.getByteArray(process.getErrorStream())); } catch (Exception e1) { logger.error(e1, e1); } process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); if (errorCheck != null) throw new DjatokaException(errorCheck); } } catch (IOException e) { logger.error(e, e); throw new DjatokaException(e); } catch (InterruptedException e) { logger.error(e, e); throw new DjatokaException(e); } if (inputFile != null) inputFile.delete(); if (winOut != null) winOut.delete(); }
|
11
|
Code Sample 1:
public void fileCopy2(File inFile, File outFile) throws Exception { try { FileChannel srcChannel = new FileInputStream(inFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { throw new Exception("Could not copy file: " + inFile.getName()); } }
Code Sample 2:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] path = StringUtils.split(request.getRequestURI(), "/"); String file = path[path.length - 1]; File f = new File(pathToImages + "/" + file); response.setContentType(getServletContext().getMimeType(f.getName())); FileInputStream fis = new FileInputStream(f); IOUtils.copy(fis, response.getOutputStream()); fis.close(); }
|
11
|
Code Sample 1:
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); } } }
Code Sample 2:
public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
|
00
|
Code Sample 1:
public void saveProjectFile(File aFile) { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); File destDir = new File(theProjectsDirectory, sdf.format(Calendar.getInstance().getTime())); if (destDir.mkdirs()) { File outFile = new File(destDir, "project.xml"); try { FileChannel sourceChannel = new FileInputStream(aFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(outFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException e) { e.printStackTrace(); } finally { aFile.delete(); } } }
Code Sample 2:
public static String getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); }
|
00
|
Code Sample 1:
@Override public void run() { try { for (int r = 0; r < this.requestCount; r++) { HttpGet httpget = new HttpGet("/"); HttpResponse response = this.httpclient.execute(this.target, httpget, this.context); this.count++; ManagedClientConnection conn = (ManagedClientConnection) this.context.getAttribute(ExecutionContext.HTTP_CONNECTION); this.context.setAttribute("r" + r, conn.getState()); HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } } } catch (Exception ex) { this.exception = ex; } }
Code Sample 2:
public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } }
|
00
|
Code Sample 1:
public InputStream getResourceStream(String resource) { try { URL url = getClass().getResource(resource); System.out.println("URL: " + url); System.out.println("Read ROM " + resource); if (url == null) url = new URL(codebase + resource); return url.openConnection().getInputStream(); } catch (Exception e) { e.printStackTrace(); } return null; }
Code Sample 2:
private RemoteObject createRemoteObject(final VideoEntry videoEntry, final RemoteContainer container) throws RemoteException { MessageDigest instance; try { instance = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RemoteException(StatusCreator.newStatus("Error creating MD5", e)); } StringWriter sw = new StringWriter(); YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup(); if (mediaGroup != null) { if (mediaGroup.getDescription() != null) { sw.append(mediaGroup.getDescription().getPlainTextContent()); } List<MediaCategory> keywordsGroup = mediaGroup.getCategories(); StringBuilder sb = new StringBuilder(); if (keywordsGroup != null) { for (MediaCategory mediaCategory : keywordsGroup) { sb.append(mediaCategory.getContent()); } } } instance.update(sw.toString().getBytes()); RemoteObject remoteVideo = InfomngmntFactory.eINSTANCE.createRemoteObject(); remoteVideo.setHash(asHex(instance.digest())); remoteVideo.setId(SiteInspector.getId(videoEntry.getHtmlLink().getHref())); remoteVideo.setName(videoEntry.getTitle().getPlainText()); remoteVideo.setRepositoryTypeObjectId(KEY_VIDEO); remoteVideo.setWrappedObject(videoEntry); setInternalUrl(remoteVideo, container); return remoteVideo; }
|
11
|
Code Sample 1:
private String calculateHash(String s) { if (s == null) { return null; } MessageDigest messageDigest; try { messageDigest = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { logger.error("Could not find a message digest algorithm."); return null; } messageDigest.update(s.getBytes()); byte[] hash = messageDigest.digest(); StringBuilder sb = new StringBuilder(); for (byte b : hash) { sb.append(String.format("%02x", b)); } return sb.toString(); }
Code Sample 2:
public void insertQuotation(final String sText, final Source aSource) throws ConfigHandlerError, com.sun.star.uno.Exception { final XTextDocument xTextDocument = (XTextDocument) this.docController.getXInterface(XTextDocument.class, this.docController.getXFrame().getController().getModel()); final XMultiServiceFactory xMultiServiceFactory = (XMultiServiceFactory) this.docController.getXInterface(XMultiServiceFactory.class, xTextDocument); final XText xText = xTextDocument.getText(); final XTextViewCursor xTextViewCursor = ((XTextViewCursorSupplier) this.docController.getXInterface(XTextViewCursorSupplier.class, this.docController.getXFrame().getController())).getViewCursor(); final XTextRange xTextRange = xTextViewCursor.getStart(); if (aSource.getSourceType() == SourceType.QUOTE || aSource.getSourceType() == SourceType.WEBQUOTE || aSource.getSourceType() == SourceType.WEBQUOTE) { final XPropertySet xQuoteProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xTextViewCursor); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String("Quotations")); } xQuoteProps.setPropertyValue("CharStyleName", new String("Citation")); final Object aBookmark = xMultiServiceFactory.createInstance("com.sun.star.text.Bookmark"); this.sourceUtils.setNameToObject(aBookmark, this.docController.getLanguageController().__("Quote: ") + aSource.getShortinfo()); final XTextContent xTextContent = (XTextContent) this.docController.getXInterface(XTextContent.class, aBookmark); xText.insertTextContent(xTextRange, xTextContent, false); this.sourceUtils.insertBibliographyEntry(xMultiServiceFactory, xTextRange, aSource, sText); if (this.docController.getTemplateController().isIndentation()) { xText.insertControlCharacter(xTextViewCursor, ControlCharacter.PARAGRAPH_BREAK, false); xQuoteProps.setPropertyValue("ParaStyleName", new String(this.docController.getLanguageController().__("Default"))); } xQuoteProps.setPropertyValue("CharStyleName", new String(this.docController.getLanguageController().__("Default"))); } else if (aSource.getSourceType() == SourceType.IMAGE || aSource.getSourceType() == SourceType.TABLE) { xText.insertControlCharacter(xTextRange, ControlCharacter.PARAGRAPH_BREAK, false); final XTextFrame xFrame = this.sourceUtils.getTextFrame(aSource.getShortinfo(), xMultiServiceFactory); xText.insertTextContent(xTextRange, xFrame, false); final XText xFrameText = xFrame.getText(); final XTextCursor xFrameCursor = xFrameText.createTextCursor(); final Size aNewSize = new Size(); XPropertySet xBaseFrameProps = null; final Size aPageTextAreaSize = this.sourceUtils.getPageTextAreaSize(xTextDocument, xTextViewCursor); if (aSource.getSourceType() == SourceType.IMAGE) { try { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption illustration: ") + aSource.getShortinfo()); final XNameContainer xBitmapContainer = (XNameContainer) this.docController.getXInterface(XNameContainer.class, xMultiServiceFactory.createInstance("com.sun.star.drawing.BitmapTable")); final XTextContent xImage = (XTextContent) this.docController.getXInterface(XTextContent.class, xMultiServiceFactory.createInstance("com.sun.star.text.TextGraphicObject")); this.sourceUtils.setNameToObject(xImage, this.docController.getLanguageController().__("Illustration: ") + aSource.getShortinfo()); final String graphicURL = this.docController.getPathUtils().getFileURLFromSystemPath(((Image) aSource).getFile().getPath(), ((Image) aSource).getFile().getPath()); xBaseFrameProps = (XPropertySet) this.docController.getXInterface(XPropertySet.class, xImage); xBaseFrameProps.setPropertyValue("AnchorType", com.sun.star.text.TextContentAnchorType.AT_PARAGRAPH); xBaseFrameProps.setPropertyValue("GraphicURL", graphicURL); final MessageDigest md = MessageDigest.getInstance("MD5"); md.update(graphicURL.getBytes(), 0, graphicURL.length()); final String internalName = new BigInteger(1, md.digest()).toString(16); xBitmapContainer.insertByName(internalName, graphicURL); final String internalURL = (String) (xBitmapContainer.getByName(internalName)); xBaseFrameProps.setPropertyValue("GraphicURL", internalURL); float imageRatio = (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height / (float) this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width; final Size aUsedAreaSize = new Size(this.sourceUtils.getImageSize(((Image) aSource).getFile()).Width * 26, this.sourceUtils.getImageSize(((Image) aSource).getFile()).Height * 26); if (aUsedAreaSize.Width >= aPageTextAreaSize.Width) { aNewSize.Width = aPageTextAreaSize.Width; aNewSize.Height = (int) (aPageTextAreaSize.Width * imageRatio); } else { aNewSize.Width = aUsedAreaSize.Width; aNewSize.Height = aUsedAreaSize.Height; } xFrameText.insertTextContent(xFrameCursor, xImage, false); xBitmapContainer.removeByName(internalName); } catch (final NoSuchAlgorithmException e) { new ASTError(e).severe(); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Illustration"), xMultiServiceFactory); } else if (aSource.getSourceType() == SourceType.TABLE) { this.sourceUtils.setNameToObject(xFrame, this.docController.getLanguageController().__("Caption table: ") + aSource.getShortinfo()); xBaseFrameProps = this.sourceUtils.createTextEmbeddedObjectCalc(xMultiServiceFactory); this.sourceUtils.setNameToObject(xBaseFrameProps, this.docController.getLanguageController().__("Table: ") + aSource.getShortinfo()); xFrameText.insertTextContent(xFrameCursor, (XTextContent) this.docController.getXInterface(XTextContent.class, xBaseFrameProps), false); final XEmbeddedObjectSupplier2 xEmbeddedObjectSupplier = (XEmbeddedObjectSupplier2) this.docController.getXInterface(XEmbeddedObjectSupplier2.class, xBaseFrameProps); final XEmbeddedObject xEmbeddedObject = xEmbeddedObjectSupplier.getExtendedControlOverEmbeddedObject(); long nAspect = xEmbeddedObjectSupplier.getAspect(); final Size aVisualAreaSize = xEmbeddedObject.getVisualAreaSize(nAspect); final XComponent xComponent = xEmbeddedObjectSupplier.getEmbeddedObject(); XSpreadsheets xSpreadsheets = ((XSpreadsheetDocument) this.docController.getXInterface(XSpreadsheetDocument.class, xComponent)).getSheets(); final XIndexAccess xIndexAccess = (XIndexAccess) this.docController.getXInterface(XIndexAccess.class, xSpreadsheets); final XSpreadsheet xSpreadsheet = (XSpreadsheet) this.docController.getXInterface(XSpreadsheet.class, xIndexAccess.getByIndex(0)); final XSheetLinkable xSheetLinkable = (XSheetLinkable) this.docController.getXInterface(XSheetLinkable.class, xSpreadsheet); xSheetLinkable.link(this.docController.getPathUtils().getFileURLFromSystemPath(((Table) aSource).getFile().getPath(), ((Table) aSource).getFile().getPath()), "", "", "", com.sun.star.sheet.SheetLinkMode.NORMAL); final CellRangeAddress aUsedArea = this.sourceUtils.getUsedArea(xSpreadsheet); final Size aUsedAreaSize = this.sourceUtils.calcCellRangeSize(xSpreadsheets, aUsedArea); if ((aUsedAreaSize.Width != aVisualAreaSize.Width) || (aUsedAreaSize.Height != aVisualAreaSize.Height)) { aNewSize.Height = (aUsedAreaSize.Height > aPageTextAreaSize.Height) ? aPageTextAreaSize.Height : aUsedAreaSize.Height; aNewSize.Width = (aUsedAreaSize.Width > aPageTextAreaSize.Width) ? aPageTextAreaSize.Width : aUsedAreaSize.Width; xEmbeddedObject.setVisualAreaSize(nAspect, aNewSize); } this.sourceUtils.insertCaption(xFrame, aSource, this.docController.getLanguageController().__("Table"), xMultiServiceFactory); } xBaseFrameProps.setPropertyValue("Width", aNewSize.Width); xBaseFrameProps.setPropertyValue("Height", aNewSize.Height); final XShape xShape = (XShape) this.docController.getXInterface(XShape.class, xFrame); xShape.setSize(aNewSize); } final XTextFieldsSupplier xTextFieldsSupplier = (XTextFieldsSupplier) this.docController.getXInterface(XTextFieldsSupplier.class, xMultiServiceFactory); final XRefreshable xRefreshable = (XRefreshable) this.docController.getXInterface(XRefreshable.class, xTextFieldsSupplier.getTextFields()); xRefreshable.refresh(); }
|
00
|
Code Sample 1:
private <T> Collection<T> loadProviders(final Class<T> providerClass) throws ModelException { try { final String providerNamePrefix = providerClass.getName() + "."; final Map<String, T> providers = new TreeMap<String, T>(new Comparator<String>() { public int compare(final String key1, final String key2) { return key1.compareTo(key2); } }); final File platformProviders = new File(this.getPlatformProviderLocation()); if (platformProviders.exists()) { if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", platformProviders.getAbsolutePath()), null); } InputStream in = null; boolean suppressExceptionOnClose = true; final java.util.Properties p = new java.util.Properties(); try { in = new FileInputStream(platformProviders); p.load(in); suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw e; } } } for (Map.Entry<Object, Object> e : p.entrySet()) { if (e.getKey().toString().startsWith(providerNamePrefix)) { final String configuration = e.getValue().toString(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", platformProviders.getAbsolutePath(), providerClass.getName(), configuration), null); } providers.put(e.getKey().toString(), this.createProviderObject(providerClass, configuration, platformProviders.toURI().toURL())); } } } final Enumeration<URL> classpathProviders = this.findResources(this.getProviderLocation() + '/' + providerClass.getName()); int count = 0; final long t0 = System.currentTimeMillis(); while (classpathProviders.hasMoreElements()) { count++; final URL url = classpathProviders.nextElement(); if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("processing", url.toExternalForm()), null); } BufferedReader reader = null; boolean suppressExceptionOnClose = true; try { reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); String line = null; while ((line = reader.readLine()) != null) { if (line.contains("#")) { continue; } if (this.isLoggable(Level.FINEST)) { this.log(Level.FINEST, getMessage("providerInfo", url.toExternalForm(), providerClass.getName(), line), null); } providers.put(providerNamePrefix + providers.size(), this.createProviderObject(providerClass, line, url)); } suppressExceptionOnClose = false; } finally { try { if (reader != null) { reader.close(); } } catch (final IOException e) { if (suppressExceptionOnClose) { this.log(Level.SEVERE, getMessage(e), e); } else { throw new ModelException(getMessage(e), e); } } } } if (this.isLoggable(Level.FINE)) { this.log(Level.FINE, getMessage("contextReport", count, this.getProviderLocation() + '/' + providerClass.getName(), Long.valueOf(System.currentTimeMillis() - t0)), null); } return providers.values(); } catch (final IOException e) { throw new ModelException(getMessage(e), e); } }
Code Sample 2:
protected static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection c = url.openConnection(); c.setConnectTimeout(2000); IOUtils.copy(c.getInputStream(), output); return output.toString(); }
|
11
|
Code Sample 1:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String pathInfo = req.getPathInfo(); String pluginPathInfo = pathInfo.substring(prefix.length()); String gwtPathInfo = pluginPathInfo.substring(pluginKey.length() + 1); String clPath = CLASSPATH_PREFIX + gwtPathInfo; InputStream input = cl.getResourceAsStream(clPath); if (input != null) { try { OutputStream output = resp.getOutputStream(); IOUtils.copy(input, output); } finally { input.close(); } } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND); } }
Code Sample 2:
public void createNewFile(String filePath, InputStream in) throws IOException { FileOutputStream out = null; try { File file = newFileRef(filePath); FileHelper.createNewFile(file, true); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
|
00
|
Code Sample 1:
private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
Code Sample 2:
private HttpURLConnection getConnection(String url, int connTimeout, int readTimeout) throws IOException { HttpURLConnection con = null; con = (HttpURLConnection) new URL(url).openConnection(); if (connTimeout > 0) { if (!isJDK14orEarlier) { con.setConnectTimeout(connTimeout * 1000); } else { System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(connTimeout * 1000)); } } if (readTimeout > 0) { if (!isJDK14orEarlier) { con.setReadTimeout(readTimeout * 1000); } else { System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(readTimeout * 1000)); } } con.setInstanceFollowRedirects(false); return con; }
|
11
|
Code Sample 1:
public void writeConfigurationFile() throws IOException, ComponentException { SystemConfig config = parent.getParentSystem().getConfiguration(); File original = config.getLocation(); File backup = new File(original.getParentFile(), original.getName() + "." + System.currentTimeMillis()); FileInputStream in = new FileInputStream(original); FileOutputStream out = new FileOutputStream(backup); byte[] buffer = new byte[2048]; try { int bytesread = 0; while ((bytesread = in.read(buffer)) > 0) { out.write(buffer, 0, bytesread); } } catch (IOException e) { logger.warn("Failed to copy backup of configuration file"); throw e; } finally { in.close(); out.close(); } FileWriter replace = new FileWriter(original); replace.write(config.toFileFormat()); replace.close(); logger.info("Re-wrote configuration file " + original.getPath()); }
Code Sample 2:
public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static String encryption(String oldPass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } md.update(oldPass.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) { i += 256; } if (i < 16) { buf.append("0"); } buf.append(Integer.toHexString(i)); } String pass32 = buf.toString(); return pass32; }
Code Sample 2:
public boolean copy(String file, String path) { try { File file_in = new File(file); String tmp1, tmp2; tmp1 = file; tmp2 = path; while (tmp2.contains("\\")) { tmp2 = tmp2.substring(tmp2.indexOf("\\") + 1); tmp1 = tmp1.substring(tmp1.indexOf("\\") + 1); } tmp1 = file.substring(0, file.length() - tmp1.length()) + tmp2 + tmp1.substring(tmp1.indexOf("\\")); File file_out = new File(tmp1); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } }
|
11
|
Code Sample 1:
public String getMessageofTheDay(String id) { StringBuffer mod = new StringBuffer(); int serverModId = 0; int clientModId = 0; BufferedReader input = null; try { URL url = new URL(FlyShareApp.BASE_WEBSITE_URL + "/mod.txt"); input = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; inputLine = input.readLine(); try { clientModId = Integer.parseInt(id); serverModId = Integer.parseInt(inputLine); } catch (NumberFormatException e) { } if (clientModId < serverModId || clientModId == 0) { mod.append(serverModId); mod.append('|'); while ((inputLine = input.readLine()) != null) mod.append(inputLine); } } catch (MalformedURLException e) { } catch (IOException e) { } finally { try { input.close(); } catch (Exception e) { } } return mod.toString(); }
Code Sample 2:
public static String filtraDoc(HttpServletRequest request, String resource, Repository rep, String template) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader br = null; int sec = 0; try { URL url = rep.getResource(request, resource); if (url == null) { return "Documento " + rep.dir + "/" + resource + " no encontrado"; } br = new BufferedReader(new InputStreamReader(url.openStream(), rep.encoding)); String line = br.readLine(); while (line != null) { int pos = line.indexOf("KAttach("); if (pos > -1) { sb.append(attach(request, ++sec, line, pos, template)); } else { line = line.replaceAll("%20", "-"); sb.append(new String(line.getBytes(rep.encoding), Config.getMng().getEncoding())).append("\n"); } line = br.readLine(); } } finally { if (br != null) br.close(); } return sb.toString(); }
|
11
|
Code Sample 1:
private static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
Code Sample 2:
public static void copiaAnexos(String from, String to, AnexoTO[] anexoTO) { FileChannel in = null, out = null; for (int i = 0; i < anexoTO.length; i++) { try { in = new FileInputStream(new File((uploadDiretorio.concat(from)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); out = new FileOutputStream(new File((uploadDiretorio.concat(to)).concat(File.separator + anexoTO[i].getNome()))).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
|
00
|
Code Sample 1:
private long getNextHighValue() throws Exception { Connection con = null; PreparedStatement psGetHighValue = null; PreparedStatement psUpdateHighValue = null; ResultSet rs = null; long high = -1L; int isolation = -1; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { con = dbo.getConnection(); psGetHighValue = con.prepareStatement(strGetHighValue); psGetHighValue.setString(1, this.name); for (rs = psGetHighValue.executeQuery(); rs.next(); ) { high = rs.getLong("high"); } psUpdateHighValue = con.prepareStatement(strUpdateHighValue); psUpdateHighValue.setLong(1, high + 1L); psUpdateHighValue.setString(2, this.name); psUpdateHighValue.executeUpdate(); } catch (SQLException e) { if (con != null) { con.rollback(); } throw e; } finally { if (psUpdateHighValue != null) { psUpdateHighValue.close(); } close(dbo, psGetHighValue, rs); } return high; }
Code Sample 2:
public static String genetateSHA256(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte[] passWd = md.digest(); String hex = toHex(passWd); return hex; }
|
00
|
Code Sample 1:
public static void copyAll(URL url, StringBuilder ret) { Reader in = null; try { in = new InputStreamReader(new BufferedInputStream(url.openStream())); copyAll(in, ret); } catch (IOException e) { throw new RuntimeException(e); } finally { close(in); } }
Code Sample 2:
protected void initializeGraphicalViewer() { getGraphicalViewer().setContents(loadModel()); getGraphicalViewer().addDropTargetListener(createTransferDropTargetListener()); getGraphicalViewer().addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection().isEmpty()) { return; } loadProperties(((StructuredSelection) event.getSelection()).getFirstElement()); } }); }
|
11
|
Code Sample 1:
public Writer createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; 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(); return new OutputStreamWriter(zos, "UTF-8"); }
Code Sample 2:
private static AtomContainer askForMovieSettings() throws IOException, QTException { final InputStream inputStream = QuickTimeFormatGenerator.class.getResourceAsStream(REFERENCE_MOVIE_RESOURCE); final ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1024 * 100); IOUtils.copy(inputStream, byteArray); final byte[] movieBytes = byteArray.toByteArray(); final QTHandle qtHandle = new QTHandle(movieBytes); final DataRef dataRef = new DataRef(qtHandle, StdQTConstants.kDataRefFileExtensionTag, ".mov"); final Movie movie = Movie.fromDataRef(dataRef, StdQTConstants.newMovieActive | StdQTConstants4.newMovieAsyncOK); final MovieExporter exporter = new MovieExporter(StdQTConstants.kQTFileTypeMovie); exporter.doUserDialog(movie, null, 0, movie.getDuration()); return exporter.getExportSettingsFromAtomContainer(); }
|
00
|
Code Sample 1:
private void copy(File in, File out) { log.info("Copying yam file from: " + in.getName() + " to: " + out.getName()); try { FileChannel ic = new FileInputStream(in).getChannel(); FileChannel oc = new FileOutputStream(out).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } catch (IOException ioe) { fail("Failed testing while copying modified file: " + ioe.getMessage()); } }
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; }
|
00
|
Code Sample 1:
public File addFile(File file, String suffix) throws IOException { if (file.exists() && file.isFile()) { File nf = File.createTempFile(prefix, "." + suffix, workdir); nf.delete(); if (!file.renameTo(nf)) { IOUtils.copy(file, nf); } synchronized (fileList) { fileList.add(nf); } if (log.isDebugEnabled()) { log.debug("Add file [" + file.getPath() + "] -> [" + nf.getPath() + "]"); } return nf; } return file; }
Code Sample 2:
public synchronized void readProject(URL url, boolean addMembers) throws IOException { _url = url; try { readProject(url.openStream(), addMembers); } catch (IOException e) { Argo.log.info("Couldn't open InputStream in ArgoParser.load(" + url + ") " + e); e.printStackTrace(); lastLoadMessage = e.toString(); throw e; } }
|
00
|
Code Sample 1:
public static final String enctrypt(String password) { MessageDigest md = null; byte[] byteHash = null; StringBuffer resultString = new StringBuffer(); try { md = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); throw new RuntimeException("NoSuchAlgorithmException SHA1"); } md.reset(); md.update(password.getBytes()); byteHash = md.digest(); for (int i = 0; i < byteHash.length; i++) { resultString.append(Integer.toHexString(0xFF & byteHash[i])); } return (resultString.toString()); }
Code Sample 2:
public void notifyTerminated(Writer r) { all_writers.remove(r); if (all_writers.isEmpty()) { all_terminated = true; Iterator iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); do { try { fc.stream.flush(); fc.stream.close(); } catch (IOException e) { } fc = fc.next; } while (fc != null); } iterator = open_files.iterator(); boolean all_ok = true; while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); logger.logComment("File chunk <" + fc.name + "> " + fc.start_byte + " " + fc.position + " " + fc.actual_file); boolean ok = true; while (fc.next != null) { ok = ok && (fc.start_byte + fc.actual_file.length()) == fc.next.start_byte; fc = fc.next; } if (ok) { logger.logComment("Received file <" + fc.name + "> is contiguous (and hopefully complete)"); } else { logger.logError("Received file <" + fc.name + "> is NOT contiguous"); all_ok = false; } } if (all_ok) { byte[] buffer = new byte[16384]; iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); try { if (fc.next != null) { FileOutputStream fos = new FileOutputStream(fc.actual_file, true); fc = fc.next; while (fc != null) { FileInputStream fis = new FileInputStream(fc.actual_file); int actually_read = fis.read(buffer); while (actually_read != -1) { fos.write(buffer, 0, actually_read); actually_read = fis.read(buffer); } fc.actual_file.delete(); fc = fc.next; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } fte.allWritersTerminated(); fte = null; } }
|
00
|
Code Sample 1:
private void btnOkActionPerformed(java.awt.event.ActionEvent evt) { try { int id = 0; String sql = "SELECT MAX(ID) as MAX_ID from CORE_USER_GROUPS"; PreparedStatement pStmt = Database.getMyConnection().prepareStatement(sql); ResultSet rs = pStmt.executeQuery(); if (rs.next()) { id = rs.getInt("MAX_ID") + 1; } else { id = 1; } Database.close(pStmt); sql = "INSERT INTO CORE_USER_GROUPS" + " (ID, GRP_NAME, GRP_DESC, DATE_INITIAL, DATE_FINAL, IND_STATUS)" + " VALUES (?, ?, ?, ?, ?, ?)"; pStmt = Database.getMyConnection().prepareStatement(sql); pStmt.setInt(1, id); pStmt.setString(2, txtGrpName.getText()); pStmt.setString(3, txtGrpDesc.getText()); pStmt.setDate(4, Utils.getTodaySql()); pStmt.setDate(5, Date.valueOf("9999-12-31")); pStmt.setString(6, "A"); pStmt.executeUpdate(); Database.getMyConnection().commit(); Database.close(pStmt); MessageBox.ok("New group added successfully", this); rs = getGroups(); tblGroups.setModel(new GroupsTableModel(rs)); Database.close(rs); } catch (SQLException e) { log.error("Failed with update operation \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } catch (IllegalArgumentException e) { log.error("Illegal argument for the DATE_FINAL \n" + e.getMessage()); MessageBox.ok("Failed to create the new group in the database", this); try { Database.getMyConnection().rollback(); } catch (Exception inner) { } ; } finally { txtGrpName.setEnabled(false); txtGrpDesc.setEnabled(false); btnOk.setEnabled(false); btnCancel.requestFocus(); } }
Code Sample 2:
public void format(File source, File target) { if (!source.exists()) { throw new IllegalArgumentException("Source '" + source + " doesn't exist"); } if (!source.isFile()) { throw new IllegalArgumentException("Source '" + source + " is not a file"); } target.mkdirs(); String fileExtension = source.getName().substring(source.getName().lastIndexOf(".") + 1); String _target = source.getName().replace(fileExtension, "html"); target = new File(target.getPath() + "/" + _target); try { Reader reader = new FileReader(source); Writer writer = new FileWriter(target); this.format(reader, writer); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
void write() throws IOException { if (!allowUnlimitedArgs && args != null && args.length > 1) throw new IllegalArgumentException("Only one argument allowed unless allowUnlimitedArgs is enabled"); String shebang = "#!" + interpretter; for (int i = 0; i < args.length; i++) { shebang += " " + args[i]; } shebang += '\n'; IOUtils.copy(new StringReader(shebang), outputStream); }
|
00
|
Code Sample 1:
public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new MyException(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
Code Sample 2:
public void testAutoCommit() throws Exception { Connection con = getConnectionOverrideProperties(new Properties()); try { Statement stmt = con.createStatement(); assertEquals(0, stmt.executeUpdate("create table #testAutoCommit (i int)")); con.setAutoCommit(false); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (0)")); con.setAutoCommit(false); con.rollback(); assertEquals(1, stmt.executeUpdate("insert into #testAutoCommit (i) values (1)")); con.setAutoCommit(true); con.setAutoCommit(false); con.rollback(); con.setAutoCommit(true); ResultSet rs = stmt.executeQuery("select i from #testAutoCommit"); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertFalse(rs.next()); rs.close(); stmt.close(); } finally { con.close(); } }
|
11
|
Code Sample 1:
public String getDataAsString(String url) throws RuntimeException { try { String responseBody = ""; URLConnection urlc; if (!url.toUpperCase().startsWith("HTTP://") && !url.toUpperCase().startsWith("HTTPS://")) { urlc = tryOpenConnection(url); } else { urlc = new URL(url).openConnection(); } urlc.setUseCaches(false); urlc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlc.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-GB; rv:1.9.1.9) Gecko/20100414 Iceweasel/3.5.9 (like Firefox/3.5.9)"); urlc.setRequestProperty("Accept-Encoding", "gzip"); InputStreamReader re = new InputStreamReader(urlc.getInputStream()); BufferedReader rd = new BufferedReader(re); String line = ""; while ((line = rd.readLine()) != null) { responseBody += line; responseBody += "\n"; line = null; } rd.close(); re.close(); return responseBody; } catch (Exception e) { throw new RuntimeException(e); } }
Code Sample 2:
public String downloadFromUrl(URL url) { BufferedReader dis; String content = ""; HttpURLConnection urlConn = null; try { urlConn = (HttpURLConnection) url.openConnection(); urlConn.setDoInput(true); urlConn.setUseCaches(false); urlConn.setAllowUserInteraction(false); dis = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line; while ((line = dis.readLine()) != null) { content = content.concat(line); content = content.concat("\n"); } } catch (MalformedURLException ex) { System.err.println(ex + " (downloadFromUrl)"); } catch (java.io.IOException iox) { System.out.println(iox + " (downloadFromUrl)"); } catch (Exception generic) { System.out.println(generic.toString() + " (downloadFromUrl)"); } finally { } return content; }
|
00
|
Code Sample 1:
public static String hash(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(text.getBytes()); byte[] digest = md.digest(); StringBuffer sb = new StringBuffer(digest.length * 2); for (int i = 0; i < digest.length; ++i) { byte b = digest[i]; int high = (b & 0xF0) >> 4; int low = b & 0xF; sb.append(DECIMAL_HEX[high]); sb.append(DECIMAL_HEX[low]); } return sb.toString(); } catch (NoSuchAlgorithmException e) { throw new NonBusinessException("Error hashing string", e); } }
Code Sample 2:
protected final void loadLogFile(String filename) throws IOException { cleanUp(true, false); InputStream is = null; OutputStream os = null; File f = File.createTempFile("log", null); try { is = getClass().getResourceAsStream(filename); Assert.isTrue(is != null, "File not found: " + filename); os = new FileOutputStream(f); IOUtils.copy(is, os); setLogFile(f); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
|
00
|
Code Sample 1:
public InputStream getResourceAsStream(String name) { if (debug >= 2) log("getResourceAsStream(" + name + ")"); InputStream stream = null; stream = findLoadedResource(name); if (stream != null) { if (debug >= 2) log(" --> Returning stream from cache"); return (stream); } if (delegate) { if (debug >= 3) log(" Delegating to parent classloader"); ClassLoader loader = parent; if (loader == null) loader = system; stream = loader.getResourceAsStream(name); if (stream != null) { if (debug >= 2) log(" --> Returning stream from parent"); return (stream); } } if (debug >= 3) log(" Searching local repositories"); URL url = findResource(name); if (url != null) { if (debug >= 2) log(" --> Returning stream from local"); try { return (url.openStream()); } catch (IOException e) { log("url.openStream(" + url.toString() + ")", e); return (null); } } if (!delegate) { if (debug >= 3) log(" Delegating to parent classloader"); ClassLoader loader = parent; if (loader == null) loader = system; stream = loader.getResourceAsStream(name); if (stream != null) { if (debug >= 2) log(" --> Returning stream from parent"); return (stream); } } if (debug >= 2) log(" --> Resource not found, returning null"); return (null); }
Code Sample 2:
@Override public void setOntology1Document(URL url1) throws IllegalArgumentException { if (url1 == null) throw new IllegalArgumentException("Input parameter URL for ontology 1 is null."); try { ont1 = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(url1.openStream()); } catch (IOException e) { throw new IllegalArgumentException("Cannot open stream for ontology 1 from given URL."); } catch (OWLOntologyCreationException e) { throw new IllegalArgumentException("Cannot load ontology 1 from given URL."); } }
|
00
|
Code Sample 1:
@Transient private String md5sum(String text) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(text.getBytes()); byte messageDigest[] = md.digest(); return bufferToHex(messageDigest, 0, messageDigest.length); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; }
Code Sample 2:
private void displayDiffResults() throws IOException { File outFile = File.createTempFile("diff", ".htm"); outFile.deleteOnExit(); FileOutputStream outStream = new FileOutputStream(outFile); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(outStream)); out.write("<html><head><title>LOC Differences</title>\n" + SCRIPT + "</head>\n" + "<body bgcolor='#ffffff'>\n" + "<div onMouseOver=\"window.defaultStatus='Metrics'\">\n"); if (addedTable.length() > 0) { out.write("<table border><tr><th>Files Added:</th>" + "<th>Add</th><th>Type</th></tr>"); out.write(addedTable.toString()); out.write("</table><br><br>"); } if (modifiedTable.length() > 0) { out.write("<table border><tr><th>Files Modified:</th>" + "<th>Base</th><th>Del</th><th>Mod</th><th>Add</th>" + "<th>Total</th><th>Type</th></tr>"); out.write(modifiedTable.toString()); out.write("</table><br><br>"); } if (deletedTable.length() > 0) { out.write("<table border><tr><th>Files Deleted:</th>" + "<th>Del</th><th>Type</th></tr>"); out.write(deletedTable.toString()); out.write("</table><br><br>"); } out.write("<table name=METRICS BORDER>\n"); if (modifiedTable.length() > 0 || deletedTable.length() > 0) { out.write("<tr><td>Base: </td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted: </td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified: </td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added: </td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed: </td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total: </td><td>"); out.write(Long.toString(total)); out.write("</td></tr>\n</table></div>"); redlinesOut.close(); out.flush(); InputStream redlines = new FileInputStream(redlinesTempFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = redlines.read(buffer)) != -1) outStream.write(buffer, 0, bytesRead); outStream.write("</BODY></HTML>".getBytes()); outStream.close(); Browser.launch(outFile.toURL().toString()); }
|
11
|
Code Sample 1:
private void copyFile(String inputPath, String basis, String filename) throws GLMRessourceFileException { try { FileChannel inChannel = new FileInputStream(new File(inputPath)).getChannel(); File target = new File(basis, filename); FileChannel outChannel = new FileOutputStream(target).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); inChannel.close(); outChannel.close(); } catch (Exception e) { throw new GLMRessourceFileException(7); } }
Code Sample 2:
private void backupFile(ZipOutputStream out, String base, String fn) throws IOException { String f = FileUtils.getAbsolutePath(fn); base = FileUtils.getAbsolutePath(base); if (!f.startsWith(base)) { Message.throwInternalError(f + " does not start with " + base); } f = f.substring(base.length()); f = correctFileName(f); out.putNextEntry(new ZipEntry(f)); InputStream in = FileUtils.openFileInputStream(fn); IOUtils.copyAndCloseInput(in, out); out.closeEntry(); }
|
00
|
Code Sample 1:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo = request.getPathInfo(); getLog().info("Process request " + pathInfo); if (null != pathInfo) { String pathId = getPathId(pathInfo); JobResources res = ContextUtil.getJobResource(pathId); if (null != res) { RequestType requType = getRequestType(request); ResultAccess access = new ResultAccess(res); Collection<Long> uIdColl = res.getUniqIds(); boolean isFiltered = false; { List<String> postSeqIds = getSeqList(request); if (!postSeqIds.isEmpty()) { isFiltered = true; uIdColl = access.loadIds(postSeqIds); } } try { if ((requType.equals(RequestType.FASTA)) || (requType.equals(RequestType.SWISSPROT))) { OutputStreamWriter out = null; out = new OutputStreamWriter(response.getOutputStream()); for (Long uid : uIdColl) { if (requType.equals(RequestType.FASTA)) { SwissProt sw = access.getSwissprotEntry(uid); if (null != sw) { PrintFactory.instance().print(ConvertFactory.instance().SwissProt2fasta(sw), out); } else { System.err.println("Not able to read Swissprot entry " + uid + " in project " + res.getBaseDir()); } } else if (requType.equals(RequestType.SWISSPROT)) { File swissFile = res.getSwissprotFile(uid); if (swissFile.exists()) { InputStream in = null; try { in = new FileInputStream(swissFile); IOUtils.copy(in, out); } catch (IOException e) { e.printStackTrace(); System.err.println("Problems with reading file to output stream " + swissFile); } finally { IOUtils.closeQuietly(in); } } else { System.err.println("Swissprot file does not exist: " + swissFile); } } } out.flush(); } else { if (uIdColl.size() <= 2) { isFiltered = false; uIdColl = res.getUniqIds(); } Tree tree = access.getTreeByUniquId(uIdColl); if (requType.equals(RequestType.TREE)) { response.getWriter().write(tree.toNewHampshireX()); } else if (requType.equals(RequestType.PNG)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); ImageMap map = ImageFactory.instance().createProteinCard(sp, tree, true, res); response.setContentType("image/png"); response.addHeader("Content-Disposition", "filename=ProteinCards.png"); ImageFactory.instance().printPNG(map.getImage(), response.getOutputStream()); response.getOutputStream().flush(); } else if (requType.equals(RequestType.HTML)) { List<SwissProt> sp = access.getSwissprotEntriesByUniquId(uIdColl); createHtml(res, access, tree, request, response, sp, isFiltered); } } } catch (Exception e) { e.printStackTrace(); getLog().error("Problem with Request: " + pathInfo + "; type " + requType, e); } } else { getLog().error("Resource is null: " + pathId + "; path " + pathInfo); } } else { getLog().error("PathInfo is null!!!"); } }
Code Sample 2:
public synchronized DASMetaData fillInDASMetaData(URL url) throws DASException { try { con = (HttpURLConnection) url.openConnection(); dasRespVersion = con.getHeaderField("X-DAS-Version"); dasSchema = con.getHeaderField("X-DAS-SchemaName"); dasSchemaVersion = con.getHeaderField("X-DAS-SchemaVersion"); String dasStatusString = con.getHeaderField("X-DAS-Status"); if (dasStatusString == null) { throw new DASException("Temporary DAS Error"); } if (dasStatusString.indexOf(" ") != -1) { dasStatusString = dasStatusString.substring(0, dasStatusString.indexOf(" ")); } dasStatus = Integer.parseInt(dasStatusString); if (dasStatus != 200) { throw new DASException("Command cannot be executed: Error was " + Integer.toString(dasStatus)); } } catch (IOException e) { throw new DASException("Cannot connect to data source"); } if (dasSchema != null && dasSchemaVersion != null) { headers.put("X-DAS-Version", dasRespVersion); headers.put("X-DAS-SchemaName", dasSchema); headers.put("X-DAS-SchemaVersion", dasSchemaVersion); dasVersion = Float.parseFloat(dasRespVersion.substring(dasRespVersion.indexOf("/") + 1, dasRespVersion.length())); theMetaData = new DASMetaDataImpl(dasVersion, Float.parseFloat(dasSchemaVersion), dasSchema); } else { dasVersion = Float.parseFloat(dasRespVersion.substring(dasRespVersion.indexOf("/") + 1, dasRespVersion.length())); headers.put("X-DAS-Version", dasRespVersion); theMetaData = new DASMetaDataImpl(dasVersion); } String lengthStr = con.getHeaderField("content-length"); if (lengthStr != null) headers.put("content-length", lengthStr); theMetaData.setDASHeaders(headers); return theMetaData; }
|
11
|
Code Sample 1:
private void trainDepParser(byte flag, JarArchiveOutputStream zout) throws Exception { AbstractDepParser parser = null; OneVsAllDecoder decoder = null; if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("\n* Save lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, s_featureXml); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, s_featureXml); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) { System.out.println("\n* Print training instances"); System.out.println("- loading lexica"); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, ENTRY_LEXICA); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, ENTRY_LEXICA); } else if (flag == ShiftPopParser.FLAG_TRAIN_BOOST) { System.out.println("\n* Train conditional"); decoder = new OneVsAllDecoder(m_model); if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_EAGER)) parser = new ShiftEagerParser(flag, t_xml, t_map, decoder); else if (s_depParser.equals(AbstractDepParser.ALG_SHIFT_POP)) parser = new ShiftPopParser(flag, t_xml, t_map, decoder); } AbstractReader<DepNode, DepTree> reader = null; DepTree tree; int n; if (s_format.equals(AbstractReader.FORMAT_DEP)) reader = new DepReader(s_trainFile, true); else if (s_format.equals(AbstractReader.FORMAT_CONLLX)) reader = new CoNLLXReader(s_trainFile, true); parser.setLanguage(s_language); reader.setLanguage(s_language); for (n = 0; (tree = reader.nextTree()) != null; n++) { parser.parse(tree); if (n % 1000 == 0) System.out.printf("\r- parsing: %dK", n / 1000); } System.out.println("\r- parsing: " + n); if (flag == ShiftPopParser.FLAG_TRAIN_LEXICON) { System.out.println("- saving"); parser.saveTags(ENTRY_LEXICA); t_xml = parser.getDepFtrXml(); } else if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE || flag == ShiftPopParser.FLAG_TRAIN_BOOST) { a_yx = parser.a_trans; zout.putArchiveEntry(new JarArchiveEntry(ENTRY_PARSER)); PrintStream fout = new PrintStream(zout); fout.print(s_depParser); fout.flush(); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_FEATURE)); IOUtils.copy(new FileInputStream(s_featureXml), zout); zout.closeArchiveEntry(); zout.putArchiveEntry(new JarArchiveEntry(ENTRY_LEXICA)); IOUtils.copy(new FileInputStream(ENTRY_LEXICA), zout); zout.closeArchiveEntry(); if (flag == ShiftPopParser.FLAG_TRAIN_INSTANCE) t_map = parser.getDepFtrMap(); } }
Code Sample 2:
public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); while (in.read(buff) != -1) { PrintUtil.prt("%%%"); buff.flip(); out.write(buff); buff.clear(); } }
|
11
|
Code Sample 1:
public static boolean copyFileToContentFolder(String source, LearningDesign learningDesign) { File inputFile = new File(source); File outputFile = new File(getRootFilePath(learningDesign) + inputFile.getName()); FileReader in; try { in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); return false; } return true; }
Code Sample 2:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
|
11
|
Code Sample 1:
public static boolean copyFile(final File src, final File dest, long extent, final boolean overwrite) throws FileNotFoundException, IOException { boolean result = false; if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Copying file " + src + " to " + dest + " extent " + extent + " exists " + dest.exists()); } if (dest.exists()) { if (overwrite) { dest.delete(); LOGGER.finer(dest.getAbsolutePath() + " removed before copy."); } else { return result; } } 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(); if (extent < 0) { extent = fcin.size(); } long trans = fcin.transferTo(0, extent, fcout); if (trans < extent) { result = false; } result = true; } catch (IOException e) { String message = "Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath() + " with extent " + extent + " got IOE: " + e.getMessage(); if (e.getMessage().equals("Invalid argument")) { LOGGER.severe("Failed copy, trying workaround: " + message); workaroundCopyFile(src, dest); } else { IOException newE = new IOException(message); newE.setStackTrace(e.getStackTrace()); throw newE; } } finally { if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } if (fis != null) { fis.close(); } if (fos != null) { fos.close(); } } return result; }
Code Sample 2:
@Test public void testTransactWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwritetrans.txt"); RFileOutputStream out = new RFileOutputStream(file, WriteMode.TRANSACTED, false, 1); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
|
00
|
Code Sample 1:
private static String md5Encode(String pass) { String string; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(pass.getBytes()); byte[] result = md.digest(); string = bytes2hexStr(result); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("La libreria java.security no implemente MD5"); } return string; }
Code Sample 2:
public static String getStringFromAFileAtURL(String anURL) { String htmlCode = "<html><body></body></html>"; try { URL url = new URL(anURL); URLConnection urlConnection = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine = ""; htmlCode = ""; while ((inputLine = in.readLine()) != null) htmlCode += inputLine + "\n"; in.close(); } catch (Exception e) { logs.info("URLResolver : lien mort"); JOptionPane.showMessageDialog(null, "lien mort"); return "<html><body></body></html>"; } return checkXMLTagsLowerCase(htmlCode); }
|
00
|
Code Sample 1:
private boolean request(URI uri, Controller controller, String login, String password) { SSLHttpClient client = new SSLHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(login, password)); HttpGet get = new HttpGet(uri); get.addHeader("Accept", "application/xml"); try { HttpResponse response = client.execute(get); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { final InputStream is = response.getEntity().getContent(); final XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); final XmlPullParser parser = factory.newPullParser(); parser.setInput(is, null); while (parser.next() != XmlPullParser.END_DOCUMENT && !controller.stopped()) { if (parser.getEventType() == XmlPullParser.START_TAG) { String name = parser.getName(); if (mEntity.equals(name)) { String id = parser.getAttributeValue(null, "id"); if (id != null) { Item item = new Item(id, parser.nextText()); controller.receiveItem(item); } } } } } } catch (Exception e) { controller.error(); return false; } return true; }
Code Sample 2:
public static void writeInputStreamToFile(final InputStream stream, final File target) { long size = 0; FileOutputStream fileOut; try { fileOut = new FileOutputStream(target); size = IOUtils.copyLarge(stream, fileOut); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (log.isInfoEnabled()) { log.info("Wrote " + size + " bytes to " + target.getAbsolutePath()); } else { System.out.println("Wrote " + size + " bytes to " + target.getAbsolutePath()); } }
|
00
|
Code Sample 1:
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")) { if (prop == null) { System.err.println("window without properties"); return; } int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Color bgcolor = prop.getValue("bgcolor", Color.white); String caption = prop.getValue("caption", ""); layout = prop.getValue("layout", 0); boolean statusbar = prop.getValue("statusbar", false); if (sheet.opentype == WABSheet.LAYERED) { Point pos = frame.getNextMDIPos(); sheet.setBounds(pos.x, pos.y, 400, 200); sheet.setNormalBounds(new Rectangle(pos.x, pos.y, 400, 200)); } else { sheet.setBounds(x, y, width, height); sheet.setNormalBounds(new Rectangle(x, y, width, height)); } if (sheet.opentype == WABSheet.MAXIMIZED) sheet.setMaximum(true); else sheet.setMaximum(false); sheet.setTitle(caption); frame.addSheetToMenu(caption); sheet.setBackground(bgcolor); if (layout == 1) sheet.getContentPane().setLayout(new FlowLayout()); else if (layout == 2) sheet.getContentPane().setLayout(new BorderLayout()); else sheet.getContentPane().setLayout(null); } else if (tag.equals("menu")) { if (prop == null) { System.err.println("menu without properties"); return; } String id = prop.getValue("id", ""); String label = prop.getValue("label", ""); if ((id != null && id.equals("WINDOW_MENU") || label.equalsIgnoreCase("window"))) { windowMenu = new JMenu(); menu = windowMenu; sheet.setWindowMenu(menu); } else { menu = new JMenu(); } menu.setText(label); sheet.menubar.add(menu); } else if (tag.equals("menuitem")) { if (prop == null) { System.err.println("menuitem without properties"); return; } JMenuItem item; String action = prop.getValue("action", ""); String label = prop.getValue("label", ""); boolean visible = prop.getValue("visible", true); String icon = prop.getValue("icon", ""); if (action.equals("WINDOW_OVERLAPPED")) { item = windowMenuOverlapped = new JMenuItem(); item.setActionCommand("10001"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_HORIZONTALLY")) { item = windowMenuTile = new JMenuItem(); item.setActionCommand("10002"); item.addActionListener(frame); } else if (action.equals("WINDOW_TILE_VERTICALLY")) { item = windowMenuArrange = new JMenuItem(); item.setActionCommand("10003"); item.addActionListener(frame); } else { item = new JMenuItem(); item.setActionCommand(action); item.addActionListener((WABClient) global); } item.setText(label); if (!visible) menu.setVisible(false); menu.add(item); if (frame.getToolBar() != null) { if (icon.length() > 0) { try { ImageIcon img = new ImageIcon(new URL(icon)); BufferedImage image = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); Graphics g = image.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); BufferedImage pressed = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = pressed.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 5, 5, 16, 16, (ImageObserver) null); g.setColor(new Color(132, 132, 132)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(255, 255, 255)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); BufferedImage over = new BufferedImage(25, 25, BufferedImage.TYPE_4BYTE_ABGR); g = over.createGraphics(); g.setColor(new Color(0, 0, 0, 0)); g.fillRect(0, 0, 25, 25); g.drawImage(img.getImage(), 4, 4, 16, 16, (ImageObserver) null); g.setColor(new Color(255, 255, 255)); g.drawLine(0, 0, 24, 0); g.drawLine(0, 0, 0, 24); g.setColor(new Color(132, 132, 132)); g.drawLine(24, 24, 24, 0); g.drawLine(24, 24, 0, 24); JButton b = new JButton(new ImageIcon(image)); b.setRolloverEnabled(true); b.setPressedIcon(new ImageIcon(pressed)); b.setRolloverIcon(new ImageIcon(over)); b.setToolTipText(label); b.setActionCommand(action); b.setFocusPainted(false); b.setBorderPainted(false); b.setContentAreaFilled(false); b.setMargin(new Insets(0, 0, 0, 0)); b.addActionListener(sheet); sheet.toolbar.add(b); } catch (Exception e) { } } } } else if (tag.equals("separator")) { menu.addSeparator(); } else if (tag.equals("choice")) { if (prop == null) { System.err.println("choice without properties"); return; } combo = new JComboBox(); list = null; int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); boolean editable = prop.getValue("editable", false); boolean visible = prop.getValue("visible", true); boolean enabled = prop.getValue("enabled", true); combo_text = prop.getValue("text", ""); combo.setBounds(x, y, width, height); combo.setName((String) id); if (editable) { combo.setEditable(editable); combo.setSelectedItem(combo_text); } if (!visible) combo.setVisible(false); if (!enabled) combo.setEnabled(false); if (layout == 0) sheet.getContentPane().add(combo); else sheet.getContentPane().add(combo, constraints); } else if (tag.equals("list")) { if (prop == null) { System.err.println("list without properties"); return; } list = new JList(); combo = null; listdata = new Vector(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); Object constraints = prop.getValue("constraints"); list.setName((String) id); list.setListData(listdata); JScrollPane sp = new JScrollPane(list); sp.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(sp); else sheet.getContentPane().add(sp, constraints); } else if (tag.equals("option")) { if (prop == null) { System.err.println("choice.option without properties"); return; } String value = prop.getValue("value", ""); String text = prop.getValue("text", ""); if (list != null) listdata.addElement(new ComboOption(text, value)); if (combo != null) { ComboOption co = new ComboOption(text, value); combo.addItem(co); if (combo_text.equals(text.trim())) combo.setSelectedItem(co); } } else if (tag.equals("label")) { if (prop == null) { System.err.println("label without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); boolean visible = prop.getValue("visible", true); label.setBounds(x, y, width, height); label.setText(text); if (!visible) label.setVisible(false); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("button")) { if (prop == null) { System.err.println("button without properties"); return; } JButton btn = new JButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); btn.setBounds(x, y, width, height); btn.setText(text); btn.addActionListener(sheet); btn.setActionCommand(onmouseup); if (layout == 0) sheet.getContentPane().add(btn); else sheet.getContentPane().add(btn, constraints); } else if (tag.equals("radiobutton")) { if (prop == null) { System.err.println("radiobutton without properties"); return; } JRadioButton rb = new JRadioButton(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); rb.setBounds(x, y, width, height); rb.setText(text); rb.setName((String) id); rb.addActionListener(sheet); rb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(rb); else sheet.getContentPane().add(rb, constraints); } else if (tag.equals("checkbox")) { if (prop == null) { System.err.println("checkbox without properties"); return; } JCheckBox cb = new JCheckBox(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String id = prop.getValue("id", ""); String text = prop.getValue("text", ""); String onmouseup = prop.getValue("onmouseup", ""); Object constraints = prop.getValue("constraints"); String checked = prop.getValue("checked", "false"); cb.setBounds(x, y, width, height); cb.setText(text); cb.setName((String) id); cb.setSelected(checked.equalsIgnoreCase("true")); if (layout == 0) sheet.getContentPane().add(cb); else sheet.getContentPane().add(cb, constraints); } else if (tag.equals("image")) { if (prop == null) { System.err.println("image without properties"); return; } JLabel label = new JLabel(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); String src = prop.getValue("src", ""); Object constraints = prop.getValue("constraints"); label.setIcon(new ImageIcon(new URL(src))); label.setBounds(x, y, width, height); if (layout == 0) sheet.getContentPane().add(label); else sheet.getContentPane().add(label, constraints); } else if (tag.equals("singlelineedit")) { if (prop == null) { System.err.println("singlelineedit without properties"); return; } String pwd = prop.getValue("password", ""); JTextField sle; if (pwd.equalsIgnoreCase("true")) sle = new JPasswordField(); else sle = new JTextField(); int x = prop.getValue("x", 0); int y = prop.getValue("y", 0); int width = prop.getValue("width", 0); int height = prop.getValue("height", 0); Object id = prop.getValue("id"); String text = prop.getValue("text", ""); Object constraints = prop.getValue("constraints"); sle.setBounds(x, y, width, height); sle.setText(text); sle.setName((String) id); if (layout == 0) sheet.getContentPane().add(sle); else sheet.getContentPane().add(sle, constraints); } else if (tag.equals("treeview")) { if (prop == null) { System.err.println("treeview without properties"); return; } treeview_root = new DefaultMutableTreeNode("root"); treeview = new JTree(treeview_root); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(treeview), constraints); } else if (tag.equals("treeitem")) { if (prop == null) { System.err.println("treeview.treeitem without properties"); return; } String text = prop.getValue("text", ""); String value = prop.getValue("value", ""); DefaultMutableTreeNode node = new DefaultMutableTreeNode(text); treeview_root.add(node); } else if (tag.equals("table")) { if (prop == null) { System.err.println("table without properties"); return; } String id = prop.getValue("id", ""); table = new JTable(); model = new DefaultTableModel() { public boolean isCellEditable(int row, int col) { return false; } }; table.setModel(model); table.setName((String) id); Object constraints = prop.getValue("constraints"); sheet.getContentPane().add(new JScrollPane(table), constraints); rowNumber = 0; columnNumber = 0; headerWidths = new Vector(); } else if (tag.equals("header")) { if (prop == null) { System.err.println("table.header without properties"); return; } String text = prop.getValue("text", ""); int width = prop.getValue("width", 0); headerWidths.addElement(new Integer(width)); model.addColumn(text); } else if (tag.equals("row")) { rowNumber++; columnNumber = 0; model.setRowCount(rowNumber); } 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("script")) { sheet.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; sheet.script += buffer + "\n"; } r.close(); sheet.endScript(); } catch (IOException ioe) { System.err.println("[IOError] " + ioe.getMessage()); System.exit(0); } } } else System.err.println("[sheet] unparsed tag: " + tag); } catch (Exception e) { e.printStackTrace(System.err); } }
Code Sample 2:
private ProgramYek getYek(String keyFilename) { File f = new File(keyFilename); InputStream is = null; try { is = new FileInputStream(f); } catch (java.io.FileNotFoundException ee) { } catch (Exception e) { System.out.println("** Exception reading key: " + e); } if (is == null) { try { URL url = ChiselResources.getResourceByName(ProgramYek.getVidSys(), ChiselResources.LOADFROMCLASSPATH); if (url == null) { } else { is = url.openStream(); } } catch (Exception e) { System.out.println("** Exception reading key: " + e); } } ProgramYek y = null; if (is != null) { try { y = ProgramYek.read(is); } catch (Exception e) { System.out.println("** Exception reading key: " + e); } } else { File chk = new File(checkFilename); if (chk.exists()) { System.out.println("This is the evaluation version of " + appname); y = new ProgramYek(appname, "Evaluation", "", 15); ProgramYek.serialize(y, keyFilename); } } return y; }
|
00
|
Code Sample 1:
protected void configure() { Enumeration<URL> resources = null; try { resources = classLoader.getResources(resourceName); } catch (IOException e) { binder().addError(e.getMessage(), e); return; } int resourceCount = 0; while (resources.hasMoreElements()) { URL url = resources.nextElement(); log.debug(url + " ..."); try { InputStream stream = url.openStream(); Properties props = new Properties(); props.load(stream); resourceCount++; addComponentsFromProperties(props, classLoader); } catch (IOException e) { binder().addError(e.getMessage(), e); } } log.info("Added components from " + resourceCount + " resources."); }
Code Sample 2:
@Override public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("getAudioFileFormat(URL url)"); } InputStream inputStream = url.openStream(); try { return getAudioFileFormat(inputStream); } finally { if (inputStream != null) { inputStream.close(); } } }
|
11
|
Code Sample 1:
public String generateKey(Message msg) { String text = msg.getDefaultMessage(); String meaning = msg.getMeaning(); if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); }
Code Sample 2:
private ContactModel convertJajahContactToContact(com.funambol.jajah.www.Contact jajahContact) throws JajahException { String temp; if (log.isTraceEnabled()) { log.trace("Converting Jajah contact to Foundation contact: Name:" + jajahContact.getName() + " Email:" + jajahContact.getEmail()); } try { ContactModel contactModel; Contact contact = new Contact(); if (jajahContact.getName() != null && jajahContact.getName().equals("") == false) { if (log.isDebugEnabled()) { log.debug("NAME: " + jajahContact.getName()); } contact.getName().getFirstName().setPropertyValue(jajahContact.getName()); } if (jajahContact.getEmail() != null && jajahContact.getEmail().equals("") == false) { if (log.isDebugEnabled()) { log.debug("EMAIL1_ADDRESS: " + jajahContact.getEmail()); } Email email1 = new Email(); email1.setEmailType(SIFC.EMAIL1_ADDRESS); email1.setPropertyValue(jajahContact.getEmail()); contact.getPersonalDetail().addEmail(email1); } if (jajahContact.getMobile() != null && jajahContact.getMobile().equals("") == false) { if (log.isDebugEnabled()) { log.debug("MOBILE_TELEPHONE_NUMBER: " + jajahContact.getMobile()); } Phone phone = new Phone(); phone.setPhoneType(SIFC.MOBILE_TELEPHONE_NUMBER); temp = jajahContact.getMobile().replace("-", ""); if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp); phone.setPropertyValue(temp); contact.getPersonalDetail().addPhone(phone); } if (jajahContact.getLandline() != null && jajahContact.getLandline().equals("") == false) { if (log.isDebugEnabled()) { log.debug("HOME_TELEPHONE_NUMBER: " + jajahContact.getLandline()); } Phone phone = new Phone(); phone.setPhoneType(SIFC.HOME_TELEPHONE_NUMBER); temp = jajahContact.getLandline().replace("-", ""); if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp); phone.setPropertyValue(temp); contact.getPersonalDetail().addPhone(phone); } if (jajahContact.getOffice() != null && jajahContact.getOffice().equals("") == false) { if (log.isDebugEnabled()) { log.debug("BUSINESS_TELEPHONE_NUMBER: " + jajahContact.getOffice()); } Phone phone = new Phone(); phone.setPhoneType(SIFC.BUSINESS_TELEPHONE_NUMBER); temp = jajahContact.getOffice().replace("-", ""); if (!(temp.startsWith("+") || temp.startsWith("00"))) temp = "+".concat(temp); phone.setPropertyValue(temp); contact.getBusinessDetail().addPhone(phone); } if (log.isDebugEnabled()) { log.debug("CONTACT_ID: " + jajahContact.getId()); } contactModel = new ContactModel(String.valueOf(jajahContact.getId()), contact); ContactToSIFC convert = new ContactToSIFC(null, null); String sifObject = convert.convert(contactModel); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(sifObject.getBytes()); String md5Hash = (new BigInteger(m.digest())).toString(); contactModel.setMd5Hash(md5Hash); return contactModel; } catch (Exception e) { throw new JajahException("JAJAH - convertJajahContactToContact error: " + e.getMessage()); } }
|
11
|
Code Sample 1:
public static String digest(String algorithm, String text) { MessageDigest mDigest = null; try { mDigest = MessageDigest.getInstance(algorithm); mDigest.update(text.getBytes(ENCODING)); } catch (NoSuchAlgorithmException nsae) { _log.error(nsae, nsae); } catch (UnsupportedEncodingException uee) { _log.error(uee, uee); } byte[] raw = mDigest.digest(); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(raw); }
Code Sample 2:
public String getShortToken(String md5Str) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); md5.update(md5Str.getBytes(JspRunConfig.charset)); } catch (Exception e) { e.printStackTrace(); } StringBuffer token = toHex(md5.digest()); return token.substring(8, 24); }
|
00
|
Code Sample 1:
public void genCreateSchema(DiagramModel diagramModel, String source) { try { con.setAutoCommit(false); stmt = con.createStatement(); Collection boxes = diagramModel.getBoxes(); BoxModel box; ItemModel item; String sqlQuery; int counter = 0; for (Iterator x = boxes.iterator(); x.hasNext(); ) { box = (BoxModel) x.next(); if (!box.isAbstractDef()) { sqlQuery = sqlCreateTableBegin(box); Collection items = box.getItems(); for (Iterator y = items.iterator(); y.hasNext(); ) { item = (ItemModel) y.next(); sqlQuery = sqlQuery + sqlColumn(item); } sqlQuery = sqlQuery + sqlForeignKeyColumns(box); sqlQuery = sqlQuery + sqlPrimaryKey(box); sqlQuery = sqlQuery + sqlUniqueKey(box); sqlQuery = sqlQuery + sqlCreateTableEnd(box, source); System.out.println(sqlQuery); try { stmt.executeUpdate(sqlQuery); counter++; } catch (SQLException e) { String tableName = box.getName(); System.out.println("// Problem while creating table " + tableName + " : " + e.getMessage()); String msg = Para.getPara().getText("tableNotCreated") + " -- " + tableName; this.informUser(msg); } } } this.genCreateForeignKeys(diagramModel); con.commit(); if (counter > 0) { String msg = Para.getPara().getText("schemaCreated") + " -- " + counter + " " + Para.getPara().getText("tables"); this.informUser(msg); } else { this.informUser(Para.getPara().getText("schemaNotCreated")); } } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the JDBC schema generation! "); try { con.rollback(); this.informUser(Para.getPara().getText("schemaNotCreated")); } catch (SQLException e1) { System.out.println(e1.getMessage() + " // Problem with the connection rollback! "); } } finally { try { con.setAutoCommit(true); stmt.close(); } catch (SQLException e) { System.out.println(e.getMessage() + " // Problem with the statement closing! "); } } }
Code Sample 2:
public void onMessage(Message message) { try { ExchangeImpl ex = new ExchangeImpl(); ex.setInMessage(message); Conduit backChannel = message.getDestination().getBackChannel(message, null, null); MessageImpl res = new MessageImpl(); res.put(Message.CONTENT_TYPE, "text/html"); backChannel.prepare(res); OutputStream out = res.getContent(OutputStream.class); FileInputStream is = new FileInputStream("test.html"); IOUtils.copy(is, out, 2048); out.flush(); out.close(); is.close(); backChannel.close(res); } catch (Exception e) { e.printStackTrace(); } }
|
00
|
Code Sample 1:
public Reader getReader() throws Exception { if (url_base == null) { return new FileReader(file); } else { URL url = new URL(url_base + file.getName()); return new InputStreamReader(url.openConnection().getInputStream()); } }
Code Sample 2:
public void copy(String fromFileName, String toFileName) throws IOException { log.info("copy() file:" + fromFileName + " toFile:" + toFileName); File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } }
|
00
|
Code Sample 1:
public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.B64InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
Code Sample 2:
static synchronized Person lookup(PhoneNumber number, String siteName) { Vector<Person> foundPersons = new Vector<Person>(5); if (number.isFreeCall()) { Person p = new Person("", "FreeCall"); p.addNumber(number); foundPersons.add(p); } else if (number.isSIPNumber() || number.isQuickDial()) { Person p = new Person(); p.addNumber(number); foundPersons.add(p); } else if (ReverseLookup.rlsMap.containsKey(number.getCountryCode())) { nummer = number.getAreaNumber(); rls_list = ReverseLookup.rlsMap.get(number.getCountryCode()); Debug.info("Begin reverselookup for: " + nummer); if (nummer.startsWith(number.getCountryCode())) nummer = nummer.substring(number.getCountryCode().length()); city = ""; for (int i = 0; i < rls_list.size(); i++) { yield(); rls = rls_list.get(i); if (!siteName.equals("") && !siteName.equals(rls.getName())) { Debug.warning("This lookup should be done using a specific site, skipping"); continue; } prefix = rls.getPrefix(); ac_length = rls.getAreaCodeLength(); if (!nummer.startsWith(prefix)) nummer = prefix + nummer; urlstr = rls.getURL(); if (urlstr.contains("$AREACODE")) { urlstr = urlstr.replaceAll("\\$AREACODE", nummer.substring(prefix.length(), ac_length + prefix.length())); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else if (urlstr.contains("$PFXAREACODE")) { urlstr = urlstr.replaceAll("\\$PFXAREACODE", nummer.substring(0, prefix.length() + ac_length)); urlstr = urlstr.replaceAll("\\$NUMBER", nummer.substring(prefix.length() + ac_length)); } else urlstr = urlstr.replaceAll("\\$NUMBER", nummer); Debug.info("Reverse lookup using: " + urlstr); url = null; data = new String[dataLength]; try { url = new URL(urlstr); if (url != null) { try { con = url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(15000); con.addRequestProperty("User-Agent", userAgent); con.connect(); header = ""; charSet = ""; for (int j = 0; ; j++) { String headerName = con.getHeaderFieldKey(j); String headerValue = con.getHeaderField(j); if (headerName == null && headerValue == null) { break; } if ("content-type".equalsIgnoreCase(headerName)) { String[] split = headerValue.split(";", 2); for (int k = 0; k < split.length; k++) { if (split[k].trim().toLowerCase().startsWith("charset=")) { String[] charsetSplit = split[k].split("="); charSet = charsetSplit[1].trim(); } } } header += headerName + ": " + headerValue + " | "; } Debug.debug("Header of " + rls.getName() + ":" + header); Debug.debug("CHARSET : " + charSet); BufferedReader d; if (charSet.equals("")) { d = new BufferedReader(new InputStreamReader(con.getInputStream(), "ISO-8859-1")); } else { d = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet)); } int lines = 0; while (null != ((str = d.readLine()))) { data[lines] = str; yield(); if (lines >= dataLength) { System.err.println("Result > " + dataLength + " Lines"); break; } lines++; } d.close(); Debug.info("Begin processing response from " + rls.getName()); for (int j = 0; j < rls.size(); j++) { yield(); firstname = ""; lastname = ""; company = ""; street = ""; zipcode = ""; city = ""; Person p = null; patterns = rls.getEntry(j); Pattern namePattern = null; Pattern streetPattern = null; Pattern cityPattern = null; Pattern zipcodePattern = null; Pattern firstnamePattern = null; Pattern lastnamePattern = null; Matcher nameMatcher = null; Matcher streetMatcher = null; Matcher cityMatcher = null; Matcher zipcodeMatcher = null; Matcher firstnameMatcher = null; Matcher lastnameMatcher = null; if (!patterns[ReverseLookupSite.NAME].equals("") && (patterns[ReverseLookupSite.FIRSTNAME].equals("") && patterns[ReverseLookupSite.LASTNAME].equals(""))) { namePattern = Pattern.compile(patterns[ReverseLookupSite.NAME]); } if (!patterns[ReverseLookupSite.STREET].equals("")) { streetPattern = Pattern.compile(patterns[ReverseLookupSite.STREET]); } if (!patterns[ReverseLookupSite.CITY].equals("")) { cityPattern = Pattern.compile(patterns[ReverseLookupSite.CITY]); } if (!patterns[ReverseLookupSite.ZIPCODE].equals("")) { zipcodePattern = Pattern.compile(patterns[ReverseLookupSite.ZIPCODE]); } if (!patterns[ReverseLookupSite.FIRSTNAME].equals("")) { firstnamePattern = Pattern.compile(patterns[ReverseLookupSite.FIRSTNAME]); } if (!patterns[ReverseLookupSite.LASTNAME].equals("")) { lastnamePattern = Pattern.compile(patterns[ReverseLookupSite.LASTNAME]); } for (int line = 0; line < dataLength; line++) { if (data[line] != null) { int spaceAlternative = 160; data[line] = data[line].replaceAll(new Character((char) spaceAlternative).toString(), " "); if (lastnamePattern != null) { lastnameMatcher = lastnamePattern.matcher(data[line]); if (lastnameMatcher.find()) { str = ""; for (int k = 1; k <= lastnameMatcher.groupCount(); k++) { if (lastnameMatcher.group(k) != null) str = str + lastnameMatcher.group(k).trim() + " "; } lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if ("lastname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setLastName(lastname); } } } yield(); if (firstnamePattern != null) { firstnameMatcher = firstnamePattern.matcher(data[line]); if (firstnameMatcher.find()) { str = ""; for (int k = 1; k <= firstnameMatcher.groupCount(); k++) { if (firstnameMatcher.group(k) != null) str = str + firstnameMatcher.group(k).trim() + " "; } firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(str)); firstname = firstname.trim(); firstname = firstname.replaceAll(",", ""); firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); if ("firstname".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); } } } yield(); if (namePattern != null) { nameMatcher = namePattern.matcher(data[line]); if (nameMatcher.find()) { str = ""; for (int k = 1; k <= nameMatcher.groupCount(); k++) { if (nameMatcher.group(k) != null) str = str + nameMatcher.group(k).trim() + " "; } String[] split; split = str.split(" ", 2); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(split[0])); lastname = lastname.trim(); lastname = lastname.replaceAll(",", ""); lastname = lastname.replaceAll("%20", " "); lastname = JFritzUtils.replaceSpecialCharsUTF(lastname); lastname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(lastname)); lastname = JFritzUtils.removeDuplicateWhitespace(lastname); if (split[1].length() > 0) { firstname = HTMLUtil.stripEntities(split[1]); if ((firstname.indexOf(" ") > -1) && (firstname.indexOf(" u.") == -1)) { company = JFritzUtils.removeLeadingSpaces(firstname.substring(firstname.indexOf(" ")).trim()); firstname = JFritzUtils.removeLeadingSpaces(firstname.substring(0, firstname.indexOf(" ")).trim()); } else { firstname = JFritzUtils.removeLeadingSpaces(firstname.replaceAll(" u. ", " und ")); } } firstname = firstname.replaceAll("%20", " "); firstname = JFritzUtils.replaceSpecialCharsUTF(firstname); firstname = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(firstname)); firstname = JFritzUtils.removeDuplicateWhitespace(firstname); firstname = firstname.trim(); company = company.replaceAll("%20", " "); company = JFritzUtils.replaceSpecialCharsUTF(company); company = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(company)); company = JFritzUtils.removeDuplicateWhitespace(company); company = company.trim(); if ("name".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); if (company.length() > 0) { p.addNumber(number.getIntNumber(), "business"); } else { p.addNumber(number.getIntNumber(), "home"); } foundPersons.add(p); } if (p != null) { p.setFirstName(firstname); p.setLastName(lastname); p.setCompany(company); } } } yield(); if (streetPattern != null) { streetMatcher = streetPattern.matcher(data[line]); if (streetMatcher.find()) { str = ""; for (int k = 1; k <= streetMatcher.groupCount(); k++) { if (streetMatcher.group(k) != null) str = str + streetMatcher.group(k).trim() + " "; } street = str.replaceAll("%20", " "); street = JFritzUtils.replaceSpecialCharsUTF(street); street = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(street)); street = JFritzUtils.removeDuplicateWhitespace(street); street = street.trim(); if ("street".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setStreet(street); } } } yield(); if (cityPattern != null) { cityMatcher = cityPattern.matcher(data[line]); if (cityMatcher.find()) { str = ""; for (int k = 1; k <= cityMatcher.groupCount(); k++) { if (cityMatcher.group(k) != null) str = str + cityMatcher.group(k).trim() + " "; } city = str.replaceAll("%20", " "); city = JFritzUtils.replaceSpecialCharsUTF(city); city = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(city)); city = JFritzUtils.removeDuplicateWhitespace(city); city = city.trim(); if ("city".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setCity(city); } } } yield(); if (zipcodePattern != null) { zipcodeMatcher = zipcodePattern.matcher(data[line]); if (zipcodeMatcher.find()) { str = ""; for (int k = 1; k <= zipcodeMatcher.groupCount(); k++) { if (zipcodeMatcher.group(k) != null) str = str + zipcodeMatcher.group(k).trim() + " "; } zipcode = str.replaceAll("%20", " "); zipcode = JFritzUtils.replaceSpecialCharsUTF(zipcode); zipcode = JFritzUtils.removeLeadingSpaces(HTMLUtil.stripEntities(zipcode)); zipcode = JFritzUtils.removeDuplicateWhitespace(zipcode); zipcode = zipcode.trim(); if ("zipcode".equals(patterns[ReverseLookupSite.FIRSTOCCURANCE])) { p = new Person(); p.addNumber(number.getIntNumber(), "home"); foundPersons.add(p); } if (p != null) { p.setPostalCode(zipcode); } } } } } if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) break; } yield(); if (!firstname.equals("") || !lastname.equals("") || !company.equals("")) { if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } return foundPersons.get(0); } } catch (IOException e1) { Debug.error("Error while retrieving " + urlstr); } } } catch (MalformedURLException e) { Debug.error("URL invalid: " + urlstr); } } yield(); Debug.warning("No match for " + nummer + " found"); if (city.equals("")) { if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(nummer); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(nummer); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(nummer); } Person p = new Person("", "", "", "", "", city, "", ""); p.addNumber(number.getAreaNumber(), "home"); return p; } else { Debug.warning("No reverse lookup sites for: " + number.getCountryCode()); Person p = new Person(); p.addNumber(number.getAreaNumber(), "home"); if (number.getCountryCode().equals(ReverseLookup.GERMANY_CODE)) city = ReverseLookupGermany.getCity(number.getIntNumber()); else if (number.getCountryCode().equals(ReverseLookup.AUSTRIA_CODE)) city = ReverseLookupAustria.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.USA_CODE)) city = ReverseLookupUnitedStates.getCity(number.getIntNumber()); else if (number.getCountryCode().startsWith(ReverseLookup.TURKEY_CODE)) city = ReverseLookupTurkey.getCity(number.getIntNumber()); p.setCity(city); return p; } return new Person("not found", "Person"); }
|
11
|
Code Sample 1:
@Override protected void writeFile() { super.writeFile(); try { String tagListFilePath = file.toURI().toASCIIString(); tagListFilePath = tagListFilePath.substring(0, tagListFilePath.lastIndexOf(FileManager.GLIPS_VIEW_EXTENSION)) + FileManager.TAG_LIST_FILE_EXTENSION; File tagListFile = new File(new URI(tagListFilePath)); StringBuffer buffer = new StringBuffer(""); for (String tagName : tags) { buffer.append(tagName + "\n"); } ByteBuffer byteBuffer = ByteBuffer.wrap(buffer.toString().getBytes("UTF-8")); FileOutputStream out = new FileOutputStream(tagListFile); FileChannel channel = out.getChannel(); channel.write(byteBuffer); channel.close(); } catch (Exception ex) { } try { String parentPath = file.getParentFile().toURI().toASCIIString(); if (!parentPath.endsWith("/")) { parentPath += "/"; } File srcFile = null, destFile = null; byte[] tab = new byte[1000]; int nb = 0; InputStream in = null; OutputStream out = null; for (String destinationName : dataBaseFiles.keySet()) { srcFile = dataBaseFiles.get(destinationName); if (srcFile != null) { destFile = new File(new URI(parentPath + destinationName)); in = new BufferedInputStream(new FileInputStream(srcFile)); out = new BufferedOutputStream(new FileOutputStream(destFile)); while (in.available() > 0) { nb = in.read(tab); if (nb > 0) { out.write(tab, 0, nb); } } in.close(); out.flush(); out.close(); } } } catch (Exception ex) { ex.printStackTrace(); } }
Code Sample 2:
private String getResourceAsString(final String name) throws IOException { final InputStream is = JiBXTestCase.class.getResourceAsStream(name); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copyAndClose(is, baos); return baos.toString(); }
|
00
|
Code Sample 1:
public static String encode(String username, String password) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(username.getBytes()); digest.update(password.getBytes()); return new String(digest.digest()); } catch (Exception e) { Log.error("Error encrypting credentials", e); } return null; }
Code Sample 2:
public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(inputFile).getChannel(); outChannel = new FileOutputStream(outputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { try { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } catch (IOException e) { throw e; } } }
|
11
|
Code Sample 1:
public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); }
Code Sample 2:
private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); try { IOUtils.copy(inputStream, outputStream); } finally { outputStream.close(); inputStream.close(); } }
|
00
|
Code Sample 1:
public void copiarMidias(final File vidDir, final File imgDir) { for (int i = 0; i < getMidias().size(); i++) { try { FileChannel src = new FileInputStream(getMidias().get(i).getUrl().trim()).getChannel(); FileChannel dest; if (getMidias().get(i).getTipo().equals("video")) { FileChannel vidDest = new FileOutputStream(vidDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = vidDest; } else { FileChannel midDest = new FileOutputStream(imgDir + "/" + processaString(getMidias().get(i).getTitulo()) + "." + retornaExtensaoMidia(getMidias().get(i))).getChannel(); dest = midDest; } dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (Exception e) { System.err.print(e.getMessage()); e.printStackTrace(); } } }
Code Sample 2:
public static boolean update(ItemNotaFiscal objINF) { final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; int result; CelulaFinanceira objCF = null; if (c == null) { return false; } if (objINF == null) { return false; } try { c.setAutoCommit(false); String sql = ""; sql = "update item_nota_fiscal " + "set id_item_pedido = ? " + "where id_item_nota_fiscal = ?"; pst = c.prepareStatement(sql); pst.setInt(1, objINF.getItemPedido().getCodigo()); pst.setInt(2, objINF.getCodigo()); result = pst.executeUpdate(); if (result > 0) { if (objINF.getItemPedido().getCelulaFinanceira() != null) { objCF = objINF.getItemPedido().getCelulaFinanceira(); objCF.atualizaGastoReal(objINF.getSubtotal()); if (CelulaFinanceiraDAO.update(objCF)) { } } } c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final Exception e1) { System.out.println("[ItemNotaFiscalDAO.update.rollback] Erro ao inserir -> " + e1.getMessage()); } System.out.println("[ItemNotaFiscalDAO.update.insert] Erro ao inserir -> " + e.getMessage()); result = 0; } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
|
11
|
Code Sample 1:
@Before public void setUp() throws IOException { testSbk = File.createTempFile("songbook", "sbk"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("test.sbk"), new FileOutputStream(testSbk)); test1Sbk = File.createTempFile("songbook", "sbk"); IOUtils.copy(Thread.currentThread().getContextClassLoader().getResourceAsStream("test1.sbk"), new FileOutputStream(test1Sbk)); }
Code Sample 2:
public static void copy(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
|
00
|
Code Sample 1:
protected URLConnection openURLConnection() throws IOException { final String locator = getMediaLocator(); if (locator == null) { return null; } final URL url; try { url = new URL(locator); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } final URLConnection connection = url.openConnection(); connection.connect(); return connection; }
Code Sample 2:
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { Session session = HibernateUtil.getInstance().getSession(); response.setBufferSize(65536); ServletOutputStream outStream = response.getOutputStream(); File file = null; FileData fileData = null; try { String fileParameter = request.getParameter("file"); String disposition = request.getParameter("disposition"); if (fileParameter == null || fileParameter.equals("")) { String pi = request.getPathInfo(); int lastSlashIndex = pi.lastIndexOf("/") + 1; fileParameter = pi.substring(lastSlashIndex, pi.indexOf("_", pi.lastIndexOf("/"))); } if (fileParameter == null || fileParameter.equals("")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.flushBuffer(); Logger.log("file parameter not specified"); return; } if (disposition == null || disposition.equals("")) { String pi = request.getPathInfo(); String filename = pi.substring(pi.lastIndexOf("/") + 1); int underscoreIndex = filename.indexOf("_") + 1; disposition = filename.substring(underscoreIndex, filename.indexOf("_", underscoreIndex)); } file = (File) session.load(File.class, new Long(fileParameter)); Logger.log("Content requested=" + file.getName() + ":" + fileParameter + " Referral: " + request.getParameter("referer")); long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long fileDate = file.getLastModifiedDate() - (file.getLastModifiedDate() % 1000); if (fileDate <= ifModifiedSince) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } response.setContentType(file.getContentType()); response.setHeader("Content-Description", file.getName()); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); response.flushBuffer(); Logger.log("Conditional GET: " + file.getName()); return; } User authUser = baseService.getAuthenticatedUser(session, request, response); if (!SecurityHelper.doesUserHavePermission(session, authUser, file, Permission.PERM.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.flushBuffer(); Logger.log("Forbidden content requested: " + fileParameter); return; } String contentType = file.getContentType(); response.setContentType(contentType); if ("attachment".equals(disposition)) { response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\""); } else { response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); } String name = file.getName(); response.setHeader("Content-Description", name); response.setDateHeader("Last-Modified", file.getLastModifiedDate()); response.setDateHeader("Expires", System.currentTimeMillis() + 31536000000L); response.setContentLength((int) file.getSize()); java.io.File possibleDataFile = new java.io.File(BaseSystem.getTempDir() + file.getNameOnDisk()); if (possibleDataFile.exists()) { Logger.log("File exists in " + BaseSystem.getTempDir() + " pulling " + possibleDataFile.getName()); FileInputStream fileInputStream = new FileInputStream(possibleDataFile); try { IOUtils.copy(fileInputStream, outStream); } finally { try { fileInputStream.close(); } catch (Throwable t) { } } } else { List<FileData> fileDataList = HibernateUtil.getInstance().executeQuery(session, "from " + FileData.class.getSimpleName() + " where permissibleObject.id = " + file.getId()); if (fileDataList.size() == 0) { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); Logger.log("Requested content not found: " + fileParameter); response.flushBuffer(); return; } fileData = (FileData) fileDataList.get(0); FileOutputStream fileOutputStream = null; try { java.io.File tmpDir = new java.io.File(BaseSystem.getTempDir()); tmpDir.mkdirs(); fileOutputStream = new FileOutputStream(possibleDataFile); IOUtils.write(fileData.getData(), fileOutputStream); } catch (Throwable t) { Logger.log(t); } finally { try { fileOutputStream.close(); } catch (Throwable t) { } } IOUtils.write(fileData.getData(), outStream); } } catch (Throwable t) { Logger.log(t); try { response.sendError(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.flushBuffer(); } catch (Throwable tt) { } try { response.reset(); response.resetBuffer(); } catch (Throwable tt) { } } finally { file = null; fileData = null; try { outStream.flush(); } catch (Throwable t) { } try { outStream.close(); } catch (Throwable t) { } try { session.close(); } catch (Throwable t) { } } }
|
00
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static boolean update(Cargo cargo) { int result = 0; Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); String sql = "update cargo set nome = (?) where id_cargo= ?"; pst = c.prepareStatement(sql); pst.setString(1, cargo.getNome()); pst.setInt(2, cargo.getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (SQLException e) { try { c.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } System.out.println("[CargoDAO.update] Erro ao atualizar -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
|
00
|
Code Sample 1:
public static void main(String[] args) throws IOException { String urltext = "http://www.vogella.de"; URL url = new URL(urltext); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); }
Code Sample 2:
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
|
00
|
Code Sample 1:
public static void initialize(Monitor monitor, final JETEmitter jetEmitter) throws JETException { IProgressMonitor progressMonitor = BasicMonitor.toIProgressMonitor(monitor); progressMonitor.beginTask("", 10); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_GeneratingJETEmitterFor_message", new Object[] { jetEmitter.templateURI })); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); try { final JETCompiler jetCompiler = jetEmitter.templateURIPath == null ? new MyBaseJETCompiler(jetEmitter.templateURI, jetEmitter.encoding, jetEmitter.classLoader) : new MyBaseJETCompiler(jetEmitter.templateURIPath, jetEmitter.templateURI, jetEmitter.encoding, jetEmitter.classLoader); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETParsing_message", new Object[] { jetCompiler.getResolvedTemplateURI() })); jetCompiler.parse(); progressMonitor.worked(1); String packageName = jetCompiler.getSkeleton().getPackageName(); if (jetEmitter.templateURIPath != null) { URI templateURI = URI.createURI(jetEmitter.templateURIPath[0]); URLClassLoader theClassLoader = null; if (templateURI.isPlatformResource()) { IProject project = workspace.getRoot().getProject(templateURI.segment(1)); if (JETNature.getRuntime(project) != null) { List<URL> urls = new ArrayList<URL>(); IJavaProject javaProject = JavaCore.create(project); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURL()); for (IClasspathEntry classpathEntry : javaProject.getResolvedClasspath(true)) { if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) { IPath projectPath = classpathEntry.getPath(); IProject otherProject = workspace.getRoot().getProject(projectPath.segment(0)); IJavaProject otherJavaProject = JavaCore.create(otherProject); urls.add(new File(otherProject.getLocation() + "/" + otherJavaProject.getOutputLocation().removeFirstSegments(1) + "/").toURL()); } } theClassLoader = new URLClassLoader(urls.toArray(new URL[0])) { @Override public Class<?> loadClass(String className) throws ClassNotFoundException { try { return super.loadClass(className); } catch (ClassNotFoundException classNotFoundException) { return jetEmitter.classLoader.loadClass(className); } } }; } } else if (templateURI.isPlatformPlugin()) { final Bundle bundle = Platform.getBundle(templateURI.segment(1)); if (bundle != null) { theClassLoader = new URLClassLoader(new URL[0], jetEmitter.classLoader) { @Override public Class<?> loadClass(String className) throws ClassNotFoundException { try { return bundle.loadClass(className); } catch (ClassNotFoundException classNotFoundException) { return super.loadClass(className); } } }; } } if (theClassLoader != null) { String className = (packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName(); if (className.endsWith("_")) { className = className.substring(0, className.length() - 1); } try { Class<?> theClass = theClassLoader.loadClass(className); Class<?> theOtherClass = null; try { theOtherClass = jetEmitter.classLoader.loadClass(className); } catch (ClassNotFoundException exception) { } if (theClass != theOtherClass) { String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } return; } } catch (ClassNotFoundException exception) { } } } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); jetCompiler.generate(outputStream); final InputStream contents = new ByteArrayInputStream(outputStream.toByteArray()); if (!javaModel.isOpen()) { javaModel.open(new SubProgressMonitor(progressMonitor, 1)); } else { progressMonitor.worked(1); } final IProject project = workspace.getRoot().getProject(jetEmitter.getProjectName()); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETPreparingProject_message", new Object[] { project.getName() })); IJavaProject javaProject; if (!project.exists()) { progressMonitor.subTask("JET creating project " + project.getName()); project.create(new SubProgressMonitor(progressMonitor, 1)); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreatingProject_message", new Object[] { project.getName() })); IProjectDescription description = workspace.newProjectDescription(project.getName()); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); description.setLocation(null); project.open(new SubProgressMonitor(progressMonitor, 1)); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); javaProject = JavaCore.create(project); for (Map.Entry<String, String> option : jetEmitter.getJavaOptions().entrySet()) { javaProject.setOption(option.getKey(), option.getValue()); } } else { project.open(new SubProgressMonitor(progressMonitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID }); project.setDescription(description, new SubProgressMonitor(progressMonitor, 1)); javaProject = JavaCore.create(project); } List<IClasspathEntry> classpath = new UniqueEList<IClasspathEntry>(Arrays.asList(javaProject.getRawClasspath())); for (int i = 0, len = classpath.size(); i < len; i++) { IClasspathEntry entry = classpath.get(i); if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE && ("/" + project.getName()).equals(entry.getPath().toString())) { classpath.remove(i); } } progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETInitializingProject_message", new Object[] { project.getName() })); IClasspathEntry classpathEntry = JavaCore.newSourceEntry(new Path("/" + project.getName() + "/src")); IClasspathEntry jreClasspathEntry = JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER")); classpath.add(classpathEntry); classpath.add(jreClasspathEntry); classpath.addAll(jetEmitter.classpathEntries); IFolder sourceFolder = project.getFolder(new Path("src")); if (!sourceFolder.exists()) { sourceFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } IFolder runtimeFolder = project.getFolder(new Path("bin")); if (!runtimeFolder.exists()) { runtimeFolder.create(false, true, new SubProgressMonitor(progressMonitor, 1)); } javaProject.setRawClasspath(classpath.toArray(new IClasspathEntry[classpath.size()]), new SubProgressMonitor(progressMonitor, 1)); javaProject.setOutputLocation(new Path("/" + project.getName() + "/bin"), new SubProgressMonitor(progressMonitor, 1)); javaProject.close(); progressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETOpeningJavaProject_message", new Object[] { project.getName() })); javaProject.open(new SubProgressMonitor(progressMonitor, 1)); IPackageFragmentRoot[] packageFragmentRoots = javaProject.getPackageFragmentRoots(); IPackageFragmentRoot sourcePackageFragmentRoot = null; for (int j = 0; j < packageFragmentRoots.length; ++j) { IPackageFragmentRoot packageFragmentRoot = packageFragmentRoots[j]; if (packageFragmentRoot.getKind() == IPackageFragmentRoot.K_SOURCE) { sourcePackageFragmentRoot = packageFragmentRoot; break; } } StringTokenizer stringTokenizer = new StringTokenizer(packageName, "."); IProgressMonitor subProgressMonitor = new SubProgressMonitor(progressMonitor, 1); subProgressMonitor.beginTask("", stringTokenizer.countTokens() + 4); subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_CreateTargetFile_message")); IContainer sourceContainer = sourcePackageFragmentRoot == null ? project : (IContainer) sourcePackageFragmentRoot.getCorrespondingResource(); while (stringTokenizer.hasMoreElements()) { String folderName = stringTokenizer.nextToken(); sourceContainer = sourceContainer.getFolder(new Path(folderName)); if (!sourceContainer.exists()) { ((IFolder) sourceContainer).create(false, true, new SubProgressMonitor(subProgressMonitor, 1)); } } IFile targetFile = sourceContainer.getFile(new Path(jetCompiler.getSkeleton().getClassName() + ".java")); if (!targetFile.exists()) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETCreating_message", new Object[] { targetFile.getFullPath() })); targetFile.create(contents, true, new SubProgressMonitor(subProgressMonitor, 1)); } else { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETUpdating_message", new Object[] { targetFile.getFullPath() })); targetFile.setContents(contents, true, true, new SubProgressMonitor(subProgressMonitor, 1)); } subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETBuilding_message", new Object[] { project.getName() })); project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, new SubProgressMonitor(subProgressMonitor, 1)); IMarker[] markers = targetFile.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE); boolean errors = false; for (int i = 0; i < markers.length; ++i) { IMarker marker = markers[i]; if (marker.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO) == IMarker.SEVERITY_ERROR) { errors = true; subProgressMonitor.subTask(marker.getAttribute(IMarker.MESSAGE) + " : " + (CodeGenPlugin.getPlugin().getString("jet.mark.file.line", new Object[] { targetFile.getLocation(), marker.getAttribute(IMarker.LINE_NUMBER) }))); } } if (!errors) { subProgressMonitor.subTask(CodeGenPlugin.getPlugin().getString("_UI_JETLoadingClass_message", new Object[] { jetCompiler.getSkeleton().getClassName() + ".class" })); List<URL> urls = new ArrayList<URL>(); urls.add(new File(project.getLocation() + "/" + javaProject.getOutputLocation().removeFirstSegments(1) + "/").toURL()); final Set<Bundle> bundles = new HashSet<Bundle>(); LOOP: for (IClasspathEntry jetEmitterClasspathEntry : jetEmitter.getClasspathEntries()) { IClasspathAttribute[] classpathAttributes = jetEmitterClasspathEntry.getExtraAttributes(); if (classpathAttributes != null) { for (IClasspathAttribute classpathAttribute : classpathAttributes) { if (classpathAttribute.getName().equals(CodeGenUtil.EclipseUtil.PLUGIN_ID_CLASSPATH_ATTRIBUTE_NAME)) { Bundle bundle = Platform.getBundle(classpathAttribute.getValue()); if (bundle != null) { bundles.add(bundle); continue LOOP; } } } } urls.add(new URL("platform:/resource" + jetEmitterClasspathEntry.getPath() + "/")); } URLClassLoader theClassLoader = new URLClassLoader(urls.toArray(new URL[0]), jetEmitter.classLoader) { @Override public Class<?> loadClass(String className) throws ClassNotFoundException { try { return super.loadClass(className); } catch (ClassNotFoundException exception) { for (Bundle bundle : bundles) { try { return bundle.loadClass(className); } catch (ClassNotFoundException exception2) { } } throw exception; } } }; Class<?> theClass = theClassLoader.loadClass((packageName.length() == 0 ? "" : packageName + ".") + jetCompiler.getSkeleton().getClassName()); String methodName = jetCompiler.getSkeleton().getMethodName(); Method[] methods = theClass.getDeclaredMethods(); for (int i = 0; i < methods.length; ++i) { if (methods[i].getName().equals(methodName)) { jetEmitter.setMethod(methods[i]); break; } } } subProgressMonitor.done(); } catch (CoreException exception) { throw new JETException(exception); } catch (Exception exception) { throw new JETException(exception); } finally { progressMonitor.done(); } }
Code Sample 2:
private void createImageArchive() throws Exception { imageArchive = new File(resoutFolder, "images.CrAr"); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(imageArchive))); out.writeInt(toNativeEndian(imageFiles.size())); for (int i = 0; i < imageFiles.size(); i++) { File f = imageFiles.get(i); out.writeLong(toNativeEndian(f.length())); out.writeLong(toNativeEndian(new File(resFolder, f.getName().substring(0, f.getName().length() - 5)).length())); } for (int i = 0; i < imageFiles.size(); i++) { BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageFiles.get(i))); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); } out.close(); }
|
11
|
Code Sample 1:
public static void uncompress(File srcFile, File destFile) throws IOException { InputStream input = null; OutputStream output = null; try { input = new GZIPInputStream(new FileInputStream(srcFile)); output = new BufferedOutputStream(new FileOutputStream(destFile)); IOUtils.copyLarge(input, output); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); } }
Code Sample 2:
public void createZipCopy(IUIContext ui, final String zipFileName, final File[] filesToZip, final FilenameFilter fileFilter, Timestamp timestamp) { TestCase.assertNotNull(ui); TestCase.assertNotNull(zipFileName); TestCase.assertFalse(zipFileName.trim().length() == 0); TestCase.assertNotNull(filesToZip); TestCase.assertNotNull(timestamp); String nameCopy = zipFileName; if (nameCopy.endsWith(".zip")) { nameCopy = nameCopy.substring(0, zipFileName.length() - 4); } nameCopy = nameCopy + "_" + timestamp.toString() + ".zip"; final String finalZip = nameCopy; IWorkspaceRunnable noResourceChangedEventsRunner = new IWorkspaceRunnable() { public void run(IProgressMonitor runnerMonitor) throws CoreException { try { Map<String, File> projectFiles = new HashMap<String, File>(); IPath basePath = new Path("/"); for (File nextLocation : filesToZip) { projectFiles.putAll(getFilesToZip(nextLocation, basePath, fileFilter)); } if (projectFiles.isEmpty()) { PlatformActivator.logDebug("Zip file (" + zipFileName + ") not created because there were no files to zip"); return; } IPath resultsPath = PlatformActivator.getDefault().getResultsPath(); File copyRoot = resultsPath.toFile(); copyRoot.mkdirs(); IPath zipFilePath = resultsPath.append(new Path(finalZip)); String zipFileName = zipFilePath.toPortableString(); ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); try { out.setLevel(Deflater.DEFAULT_COMPRESSION); for (String filePath : projectFiles.keySet()) { File nextFile = projectFiles.get(filePath); FileInputStream fin = new FileInputStream(nextFile); try { out.putNextEntry(new ZipEntry(filePath)); try { byte[] bin = new byte[4096]; int bread = fin.read(bin, 0, 4096); while (bread != -1) { out.write(bin, 0, bread); bread = fin.read(bin, 0, 4096); } } finally { out.closeEntry(); } } finally { fin.close(); } } } finally { out.close(); } } catch (FileNotFoundException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } catch (IOException e) { Status error = new Status(Status.ERROR, PlatformActivator.PLUGIN_ID, Status.ERROR, e.getLocalizedMessage(), e); throw new CoreException(error); } } }; try { IWorkspace workspace = ResourcesPlugin.getWorkspace(); workspace.run(noResourceChangedEventsRunner, workspace.getRoot(), IWorkspace.AVOID_UPDATE, new NullProgressMonitor()); } catch (CoreException ce) { PlatformActivator.logException(ce); } }
|
00
|
Code Sample 1:
protected Class findClass(String name) throws ClassNotFoundException { String classFile = name.replace('.', '/') + ".class"; InputStream classInputStream = null; if (this.extensionJars != null) { for (int i = 0; i < this.extensionJars.length; i++) { JarFile extensionJar = this.extensionJars[i]; JarEntry jarEntry = extensionJar.getJarEntry(classFile); if (jarEntry != null) { try { classInputStream = extensionJar.getInputStream(jarEntry); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } } } if (classInputStream == null) { URL url = getResource(classFile); if (url == null) { throw new ClassNotFoundException("Class " + name); } try { classInputStream = url.openStream(); } catch (IOException ex) { throw new ClassNotFoundException("Couldn't read class " + name, ex); } } try { ByteArrayOutputStream out = new ByteArrayOutputStream(); BufferedInputStream in = new BufferedInputStream(classInputStream); byte[] buffer = new byte[8096]; int size; while ((size = in.read(buffer)) != -1) { out.write(buffer, 0, size); } in.close(); return defineClass(name, out.toByteArray(), 0, out.size(), this.protectionDomain); } catch (IOException ex) { throw new ClassNotFoundException("Class " + name, ex); } }
Code Sample 2:
public static String toPWD(String pwd) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(pwd.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
|
11
|
Code Sample 1:
public static void main(String[] args) throws MalformedURLException, IOException { InputStream in = null; try { in = new URL("hdfs://localhost:8020/user/leeing/maxtemp/sample.txt").openStream(); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); System.out.println("\nend."); } }
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 void process(String dir) { String[] list = new File(dir).list(); if (list == null) return; int n = list.length; long[] bubblesort = new long[list.length + 1]; if (!statustext) { IJ.log("Current Directory is: " + dir); IJ.log(" "); IJ.log("DICOM File Name / " + prefix1 + " / " + prefix2 + " / " + prefix3 + " / " + pick); IJ.log(" "); } for (int i = 0; i < n; i++) { IJ.showStatus(i + "/" + n); File f = new File(dir + list[i]); if (!f.isDirectory()) { ImagePlus img = new Opener().openImage(dir, list[i]); if (img != null && img.getStackSize() == 1) { if (!scoutengine(img)) return; if (!statustext) { IJ.log(list[i] + "/" + whichprefix1 + "/" + whichprefix2 + "/" + whichprefix3 + "/" + whichcase); } int lastDigit = whichcase.length() - 1; while (lastDigit > 0) { if (!Character.isDigit(whichcase.charAt(lastDigit))) lastDigit -= 1; else break; } if (lastDigit < whichcase.length() - 1) whichcase = whichcase.substring(0, lastDigit + 1); bubblesort[i] = Long.parseLong(whichcase); } } } if (statussorta || statussortd || statustext) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (statussorta) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } else { if (bubblesort[i] < bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } } IJ.log(" "); for (int i = 0; i < n; i++) { if (!statustext) { IJ.log(list[i] + " / " + bubblesort[i]); } else { IJ.log(dir + list[i]); } } } if (open_as_stack || only_images) { boolean sorted = false; while (!sorted) { sorted = true; for (int i = 0; i < n - 1; i++) { if (bubblesort[i] > bubblesort[i + 1]) { long temp = bubblesort[i]; tempp = list[i]; bubblesort[i] = bubblesort[i + 1]; list[i] = list[i + 1]; bubblesort[i + 1] = temp; list[i + 1] = tempp; sorted = false; } } } if (only_images) { Opener o = new Opener(); int counter = 0; IJ.log(" "); for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; else { ImagePlus imp = o.openImage(path); counter++; if (imp != null) { IJ.log(counter + " + " + path); imp.show(); } else IJ.log(counter + " - " + path); } } return; } int width = 0, height = 0, type = 0; ImageStack stack = null; double min = Double.MAX_VALUE; double max = -Double.MAX_VALUE; int k = 0; try { for (int i = 0; i < n; i++) { String path = (dir + list[i]); if (path == null) break; if (list[i].endsWith(".txt")) continue; ImagePlus imp = new Opener().openImage(path); if (imp != null && stack == null) { width = imp.getWidth(); height = imp.getHeight(); type = imp.getType(); ColorModel cm = imp.getProcessor().getColorModel(); if (halfSize) stack = new ImageStack(width / 2, height / 2, cm); else stack = new ImageStack(width, height, cm); } if (stack != null) k = stack.getSize() + 1; IJ.showStatus(k + "/" + n); IJ.showProgress((double) k / n); if (imp == null) IJ.log(list[i] + ": unable to open"); else if (imp.getWidth() != width || imp.getHeight() != height) IJ.log(list[i] + ": wrong dimensions"); else if (imp.getType() != type) IJ.log(list[i] + ": wrong type"); else { ImageProcessor ip = imp.getProcessor(); if (grayscale) ip = ip.convertToByte(true); if (halfSize) ip = ip.resize(width / 2, height / 2); if (ip.getMin() < min) min = ip.getMin(); if (ip.getMax() > max) max = ip.getMax(); String label = imp.getTitle(); String info = (String) imp.getProperty("Info"); if (info != null) label += "\n" + info; stack.addSlice(label, ip); } System.gc(); } } catch (OutOfMemoryError e) { IJ.outOfMemory("FolderOpener"); stack.trim(); } if (stack != null && stack.getSize() > 0) { ImagePlus imp2 = new ImagePlus("Stack", stack); if (imp2.getType() == ImagePlus.GRAY16 || imp2.getType() == ImagePlus.GRAY32) imp2.getProcessor().setMinAndMax(min, max); imp2.show(); } IJ.showProgress(1.0); } }
Code Sample 2:
@Test(dependsOnMethods = { "getSize" }) public void download() throws IOException { FileObject typica = fsManager.resolveFile("s3://" + bucketName + "/jonny.zip"); File localCache = File.createTempFile("vfs.", ".s3-test"); FileOutputStream out = new FileOutputStream(localCache); IOUtils.copy(typica.getContent().getInputStream(), out); Assert.assertEquals(localCache.length(), typica.getContent().getSize()); localCache.delete(); }
|
11
|
Code Sample 1:
public static boolean changeCredentials() { boolean passed = false; boolean credentials = false; HashMap info = null; Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write the credentials to file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { System.out.println(ex.toString()); if (ex.getMessage().toLowerCase().contains("unable")) { JOptionPane.showMessageDialog(null, "Database problem occured, please try again later", "Error", JOptionPane.ERROR_MESSAGE); passed = true; testVar = false; } else { passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed until you enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } while (!passed) { Debug.log("Main.changeCredentials", "show dialog for userinfo"); info = getUserInfo(); if ((Boolean) info.get("submit")) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(info.get("password").toString().getBytes()); String passHash = new BigInteger(1, md5.digest()).toString(16); Debug.log("Main.changeCredentials", "validate credentials with the database"); passed = xmlRpcC.checkUser(info.get("username").toString(), passHash); Debug.log("Main.changeCredentials", "write credentials to local xml file"); xmlC.writeUserdata(userdataFile, info.get("username").toString(), passHash); credentials = passed; testVar = true; } catch (Exception ex) { Debug.log("Main.changeCredentials", "credential validation failed"); passed = Boolean.parseBoolean(ex.getMessage()); JOptionPane.showMessageDialog(null, "Invallid userdata, try again", "Invallid userdata", JOptionPane.ERROR_MESSAGE); } } else { if (new File(userdataFile).exists()) { testVar = true; credentials = true; } else { testVar = false; JOptionPane.showMessageDialog(null, "No userdata was entered\nNo tests will be executed untill u enter them ", "Warning", JOptionPane.ERROR_MESSAGE); } passed = true; } } return credentials; }
Code Sample 2:
public void setKey(String key) { MessageDigest md5; byte[] mdKey = new byte[32]; try { md5 = MessageDigest.getInstance("MD5"); md5.update(key.getBytes()); byte[] digest = md5.digest(); System.arraycopy(digest, 0, mdKey, 0, 16); System.arraycopy(digest, 0, mdKey, 16, 16); } catch (Exception e) { System.out.println("MD5 not implemented, can't generate key out of string!"); System.exit(1); } setKey(mdKey); }
|
11
|
Code Sample 1:
public static boolean copyFile(String source, String destination, boolean replace) { File sourceFile = new File(source); File destinationFile = new File(destination); if (sourceFile.isDirectory() || destinationFile.isDirectory()) return false; if (destinationFile.isFile() && !replace) return false; if (!sourceFile.isFile()) return false; if (replace) destinationFile.delete(); try { File dir = destinationFile.getParentFile(); while (dir != null && !dir.exists()) { dir.mkdir(); } DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile), 10240)); DataInputStream inStream = new DataInputStream(new BufferedInputStream(new FileInputStream(sourceFile), 10240)); try { while (inStream.available() > 0) { outStream.write(inStream.readUnsignedByte()); } } catch (EOFException eof) { } inStream.close(); outStream.close(); } catch (IOException ex) { throw new FailedException("Failed to copy file " + sourceFile.getAbsolutePath() + " to " + destinationFile.getAbsolutePath(), ex).setFile(destinationFile.getAbsolutePath()); } return true; }
Code Sample 2:
public static void main(String[] args) { Usage u = new ccngetmeta(); for (int i = 0; i < args.length - 3; i++) { if (!CommonArguments.parseArguments(args, i, u)) { u.usage(); System.exit(1); } if (CommonParameters.startArg > i + 1) i = CommonParameters.startArg - 1; } if (args.length != CommonParameters.startArg + 3) { u.usage(); System.exit(1); } try { int readsize = 1024; CCNHandle handle = CCNHandle.open(); String metaArg = args[CommonParameters.startArg + 1]; if (!metaArg.startsWith("/")) metaArg = "/" + metaArg; ContentName fileName = MetadataProfile.getLatestVersion(ContentName.fromURI(args[CommonParameters.startArg]), ContentName.fromNative(metaArg), CommonParameters.timeout, handle); if (fileName == null) { System.out.println("File " + args[CommonParameters.startArg] + " does not exist"); System.exit(1); } if (VersioningProfile.hasTerminalVersion(fileName)) { } else { System.out.println("File " + fileName + " does not exist... exiting"); System.exit(1); } File theFile = new File(args[CommonParameters.startArg + 2]); if (theFile.exists()) { System.out.println("Overwriting file: " + args[CommonParameters.startArg + 1]); } FileOutputStream output = new FileOutputStream(theFile); long starttime = System.currentTimeMillis(); CCNInputStream input; if (CommonParameters.unversioned) input = new CCNInputStream(fileName, handle); else input = new CCNFileInputStream(fileName, handle); if (CommonParameters.timeout != null) { input.setTimeout(CommonParameters.timeout); } byte[] buffer = new byte[readsize]; int readcount = 0; long readtotal = 0; while ((readcount = input.read(buffer)) != -1) { readtotal += readcount; output.write(buffer, 0, readcount); output.flush(); } if (CommonParameters.verbose) System.out.println("ccngetfile took: " + (System.currentTimeMillis() - starttime) + "ms"); System.out.println("Retrieved content " + args[CommonParameters.startArg + 1] + " got " + readtotal + " bytes."); System.exit(0); } catch (ConfigurationException e) { System.out.println("Configuration exception in ccngetfile: " + e.getMessage()); e.printStackTrace(); } catch (MalformedContentNameStringException e) { System.out.println("Malformed name: " + args[CommonParameters.startArg] + " " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println("Cannot write file or read content. " + e.getMessage()); e.printStackTrace(); } System.exit(1); }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
private File writeResourceToFile(String resource) throws IOException { File tmp = File.createTempFile("zfppt" + resource, null); InputStream res = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource); OutputStream out = new FileOutputStream(tmp); IOUtils.copy(res, out); out.close(); return tmp; }
|
11
|
Code Sample 1:
private boolean copy_to_file_io(File src, File dst) throws IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(src); is = new BufferedInputStream(is); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); byte buffer[] = new byte[1024 * 64]; int read; while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } return true; } finally { try { if (is != null) is.close(); } catch (IOException e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (IOException e) { Debug.debug(e); } } }
Code Sample 2:
public Boolean compress(String sSourceDir, ArrayList<String> aFiles, String sDestinationFilename) { logger.debug("compress(%s, %s, %s)", sSourceDir, aFiles, sDestinationFilename); BufferedInputStream oOrigin = null; FileOutputStream oDestination; ZipOutputStream oOutput = null; Iterator<String> oIterator; byte[] aData; try { oDestination = new FileOutputStream(sDestinationFilename); oOutput = new ZipOutputStream(new BufferedOutputStream(oDestination)); aData = new byte[BUFFER_SIZE]; oIterator = aFiles.iterator(); while (oIterator.hasNext()) { try { String sFilename = (String) oIterator.next(); FileInputStream fisInput = new FileInputStream(sSourceDir + File.separator + sFilename); oOrigin = new BufferedInputStream(fisInput, BUFFER_SIZE); ZipEntry oEntry = new ZipEntry(sFilename.replace('\\', '/')); oOutput.putNextEntry(oEntry); int iCount; while ((iCount = oOrigin.read(aData, 0, BUFFER_SIZE)) != -1) oOutput.write(aData, 0, iCount); } finally { StreamHelper.close(oOrigin); } } } catch (Exception oException) { logger.error(oException.getMessage(), oException); return false; } finally { StreamHelper.close(oOutput); } return true; }
|
11
|
Code Sample 1:
@Test public void testCopy_readerToOutputStream_Encoding_nullEncoding() 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, null); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Content differs", Arrays.equals(inData, baout.toByteArray())); }
Code Sample 2:
public static final boolean compressToZip(final String sSource, final String sDest, final boolean bDeleteSourceOnSuccess) { ZipOutputStream os = null; InputStream is = null; try { os = new ZipOutputStream(new FileOutputStream(sDest)); is = new FileInputStream(sSource); final byte[] buff = new byte[1024]; int r; String sFileName = sSource; if (sFileName.indexOf('/') >= 0) sFileName = sFileName.substring(sFileName.lastIndexOf('/') + 1); os.putNextEntry(new ZipEntry(sFileName)); while ((r = is.read(buff)) > 0) os.write(buff, 0, r); is.close(); os.flush(); os.closeEntry(); os.close(); } catch (Throwable e) { Log.log(Log.WARNING, "lazyj.Utils", "compressToZip : cannot compress '" + sSource + "' to '" + sDest + "' because", e); return false; } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { } } if (os != null) { try { os.close(); } catch (IOException ioe) { } } } if (bDeleteSourceOnSuccess) try { if (!(new File(sSource)).delete()) Log.log(Log.WARNING, "lazyj.Utils", "compressToZip: could not delete original file (" + sSource + ")"); } catch (SecurityException se) { Log.log(Log.ERROR, "lazyj.Utils", "compressToZip: security constraints prevents file deletion"); } return true; }
|
11
|
Code Sample 1:
public boolean visar() throws SQLException, ClassNotFoundException, Exception { Connection conn = null; PreparedStatement ps = null; Date fechaSystem = new Date(); DateFormat aaaammdd = new SimpleDateFormat("yyyyMMdd"); DateFormat hhmmss = new SimpleDateFormat("HHmmss"); DateFormat sss = new SimpleDateFormat("S"); String ss = sss.format(fechaSystem); if (ss.length() > 2) { ss = ss.substring(0, 2); } boolean visado = false; try { conn = ToolsBD.getConn(); conn.setAutoCommit(false); String sentenciaSql = "UPDATE BZMODIF SET FZJCUSVI=?, FZJFVISA=?, FZJHVISA=?" + ((hayVisadoExtracto) ? ", FZJIEXTR=?" : "") + ((hayVisadoRemitente) ? ", FZJIREMI=?" : "") + " WHERE FZJCENSA='E' AND FZJCAGCO=? AND FZJNUMEN=? AND FZJANOEN=? AND FZJFMODI=? AND FZJHMODI=?"; ps = conn.prepareStatement(sentenciaSql); ps.setString(1, usuarioVisado); ps.setInt(2, Integer.parseInt(aaaammdd.format(fechaSystem))); ps.setInt(3, Integer.parseInt(hhmmss.format(fechaSystem) + ss)); int contador = 4; if (hayVisadoExtracto) { ps.setString(contador++, "X"); } if (hayVisadoRemitente) { ps.setString(contador++, "X"); } ps.setInt(contador++, oficina); ps.setInt(contador++, numeroRegistro); ps.setInt(contador++, anoEntrada); ps.setString(contador++, fechaModificacion); ps.setString(contador++, horaModificacion); int registrosAfectados = ps.executeUpdate(); if (registrosAfectados > 0 && !hayVisadoExtracto && !hayVisadoRemitente) { visado = true; } if (registrosAfectados > 0 && (hayVisadoExtracto || hayVisadoRemitente)) { boolean generado = generarBZVISAD(conn, Integer.parseInt(aaaammdd.format(fechaSystem)), Integer.parseInt(hhmmss.format(fechaSystem) + ss)); if (generado) { visado = actualizarBZENTRA(conn); } String rem = ""; String com = ""; if (hayVisadoRemitente) { if (!remitente.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1, entidad2 + ""); valor.remove(); } } else { if (!altres.trim().equals("")) { rem = remitente; } else { javax.naming.InitialContext contexto = new javax.naming.InitialContext(); Object ref = contexto.lookup("es.caib.regweb.ValoresHome"); ValoresHome home = (ValoresHome) javax.rmi.PortableRemoteObject.narrow(ref, ValoresHome.class); Valores valor = home.create(); rem = valor.recuperaRemitenteCastellano(entidad1Old, entidad2Old + ""); valor.remove(); } } if (hayVisadoExtracto) { com = extracto; } else { com = comentario; } try { Class t = Class.forName("es.caib.regweb.module.PluginHook"); Class[] partypes = { String.class, Integer.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class, Integer.class, Integer.class, String.class, Integer.class, String.class, String.class, Integer.class, Integer.class, Integer.class, String.class, String.class, String.class }; Object[] params = { "V", new Integer(anoEntrada), new Integer(numeroRegistro), new Integer(oficina), new Integer(fechaDocumento), rem, com, tipoDocumento, new Integer(fechaRegistro), new Integer(fzacagge), fora, new Integer(destinatario), idioma, null, null, null, null, null, null, null }; java.lang.reflect.Method metodo = t.getMethod("entrada", partypes); metodo.invoke(null, params); } catch (IllegalAccessException iae) { } catch (IllegalArgumentException iae) { } catch (InvocationTargetException ite) { } catch (NullPointerException npe) { } catch (ExceptionInInitializerError eiie) { } catch (NoSuchMethodException nsme) { } catch (SecurityException se) { } catch (LinkageError le) { } catch (ClassNotFoundException le) { } } conn.commit(); int fzahsis = Integer.parseInt(hhmmss.format(fechaSystem) + ss); String Stringsss = sss.format(fechaSystem); switch(Stringsss.length()) { case (1): Stringsss = "00" + Stringsss; break; case (2): Stringsss = "0" + Stringsss; break; } int horamili = Integer.parseInt(hhmmss.format(fechaSystem) + Stringsss); int fzafsis = Integer.parseInt(aaaammdd.format(fechaSystem)); logLopdBZMODIF("UPDATE", sessioEjb.getCallerPrincipal().getName().toUpperCase(), fzafsis, horamili, 'E', numeroRegistro, anoEntrada, oficina, Integer.parseInt(fechaModificacion), Integer.parseInt(horaModificacion)); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); e.printStackTrace(); visado = false; try { if (conn != null) conn.rollback(); else System.out.println("ERROR: No es pot fer rollback sense connexió!"); } catch (Exception ex) { System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); } } finally { ToolsBD.closeConn(conn, ps, null); } return visado; }
Code Sample 2:
public boolean setCliente(int IDcliente, String nombre, String paterno, String materno, String ocupacion, String rfc) { boolean inserto = false; try { stm = conexion.prepareStatement("insert into clientes values( '" + IDcliente + "' , '" + nombre.toUpperCase() + "' , '" + paterno.toUpperCase() + "' , '" + materno.toUpperCase() + "' , '" + ocupacion.toUpperCase() + "' , '" + rfc + "' )"); stm.executeUpdate(); conexion.commit(); inserto = true; } catch (SQLException e) { System.out.println("error al insertar registro en la tabla clientes general " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return inserto = false; } return inserto; }
|
00
|
Code Sample 1:
public static String getWhatsNew(String ver) { URL url = null; try { url = new URL("http://googlemeupdate.bravehost.com/History.htm"); } catch (MalformedURLException ex) { ex.printStackTrace(); } InputStream html = null; try { html = url.openStream(); int c = 0; String Buffer = ""; String Code = ""; while (c != -1) { try { c = html.read(); } catch (IOException ex) { } Buffer = Buffer + (char) c; } Buffer = Buffer.substring(Buffer.lastIndexOf(ver) + ver.length() + 2, Buffer.indexOf("end::")).replaceAll("||", ""); return "<html>" + Buffer.substring(Buffer.indexOf("Google.mE Version: ")); } catch (IOException ex) { ex.printStackTrace(); return ""; } }
Code Sample 2:
public void testSimpleHttpPostsWithContentLength() throws Exception { int reqNo = 20; Random rnd = new Random(); List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(false); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
|
00
|
Code Sample 1:
public static void transfer(FileInputStream fileInStream, FileOutputStream fileOutStream) throws IOException { FileChannel fileInChannel = fileInStream.getChannel(); FileChannel fileOutChannel = fileOutStream.getChannel(); long fileInSize = fileInChannel.size(); try { long transferred = fileInChannel.transferTo(0, fileInSize, fileOutChannel); if (transferred != fileInSize) { throw new IOException("transfer() did not complete"); } } finally { ensureClose(fileInChannel, fileOutChannel); } }
Code Sample 2:
public static void storePolicy(DBBroker broker, XmldbURI docPath) throws EXistException, IOException { XmldbURI docName = docPath.lastSegment(); URL url = XACMLUtil.class.getResource(docPath.toString()); if (url == null) return; String content = toString(url.openStream()); if (content == null) return; Collection collection = getPolicyCollection(broker); if (collection == null) return; TransactionManager transact = broker.getBrokerPool().getTransactionManager(); Txn txn = transact.beginTransaction(); try { IndexInfo info = collection.validateXMLResource(txn, broker, docName, content); collection.store(txn, broker, info, content, false); transact.commit(txn); } catch (Exception e) { transact.abort(txn); if (e instanceof EXistException) throw (EXistException) e; throw new EXistException("Error storing policy '" + docPath + "'", e); } }
|
11
|
Code Sample 1:
public static void copyFile(String fromFilePath, String toFilePath, boolean overwrite) throws IOException { File fromFile = new File(fromFilePath); File toFile = new File(toFilePath); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFilePath); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFilePath); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFilePath); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!overwrite) { throw new IOException(toFilePath + " already exists!"); } if (!toFile.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + toFilePath); } String parent = toFile.getParent(); if (parent == null) { parent = System.getProperty("user.dir"); } File dir = new File(parent); if (!dir.exists()) { throw new IOException("FileCopy: destination directory doesn't exist: " + parent); } if (dir.isFile()) { throw new IOException("FileCopy: destination is not a directory: " + parent); } if (!dir.canWrite()) { throw new IOException("FileCopy: destination directory is unwriteable: " + parent); } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { long lastModified = fromFile.lastModified(); toFile.setLastModified(lastModified); if (from != null) { try { from.close(); } catch (IOException e) { } } if (to != null) { try { to.close(); } catch (IOException e) { } } } }
Code Sample 2:
private BinaryDocument documentFor(String code, String type, int diagramIndex) { code = code.replaceAll("\n", "").replaceAll("\t", "").trim().replaceAll(" ", "%20"); StringBuilder builder = new StringBuilder("http://yuml.me/diagram/"); builder.append(type).append("/"); builder.append(code); URL url; try { url = new URL(builder.toString()); String name = "uml" + diagramIndex + ".png"; diagramIndex++; BinaryDocument pic = new BinaryDocument(name, "image/png"); IOUtils.copy(url.openStream(), pic.getContent().getOutputStream()); return pic; } catch (MalformedURLException e) { throw ManagedIOException.manage(e); } catch (IOException e) { throw ManagedIOException.manage(e); } }
|
00
|
Code Sample 1:
public static File[] splitFile(FileValidator validator, File source, long target_length, File todir, String prefix) { if (target_length == 0) return null; if (todir == null) { todir = new File(System.getProperty("java.io.tmpdir")); } if (prefix == null || prefix.equals("")) { prefix = source.getName(); } Vector result = new Vector(); FileOutputStream fos = null; FileInputStream fis = null; try { fis = new FileInputStream(source); byte[] bytes = new byte[CACHE_SIZE]; long current_target_size = 0; int current_target_nb = 1; int nbread = -1; try { File f = new File(todir, prefix + i18n.getString("targetname_suffix") + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); while ((nbread = fis.read(bytes)) > -1) { if ((current_target_size + nbread) > target_length) { int limit = (int) (target_length - current_target_size); fos.write(bytes, 0, limit); fos.close(); current_target_nb++; current_target_size = 0; f = new File(todir, prefix + "_" + current_target_nb); if (!validator.verifyFile(f)) return null; result.add(f); fos = new FileOutputStream(f); fos.write(bytes, limit, nbread - limit); current_target_size += nbread - limit; } else { fos.write(bytes, 0, nbread); current_target_size += nbread; } } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } try { if (fis != null) fis.close(); } catch (IOException e) { } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } File[] fresult = null; if (result.size() > 0) { fresult = new File[result.size()]; fresult = (File[]) result.toArray(fresult); } return fresult; }
Code Sample 2:
public RobotList<Percentage> sort_decr_Percentage(RobotList<Percentage> list, String field) { int length = list.size(); Index_value[] distri = new Index_value[length]; for (int i = 0; i < length; i++) { distri[i] = new Index_value(i, list.get(i).percent); } boolean permut; do { permut = false; for (int i = 0; i < length - 1; i++) { if (distri[i].value < distri[i + 1].value) { Index_value a = distri[i]; distri[i] = distri[i + 1]; distri[i + 1] = a; permut = true; } } } while (permut); RobotList<Percentage> sol = new RobotList<Percentage>(Percentage.class); for (int i = 0; i < length; i++) { sol.addLast(new Percentage(distri[i].value)); } return sol; }
|
00
|
Code Sample 1:
protected boolean hasOsmTileETag(String eTag) throws IOException { URL url; url = new URL(tile.getUrl()); HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); prepareHttpUrlConnection(urlConn); urlConn.setRequestMethod("HEAD"); urlConn.setReadTimeout(30000); String osmETag = urlConn.getHeaderField("ETag"); if (osmETag == null) return true; return (osmETag.equals(eTag)); }
Code Sample 2:
public InputStream getResource(FCValue name) throws FCException { Element el = _factory.getElementWithID(name.getAsString()); if (el == null) { throw new FCException("Could not find resource \"" + name + "\""); } String urlString = el.getTextTrim(); if (!urlString.startsWith("http")) { try { log.debug("Get resource: " + urlString); URL url; if (urlString.startsWith("file:")) { url = new URL(urlString); } else { url = getClass().getResource(urlString); } return url.openStream(); } catch (Exception e) { throw new FCException("Failed to load resource.", e); } } else { try { FCService http = getRuntime().getServiceFor(FCService.HTTP_DOWNLOAD); return http.perform(new FCValue[] { name }).getAsInputStream(); } catch (Exception e) { throw new FCException("Failed to load resource.", e); } } }
|
11
|
Code Sample 1:
public static void unzipFile(File zipFile, File destFile, boolean removeSrcFile) throws Exception { ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry zipentry = zipinputstream.getNextEntry(); int BUFFER_SIZE = 4096; while (zipentry != null) { String entryName = zipentry.getName(); log.info("<<<<<< ZipUtility.unzipFile - Extracting: " + zipentry.getName()); File newFile = null; if (destFile.isDirectory()) newFile = new File(destFile, entryName); else newFile = destFile; if (zipentry.isDirectory() || entryName.endsWith(File.separator + ".")) { newFile.mkdirs(); } else { ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); byte[] bufferArray = buffer.array(); FileUtilities.createDirectory(newFile.getParentFile()); FileChannel destinationChannel = new FileOutputStream(newFile).getChannel(); while (true) { buffer.clear(); int lim = zipinputstream.read(bufferArray); if (lim == -1) break; buffer.flip(); buffer.limit(lim); destinationChannel.write(buffer); } destinationChannel.close(); zipinputstream.closeEntry(); } zipentry = zipinputstream.getNextEntry(); } zipinputstream.close(); if (removeSrcFile) { if (zipFile.exists()) zipFile.delete(); } }
Code Sample 2:
public static void createModelZip(String filename, String tempdir) throws EDITSException { try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(filename); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); int BUFFER = 2048; byte data[] = new byte[BUFFER]; File f = new File(tempdir); for (File fs : f.listFiles()) { FileInputStream fi = new FileInputStream(fs.getAbsolutePath()); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(fs.getName()); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) out.write(data, 0, count); out.closeEntry(); origin.close(); } out.close(); } catch (Exception e) { throw new EDITSException("Can not create a model in file " + filename + " from folder " + tempdir); } }
|
00
|
Code Sample 1:
public static Shader loadShader(String vspath, String fspath, int textureUnits, boolean separateCam, boolean fog) throws ShaderProgramProcessException { if (vspath == "" || fspath == "") return null; BufferedReader in; String vert = "", frag = ""; try { URL v_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + vspath); String v_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + vspath; if (v_url != null) in = new BufferedReader(new InputStreamReader(v_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(v_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) vert += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in vertex shader \"" + vspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } try { URL f_url = Graphics.class.getClass().getResource("/eu/cherrytree/paj/graphics/shaders/" + fspath); String f_path = AppDefinition.getDefaultDataPackagePath() + "/shaders/" + fspath; if (f_url != null) in = new BufferedReader(new InputStreamReader(f_url.openStream())); else in = new BufferedReader(new InputStreamReader(new FileReader(f_path).getInputStream())); boolean run = true; String str; while (run) { str = in.readLine(); if (str != null) frag += str + "\n"; else run = false; } in.close(); } catch (Exception e) { System.err.println("Couldn't read in fragment shader \"" + fspath + "\"."); throw new ShaderNotLoadedException(vspath, fspath); } return loadShaderFromSource(vert, frag, textureUnits, separateCam, fog); }
Code Sample 2:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
|
11
|
Code Sample 1:
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
Code Sample 2:
private Collection<Class<? extends Plugin>> loadFromResource(ClassLoader classLoader, String resource) throws IOException { Collection<Class<? extends Plugin>> pluginClasses = new HashSet<Class<? extends Plugin>>(); Enumeration providerFiles = classLoader.getResources(resource); if (!providerFiles.hasMoreElements()) { logger.warning("Can't find the resource: " + resource); return pluginClasses; } do { URL url = (URL) providerFiles.nextElement(); InputStream stream = url.openStream(); BufferedReader reader; try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); } catch (IOException e) { continue; } String line; while ((line = reader.readLine()) != null) { int index = line.indexOf('#'); if (index != -1) { line = line.substring(0, index); } line = line.trim(); if (line.length() > 0) { Class pluginClass; try { pluginClass = classLoader.loadClass(line); } catch (ClassNotFoundException e) { logger.log(Level.WARNING, "Can't use the Pluginclass with the name " + line + ".", e); continue; } if (Plugin.class.isAssignableFrom(pluginClass)) { pluginClasses.add((Class<? extends Plugin>) pluginClass); } else { logger.warning("The Pluginclass with the name " + line + " isn't a subclass of Plugin."); } } } reader.close(); stream.close(); } while (providerFiles.hasMoreElements()); return pluginClasses; }
|
00
|
Code Sample 1:
static Object loadPersistentRepresentationFromFile(URL url) throws PersistenceException { PersistenceManager.persistenceURL.get().addFirst(url); ObjectInputStream ois = null; HierarchicalStreamReader reader = null; XStream xstream = null; try { Reader inputReader = new java.io.InputStreamReader(url.openStream()); try { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader xsr = inputFactory.createXMLStreamReader(url.toExternalForm(), inputReader); reader = new StaxReader(new QNameMap(), xsr); } catch (XMLStreamException xse) { throw new PersistenceException("Error creating reader", xse); } xstream = new XStream(new StaxDriver()); xstream.setClassLoader(Gate.getClassLoader()); ois = xstream.createObjectInputStream(reader); Object res = null; Iterator urlIter = ((Collection) PersistenceManager.getTransientRepresentation(ois.readObject())).iterator(); while (urlIter.hasNext()) { URL anUrl = (URL) urlIter.next(); try { Gate.getCreoleRegister().registerDirectories(anUrl); } catch (GateException ge) { Err.prln("Could not reload creole directory " + anUrl.toExternalForm()); } } res = ois.readObject(); ois.close(); return res; } catch (PersistenceException pe) { throw pe; } catch (Exception e) { throw new PersistenceException("Error loading GAPP file", e); } finally { PersistenceManager.persistenceURL.get().removeFirst(); if (PersistenceManager.persistenceURL.get().isEmpty()) { PersistenceManager.persistenceURL.remove(); } } }
Code Sample 2:
protected void downloadCacheFile(File file) throws Exception { ApplicationProperties app = ApplicationProperties.getInstance(); String address = app.getProperty(JabberConstants.PROPERTY_JABBER_SERVERLIST, DEFAULT_SERVER_URL); URL url = new URL(address); file.createNewFile(); OutputStream cache = new FileOutputStream(file); InputStream input = url.openStream(); byte buffer[] = new byte[1024]; int bytesRead = 0; while ((bytesRead = input.read(buffer)) >= 0) cache.write(buffer, 0, bytesRead); input.close(); cache.close(); }
|
11
|
Code Sample 1:
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
Code Sample 2:
public static boolean copyFile(File outFile, File inFile) { InputStream inStream = null; OutputStream outStream = null; try { if (outFile.createNewFile()) { inStream = new FileInputStream(inFile); outStream = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0) outStream.write(buffer, 0, length); inStream.close(); outStream.close(); } else return false; } catch (IOException iox) { iox.printStackTrace(); return false; } return true; }
|
00
|
Code Sample 1:
protected void refreshMods(String modsUrl) { while (true) { JMenuItem mi = mnMods.getItem(mnMods.getItemCount() - 1); if (mi == null) break; mnMods.remove(mnMods.getItemCount() - 1); } try { log.info("Loading mods from " + modsUrl); URL url = new URL(modsUrl); URLConnection conn = url.openConnection(); conn.setUseCaches(false); SAXReader reader = new SAXReader(); Document document = reader.read(conn.getInputStream()); Element root = document.getRootElement(); for (Iterator i = root.elementIterator("mod"); i.hasNext(); ) { final Element mod = (Element) i.next(); JMenuItem mi = new JMenuItem(mod.element("name").getTextTrim()); mi.setIcon(Application.icon("applications-other")); mi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Application.getInstance().openUrl(mod.element("siteUrl").getTextTrim()); } }); mnMods.add(mi); } } catch (Throwable t) { t.printStackTrace(); log.warn("Failed to dynamically add mod links"); } }
Code Sample 2:
public HttpURLConnection openConnection(String url) throws IOException { if (isDebugMode()) System.out.println("open: " + url); URL u = new URL(url); HttpURLConnection urlConnection; if (proxy != null) urlConnection = (HttpURLConnection) u.openConnection(proxy); else urlConnection = (HttpURLConnection) u.openConnection(); urlConnection.setRequestProperty("User-Agent", userAgent); return urlConnection; }
|
11
|
Code Sample 1:
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
Code Sample 2:
public void SplitFile(File in, File out0, File out1, long pos) throws IOException { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out0); FileChannel fic = fis.getChannel(); FileChannel foc = fos.getChannel(); foc.transferFrom(fic, 0, pos); foc.close(); fos = new FileOutputStream(out1); foc = fos.getChannel(); foc.transferFrom(fic, 0, fic.size() - pos); foc.close(); fic.close(); }
|
00
|
Code Sample 1:
public static Class[] findSubClasses(Class baseClass) { String packagePath = "/" + baseClass.getPackage().getName().replace('.', '/'); URL url = baseClass.getResource(packagePath); if (url == null) { return new Class[0]; } List<Class> derivedClasses = new ArrayList<Class>(); try { URLConnection connection = url.openConnection(); if (connection instanceof JarURLConnection) { JarFile jarFile = ((JarURLConnection) connection).getJarFile(); Enumeration e = jarFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = (ZipEntry) e.nextElement(); String entryName = entry.getName(); if (entryName.endsWith(".class")) { String clazzName = entryName.substring(0, entryName.length() - 6); clazzName = clazzName.replace('/', '.'); try { Class clazz = Class.forName(clazzName); if (isConcreteSubclass(baseClass, clazz)) { derivedClasses.add(clazz); } } catch (Throwable ignoreIt) { } } } } else if (connection instanceof FileURLConnection) { File file = new File(url.getFile()); File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { String filename = files[i].getName(); if (filename.endsWith(".class")) { filename = filename.substring(0, filename.length() - 6); String clazzname = baseClass.getPackage().getName() + "." + filename; try { Class clazz = Class.forName(clazzname); if (isConcreteSubclass(baseClass, clazz)) { derivedClasses.add(clazz); } } catch (Throwable ignoreIt) { } } } } } catch (IOException ignoreIt) { } return derivedClasses.toArray(new Class[derivedClasses.size()]); }
Code Sample 2:
private void getRandomGUID(boolean secure) { MessageDigest md5 = null; final StringBuilder sbValueBeforeMD5 = new StringBuilder(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.fatal("", e); return; } try { final long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(sId); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuilder sb = new StringBuilder(); for (int j = 0; j < array.length; ++j) { final int b = array[j] & 0xFF; if (b < 0x10) { sb.append('0'); } sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { logger.fatal("", e); } }
|
00
|
Code Sample 1:
public static long[] getOnlineUids(String myUid) throws ClientProtocolException, IOException, JSONException { HttpClient client = new DefaultHttpClient(params); HttpGet get = new HttpGet(UIDS_ONLINE_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()]; int uid = Integer.parseInt(myUid); for (int i = 0; i < result.length(); i++) { if (uid != result.getInt(i)) { friends[i] = result.getInt(i); } } return friends; } throw new IOException("bad http response:" + response.getStatusLine().getReasonPhrase()); }
Code Sample 2:
private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { assertTrue(resourceName.startsWith("/")); final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
|
11
|
Code Sample 1:
public List<SatelliteElementSet> parseTLE(String urlString) throws IOException { List<SatelliteElementSet> elementSets = new ArrayList<SatelliteElementSet>(); BufferedReader reader = null; try { String line = null; int i = 0; URL url = new URL(urlString); String[] lines = new String[3]; reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { i++; switch(i) { case 1: { lines[0] = line; break; } case 2: { lines[1] = line; break; } case 3: { lines[2] = line; Long catnum = Long.parseLong(StringUtils.strip(lines[1].substring(2, 7))); long setnum = Long.parseLong(StringUtils.strip(lines[1].substring(64, 68))); elementSets.add(new SatelliteElementSet(catnum, lines, setnum, Calendar.getInstance(TZ).getTime())); i = 0; break; } default: { throw new IOException("TLE string did not contain three elements"); } } } } finally { if (null != reader) { reader.close(); } } return elementSets; }
Code Sample 2:
public static String downloadWebpage1(String address) throws MalformedURLException, IOException { URL url = new URL(address); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; String page = ""; while((line = br.readLine()) != null) { page += line + "\n"; } br.close(); return page; }
|
00
|
Code Sample 1:
public String hash(String plainTextPassword) { try { MessageDigest digest = MessageDigest.getInstance(digestAlgorithm); digest.update(plainTextPassword.getBytes(charset)); byte[] rawHash = digest.digest(); return new String(org.jboss.seam.util.Hex.encodeHex(rawHash)); } catch (NoSuchAlgorithmException e) { log.error("Digest algorithm #0 to calculate the password hash will not be supported.", digestAlgorithm); throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { log.error("The Character Encoding #0 is not supported", charset); throw new RuntimeException(e); } }
Code Sample 2:
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(); } }
|
00
|
Code Sample 1:
public static void process(PricesType prices, Long id_site, DatabaseAdapter dbDyn) throws PriceException { PreparedStatement ps = null; String sql_ = null; PriceListItemType debugItem = null; try { if (log.isDebugEnabled()) { log.debug("dbDyn - " + dbDyn); if (dbDyn != null) log.debug("dbDyn.conn - " + dbDyn.getConnection()); } dbDyn.getConnection().setAutoCommit(false); if (dbDyn.getFamaly() != DatabaseManager.MYSQL_FAMALY) { sql_ = "delete from WM_PRICE_IMPORT_TABLE where shop_code in " + "( select shop_code from WM_PRICE_SHOP_LIST where ID_SITE=? )"; ps = dbDyn.prepareStatement(sql_); RsetTools.setLong(ps, 1, id_site); ps.executeUpdate(); ps.close(); ps = null; } else { String sqlCheck = ""; boolean isFound = false; WmPriceShopListListType shops = GetWmPriceShopListWithIdSiteList.getInstance(dbDyn, id_site).item; boolean isFirst = true; for (int i = 0; i < shops.getWmPriceShopListCount(); i++) { WmPriceShopListItemType shop = shops.getWmPriceShopList(i); isFound = true; if (isFirst) isFirst = false; else sqlCheck += ","; sqlCheck += ("'" + shop.getCodeShop() + "'"); } if (isFound) { sql_ = "delete from WM_PRICE_IMPORT_TABLE where shop_code in ( " + sqlCheck + " )"; if (log.isDebugEnabled()) log.debug("sql " + sql_); ps = dbDyn.prepareStatement(sql_); ps.executeUpdate(); ps.close(); ps = null; } } if (log.isDebugEnabled()) log.debug("Start unmarshalling data"); if (prices == null) throw new PriceException("������ ������� ����� �������. ��� ������ #10.03"); int batchLoop = 0; int count = 0; sql_ = "insert into WM_PRICE_IMPORT_TABLE " + "(is_group, id, id_main, name, price, currency, is_to_load, shop_code, ID_UPLOAD_PRICE) " + "values (?,?,?,?,?,?,?,?,?)"; Long id_upload_session = null; for (int j = 0; j < prices.getPriceListCount(); j++) { PriceListType price = prices.getPriceList(j); if (log.isDebugEnabled()) { log.debug("shopCode " + price.getShopCode()); log.debug("Size vector: " + price.getItemCount()); } for (int i = 0; (i < price.getItemCount()) && (count < 5000); i++, count++) { if (ps == null) ps = dbDyn.prepareStatement(sql_); PriceListItemType item = price.getItem(i); debugItem = item; ps.setInt(1, Boolean.TRUE.equals(item.getIsGroup()) ? 1 : 0); RsetTools.setLong(ps, 2, item.getItemID()); RsetTools.setLong(ps, 3, item.getParentID()); ps.setString(4, item.getNameItem()); RsetTools.setDouble(ps, 5, item.getPrice()); ps.setString(6, item.getCurr()); ps.setString(7, item.getIsLoad().toString()); ps.setString(8, price.getShopCode().toUpperCase()); RsetTools.setLong(ps, 9, id_upload_session); if (dbDyn.getIsBatchUpdate()) { ps.addBatch(); if (++batchLoop >= 200) { int[] updateCounts = ps.executeBatch(); ps.close(); ps = null; batchLoop = 0; } } else ps.executeUpdate(); } } if (dbDyn.getIsBatchUpdate()) { if (ps != null) { int[] updateCounts = ps.executeBatch(); ps.close(); ps = null; } } ImportPriceProcess.process(dbDyn, id_site); dbDyn.commit(); } catch (Exception e) { if (debugItem != null) { log.error("debugItem.getIsGroup() " + (Boolean.TRUE.equals(debugItem.getIsGroup()) ? 1 : 0)); log.error("debugItem.getItemID() " + debugItem.getItemID()); log.error("debugItem.getParentID() " + debugItem.getParentID()); log.error("debugItem.getNameItem() " + debugItem.getNameItem()); log.error("debugItem.getPrice() " + debugItem.getPrice()); log.error("debugItem.getCurr() " + debugItem.getCurr()); log.error("debugItem.getIsLoad().toString() " + debugItem.getIsLoad().toString()); } else log.error("debugItem is null"); log.error("sql:\n" + sql_); final String es = "error process import price-list"; log.error(es, e); try { dbDyn.rollback(); } catch (Exception e11) { } throw new PriceException(es, e); } finally { DatabaseManager.close(ps); ps = null; } }
Code Sample 2:
private void doPOST(HttpURLConnection connection, InputStream inputXML) throws MessageServiceException { try { OutputStream requestStream = new BufferedOutputStream(connection.getOutputStream()); IOUtils.copyAndClose(inputXML, requestStream); connection.connect(); } catch (IOException e) { throw new MessageServiceException(e.getMessage(), e); } }
|
00
|
Code Sample 1:
private Document saveFile(Document document, File file) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { Preference preference = preferences.get(0); String repo = preference.getRepository(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(document.getLocation()); File folder = new File(sbRepo.append(sbFolder).toString()); log.info("Check in file ID [" + document.getId() + "] to " + folder.getAbsolutePath()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null, fcVersionDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append(".").append(document.getExt()); StringBuffer sbVersionFile = new StringBuffer(folder.getAbsolutePath()).append(File.separator).append(document.getId()).append("_").append(document.getVersion().toString()).append(".").append(document.getExt()); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcVersionDest = new FileOutputStream(sbVersionFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); fcSource = new FileInputStream(file).getChannel(); fcVersionDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } if (fcVersionDest != null) { fcVersionDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } } return document; }
Code Sample 2:
private void init() throws IOException { JarInputStream jis = new JarInputStream(new BufferedInputStream(url.openStream())); try { do { ZipEntry ze = jis.getNextEntry(); if (ze == null) { break; } if (!ze.isDirectory()) { entries.add(ze.getName()); } } while (true); } finally { jis.close(); } }
|
00
|
Code Sample 1:
protected BufferedImage handleFirenzeException() { if (params.uri.indexOf("bncf.firenze.sbn.it") != -1) try { params.uri = params.uri.replace("http://opac.bncf.firenze.sbn.it/mdigit/jsp/mdigit.jsp?idr", "http://teca.bncf.firenze.sbn.it/TecaViewer/index.jsp?RisIdr"); URLConnection connection = new URL(params.uri).openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String url = null; params.uri = "addPage('http://opac.bncf.firenze.sbn.it/php/xlimage/XLImageRV.php"; while ((url = reader.readLine()) != null) { int index = url.indexOf(params.uri); if (index != -1) { url = url.substring(url.indexOf("'") + 1, url.lastIndexOf("'")); break; } } connection = new URL(url).openConnection(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); params.uri = "<input type=\"image\" border=\"0\" name=\"tpos\" width=\""; while ((url = reader.readLine()) != null) { int index = url.indexOf(params.uri); if (index != -1) { url = url.substring(url.indexOf(" src=\"") + 6, url.lastIndexOf("\" alt=\"")).replace("&z=2", "&z=32").replace("&z=4", "&z=64").replace("&z=8", "&z=128"); break; } } if (url != null) { connection = new URL(url).openConnection(); return processNewUri(connection); } } catch (Exception e) { } return null; }
Code Sample 2:
private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); }
|
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 void encryptFile(String originalFile, String encryptedFile, String password) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(password.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(originalFile); out = new CipherOutputStream(new FileOutputStream(encryptedFile), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
|
00
|
Code Sample 1:
@Override public CelShadingModel loadModel(URL url, String skin) throws IOException, IncorrectFormatException, ParsingErrorException { boolean baseURLWasNull = setBaseURLFromModelURL(url); CelShadingModel model = loadModel(url.openStream(), skin); if (baseURLWasNull) { popBaseURL(); } return (model); }
Code Sample 2:
public void testServletTesterClient() throws Exception { String base_url = tester.createSocketConnector(true); URL url = new URL(base_url + "/context/hello/info"); String result = IO.toString(url.openStream()); assertEquals("<h1>Hello Servlet</h1>", result); }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.