label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); sourceChannel.close(); destinationChannel.close(); } 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(); }
00
Code Sample 1: public OutputStream getAsOutputStream() throws IOException { OutputStream out; if (contentStream != null) { File tmp = File.createTempFile(getId(), null); out = new FileOutputStream(tmp); IOUtils.copy(contentStream, out); } else { out = new ByteArrayOutputStream(); out.write(getContent()); } return out; } Code Sample 2: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String 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(); }
00
Code Sample 1: public void get(File fileToGet) throws IOException { FTPClient ftp = new FTPClient(); try { int reply = 0; ftp.connect(this.endpointURL, Config.getFtpPort()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp get server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.setFileType(FTP.BINARY_FILE_TYPE); ftp.enterLocalPassiveMode(); OutputStream output = new FileOutputStream(fileToGet.getName()); if (ftp.retrieveFile(fileToGet.getName(), output) != true) { ftp.logout(); output.close(); throw new IOException("FTP get exception, maybe file not found"); } ftp.logout(); } catch (Exception e) { throw new IOException(e.getMessage()); } } Code Sample 2: private void copyFile(File from, File to) throws IOException { FileUtils.ensureParentDirectoryExists(to); byte[] buffer = new byte[1024]; int read; FileInputStream is = new FileInputStream(from); FileOutputStream os = new FileOutputStream(to); while ((read = is.read(buffer)) > 0) { os.write(buffer, 0, read); } is.close(); os.close(); }
11
Code Sample 1: public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException { ZipFile zip = new ZipFile(mapPackFile); try { Enumeration<? extends ZipEntry> entries = zip.entries(); MessageDigest md5Total = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5"); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) continue; String name = entry.getName(); if (name.toUpperCase().startsWith("META-INF")) continue; md5.reset(); InputStream in = zip.getInputStream(entry); byte[] data = Utilities.getInputBytes(in); in.close(); byte[] digest = md5.digest(data); log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\""); md5Total.update(digest); md5Total.update(name.getBytes()); } String md5sum = Hex.encodeHexString(md5Total.digest()); log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum); return md5sum; } finally { zip.close(); } } Code Sample 2: public static boolean validPassword(String password, String passwordInDb) throws NoSuchAlgorithmException, UnsupportedEncodingException { byte[] pwdInDb = hexStringToByte(passwordInDb); byte[] salt = new byte[SALT_LENGTH]; System.arraycopy(pwdInDb, 0, salt, 0, SALT_LENGTH); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(salt); md.update(password.getBytes("UTF-8")); byte[] digest = md.digest(); byte[] digestInDb = new byte[pwdInDb.length - SALT_LENGTH]; System.arraycopy(pwdInDb, SALT_LENGTH, digestInDb, 0, digestInDb.length); if (Arrays.equals(digest, digestInDb)) { return true; } else { return false; } }
00
Code Sample 1: private void init(URL url) { frame = new JInternalFrame(name); frame.addInternalFrameListener(this); listModel.add(listModel.size(), this); area = new JTextArea(); area.setMargin(new Insets(5, 5, 5, 5)); try { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String in; while ((in = reader.readLine()) != null) { area.append(in); area.append("\n"); } reader.close(); } catch (Exception e) { e.printStackTrace(); return; } th = area.getTransferHandler(); area.setFont(new Font("monospaced", Font.PLAIN, 12)); area.setCaretPosition(0); area.setDragEnabled(true); area.setDropMode(DropMode.INSERT); frame.getContentPane().add(new JScrollPane(area)); dp.add(frame); frame.show(); if (DEMO) { frame.setSize(300, 200); } else { frame.setSize(400, 300); } frame.setResizable(true); frame.setClosable(true); frame.setIconifiable(true); frame.setMaximizable(true); frame.setLocation(left, top); incr(); SwingUtilities.invokeLater(new Runnable() { public void run() { select(); } }); nullItem.addActionListener(this); setNullTH(); } Code Sample 2: 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; }
00
Code Sample 1: private void weightAndPlaceClasses() { int rows = getRows(); for (int curRow = _maxPackageRank; curRow < rows; curRow++) { xPos = getHGap() / 2; BOTLObjectSourceDiagramNode[] rowObject = getObjectsInRow(curRow); for (int i = 0; i < rowObject.length; i++) { if (curRow == _maxPackageRank) { int nDownlinks = rowObject[i].getDownlinks().size(); rowObject[i].setWeight((nDownlinks > 0) ? (1 / nDownlinks) : 2); } else { Vector uplinks = rowObject[i].getUplinks(); int nUplinks = uplinks.size(); if (nUplinks > 0) { float average_col = 0; for (int j = 0; j < uplinks.size(); j++) { average_col += ((BOTLObjectSourceDiagramNode) (uplinks.elementAt(j))).getColumn(); } average_col /= nUplinks; rowObject[i].setWeight(average_col); } else { rowObject[i].setWeight(1000); } } } int[] pos = new int[rowObject.length]; for (int i = 0; i < pos.length; i++) { pos[i] = i; } boolean swapped = true; while (swapped) { swapped = false; for (int i = 0; i < pos.length - 1; i++) { if (rowObject[pos[i]].getWeight() > rowObject[pos[i + 1]].getWeight()) { int temp = pos[i]; pos[i] = pos[i + 1]; pos[i + 1] = temp; swapped = true; } } } for (int i = 0; i < pos.length; i++) { rowObject[pos[i]].setColumn(i); if ((i > _vMax) && (rowObject[pos[i]].getUplinks().size() == 0) && (rowObject[pos[i]].getDownlinks().size() == 0)) { if (getColumns(rows - 1) > _vMax) { rows++; } rowObject[pos[i]].setRank(rows - 1); } else { rowObject[pos[i]].setLocation(new Point(xPos, yPos)); xPos += rowObject[pos[i]].getSize().getWidth() + getHGap(); } } yPos += getRowHeight(curRow) + getVGap(); } } Code Sample 2: public void run(String srcf, String dst) { final Path srcPath = new Path("./" + srcf); final Path desPath = new Path(dst); try { Path[] srcs = FileUtil.stat2Paths(hdfs.globStatus(srcPath), srcPath); OutputStream out = FileSystem.getLocal(conf).create(desPath); for (int i = 0; i < srcs.length; i++) { System.out.println(srcs[i]); InputStream in = hdfs.open(srcs[i]); IOUtils.copyBytes(in, out, conf, false); in.close(); } out.close(); } catch (IOException ex) { System.err.print(ex.getMessage()); } }
11
Code Sample 1: private void copyFile(File source) throws IOException { File backup = new File(source.getCanonicalPath() + ".backup"); if (!backup.exists()) { FileChannel srcChannel = new FileInputStream(source).getChannel(); backup.createNewFile(); FileChannel dstChannel = new FileOutputStream(backup).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } } Code Sample 2: public void sendContent(OutputStream out, Range range, Map<String, String> params, String contentType) throws IOException { LOGGER.debug("GET REQUEST OR RESPONSE - Send content: " + file.getAbsolutePath()); FileInputStream in = null; try { in = new FileInputStream(file); int bytes = IOUtils.copy(in, out); LOGGER.debug("wrote bytes: " + bytes); out.flush(); } finally { IOUtils.closeQuietly(in); } }
00
Code Sample 1: public static void main(String[] args) { final MavenDeployerGui gui = new MavenDeployerGui(); final Chooser repositoryChooser = new Chooser(gui.formPanel, JFileChooser.DIRECTORIES_ONLY); final Chooser artifactChooser = new Chooser(gui.formPanel, JFileChooser.FILES_ONLY); final Chooser pomChooser = new Chooser(gui.formPanel, JFileChooser.FILES_ONLY, new POMFilter()); gui.cancel.setEnabled(false); gui.cbDeployPOM.setVisible(false); gui.cbDeployPOM.setEnabled(false); gui.mavenBin.setText(findMavenExecutable()); gui.repositoryBrowser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File repo = repositoryChooser.chooseFrom(currentDir); if (repo != null) { currentDir = repositoryChooser.currentFolder; gui.repositoryURL.setText(repo.getAbsolutePath()); } } }); gui.artifactBrowser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { File artifact = artifactChooser.chooseFrom(currentDir); if (artifact != null) { currentDir = artifactChooser.currentFolder; gui.artifactFile.setText(artifact.getAbsolutePath()); } } }); gui.deploy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { deployer = new Deployer(gui, pom); deployer.execute(); } }); gui.clear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { gui.console.setText(""); } }); gui.cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (deployer != null) { deployer.stop(); deployer = null; } } }); gui.cbDeployPOM.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { readPOM(gui); } }); gui.loadPOM.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { pom = pomChooser.chooseFrom(currentDir); if (pom != null) { currentDir = pomChooser.currentFolder; readPOM(gui); gui.cbDeployPOM.setText("Deploy also " + pom.getAbsolutePath()); gui.cbDeployPOM.setEnabled(true); gui.cbDeployPOM.setVisible(true); } } }); String version = ""; try { URL url = Thread.currentThread().getContextClassLoader().getResource("META-INF/maven/com.mycila.maven/maven-deployer/pom.properties"); Properties p = new Properties(); p.load(url.openStream()); version = " " + p.getProperty("version"); } catch (Exception ignored) { version = " x.y"; } JFrame frame = new JFrame("Maven Deployer" + version + " - By Mathieu Carbou (http://blog.mycila.com)"); frame.setContentPane(gui.formPanel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setLocationByPlatform(true); frame.pack(); frame.setVisible(true); } Code Sample 2: public String digest(String password, String digestType, String inputEncoding) throws CmsPasswordEncryptionException { MessageDigest md; String result; try { if (DIGEST_TYPE_PLAIN.equals(digestType.toLowerCase())) { result = password; } else if (DIGEST_TYPE_SSHA.equals(digestType.toLowerCase())) { byte[] salt = new byte[4]; byte[] digest; byte[] total; if (m_secureRandom == null) { m_secureRandom = SecureRandom.getInstance("SHA1PRNG"); } m_secureRandom.nextBytes(salt); md = MessageDigest.getInstance(DIGEST_TYPE_SHA); md.reset(); md.update(password.getBytes(inputEncoding)); md.update(salt); digest = md.digest(); total = new byte[digest.length + salt.length]; System.arraycopy(digest, 0, total, 0, digest.length); System.arraycopy(salt, 0, total, digest.length, salt.length); result = new String(Base64.encodeBase64(total)); } else { md = MessageDigest.getInstance(digestType); md.reset(); md.update(password.getBytes(inputEncoding)); result = new String(Base64.encodeBase64(md.digest())); } } catch (NoSuchAlgorithmException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_ALGORITHM_1, digestType); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } catch (UnsupportedEncodingException e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_UNSUPPORTED_PASSWORD_ENCODING_1, inputEncoding); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsPasswordEncryptionException(message, e); } return result; }
11
Code Sample 1: private Datastream addManagedDatastreamVersion(Entry entry) throws StreamIOException, ObjectIntegrityException { Datastream ds = new DatastreamManagedContent(); setDSCommonProperties(ds, entry); ds.DSLocationType = "INTERNAL_ID"; ds.DSMIME = getDSMimeType(entry); IRI contentLocation = entry.getContentSrc(); if (contentLocation != null) { if (m_obj.isNew()) { ValidationUtility.validateURL(contentLocation.toString(), ds.DSControlGrp); } if (m_format.equals(ATOM_ZIP1_1)) { if (!contentLocation.isAbsolute() && !contentLocation.isPathAbsolute()) { File f = getContentSrcAsFile(contentLocation); contentLocation = new IRI(DatastreamManagedContent.TEMP_SCHEME + f.getAbsolutePath()); } } ds.DSLocation = contentLocation.toString(); ds.DSLocation = (DOTranslationUtility.normalizeDSLocationURLs(m_obj.getPid(), ds, m_transContext)).DSLocation; return ds; } try { File temp = File.createTempFile("binary-datastream", null); OutputStream out = new FileOutputStream(temp); if (MimeTypeHelper.isText(ds.DSMIME) || MimeTypeHelper.isXml(ds.DSMIME)) { IOUtils.copy(new StringReader(entry.getContent()), out, m_encoding); } else { IOUtils.copy(entry.getContentStream(), out); } ds.DSLocation = DatastreamManagedContent.TEMP_SCHEME + temp.getAbsolutePath(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } return ds; } Code Sample 2: public void testCreateNewXMLFile() throws InvalidNodeTypeDefException, ParseException, Exception { JCRNodeSource emptySource = loadTestSource(); assertEquals(false, emptySource.exists()); OutputStream sourceOut = emptySource.getOutputStream(); assertNotNull(sourceOut); InputStream contentIn = getClass().getResourceAsStream(CONTENT_FILE); try { IOUtils.copy(contentIn, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn.close(); } InputStream contentIn2 = getClass().getResourceAsStream(CONTENT2_FILE); sourceOut = emptySource.getOutputStream(); try { IOUtils.copy(contentIn2, sourceOut); sourceOut.flush(); } finally { sourceOut.close(); contentIn2.close(); } InputStream expected = getClass().getResourceAsStream(CONTENT2_FILE); JCRNodeSource persistentSource = loadTestSource(); assertEquals(true, persistentSource.exists()); InputStream actual = persistentSource.getInputStream(); try { assertTrue(isXmlEqual(expected, actual)); } finally { expected.close(); actual.close(); } JCRNodeSource tmpSrc = (JCRNodeSource) resolveSource(BASE_URL + "users/alexander.saar"); persistentSource.delete(); tmpSrc.delete(); }
00
Code Sample 1: public synchronized String encrypt(String password) { try { MessageDigest md = null; md = MessageDigest.getInstance("SHA-1"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); byte[] hash = (new Base64()).encode(raw); return new String(hash); } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm SHA-1 is not supported"); return null; } catch (UnsupportedEncodingException e) { System.out.println("UTF-8 encoding is not supported"); return null; } } Code Sample 2: public void open() throws IOException, RecursionException { String encoding = null; if (source != null) { Reader sourceReader = source.getCharacterStream(); if (sourceReader != null) { if (readerReader == null) readerReader = new XMLReaderReader(); readerReader.reset(sourceReader, true); isStandalone = readerReader.isXMLStandalone(); activeReader = readerReader; isOpen = true; return; } InputStream in = source.getByteStream(); if (in != null) { if (streamReader == null) streamReader = new XMLStreamReader(); streamReader.reset(in, source.getEncoding(), true); isOpen = true; isStandalone = streamReader.isXMLStandalone(); activeReader = streamReader; return; } url = new URL(defaultContext, source.getSystemId()); sysID = url.toString(); encoding = source.getEncoding(); } if (streamReader == null) streamReader = new XMLStreamReader(); streamReader.reset(url.openStream(), encoding, true); isStandalone = streamReader.isXMLStandalone(); activeReader = streamReader; isOpen = true; }
00
Code Sample 1: public static void main(String argv[]) { Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL; int errorCount = 0; int warningCount = 0; double tmp, s; double[] columnwise = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12. }; double[] rowwise = { 1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12. }; double[][] avals = { { 1., 4., 7., 10. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] rankdef = avals; double[][] tvals = { { 1., 2., 3. }, { 4., 5., 6. }, { 7., 8., 9. }, { 10., 11., 12. } }; double[][] subavals = { { 5., 8., 11. }, { 6., 9., 12. } }; double[][] rvals = { { 1., 4., 7. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] pvals = { { 1., 1., 1. }, { 1., 2., 3. }, { 1., 3., 6. } }; double[][] ivals = { { 1., 0., 0., 0. }, { 0., 1., 0., 0. }, { 0., 0., 1., 0. } }; double[][] evals = { { 0., 1., 0., 0. }, { 1., 0., 2.e-7, 0. }, { 0., -2.e-7, 0., 1. }, { 0., 0., 1., 0. } }; double[][] square = { { 166., 188., 210. }, { 188., 214., 240. }, { 210., 240., 270. } }; double[][] sqSolution = { { 13. }, { 15. } }; double[][] condmat = { { 1., 3. }, { 7., 9. } }; int rows = 3, cols = 4; int invalidld = 5; int raggedr = 0; int raggedc = 4; int validld = 3; int nonconformld = 4; int ib = 1, ie = 2, jb = 1, je = 3; int[] rowindexset = { 1, 2 }; int[] badrowindexset = { 1, 3 }; int[] columnindexset = { 1, 2, 3 }; int[] badcolumnindexset = { 1, 2, 4 }; double columnsummax = 33.; double rowsummax = 30.; double sumofdiagonals = 15; double sumofsquares = 650; print("\nTesting constructors and constructor-like methods...\n"); try { A = new Matrix(columnwise, invalidld); errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input"); } catch (IllegalArgumentException e) { try_success("Catch invalid length in packed constructor... ", e.getMessage()); } try { A = new Matrix(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to default constructor... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { A = Matrix.constructWithCopy(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to constructWithCopy... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructWithCopy... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } A = new Matrix(columnwise, validld); B = new Matrix(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; C = B.minus(A); avals[0][0] = tmp; B = Matrix.constructWithCopy(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; if ((tmp - B.get(0, 0)) != 0.0) { errorCount = try_failure(errorCount, "constructWithCopy... ", "copy not effected... data visible outside"); } else { try_success("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; I = new Matrix(ivals); try { check(I, Matrix.identity(3, 4)); try_success("identity... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "identity... ", "identity Matrix not successfully created"); } print("\nTesting access methods...\n"); B = new Matrix(avals); if (B.getRowDimension() != rows) { errorCount = try_failure(errorCount, "getRowDimension... ", ""); } else { try_success("getRowDimension... ", ""); } if (B.getColumnDimension() != cols) { errorCount = try_failure(errorCount, "getColumnDimension... ", ""); } else { try_success("getColumnDimension... ", ""); } B = new Matrix(avals); double[][] barray = B.getArray(); if (barray != avals) { errorCount = try_failure(errorCount, "getArray... ", ""); } else { try_success("getArray... ", ""); } barray = B.getArrayCopy(); if (barray == avals) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied"); } try { check(barray, avals); try_success("getArrayCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied"); } double[] bpacked = B.getColumnPackedCopy(); try { check(bpacked, columnwise); try_success("getColumnPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns"); } bpacked = B.getRowPackedCopy(); try { check(bpacked, rowwise); try_success("getRowPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows"); } try { tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension()); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("get(int,int)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } try { if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1) != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) { errorCount = try_failure(errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived"); } else { try_success("get(int,int)... ", ""); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } SUB = new Matrix(subavals); try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, jb, je); try { check(SUB, M); try_success("getMatrix(int,int,int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(ib, ie, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, columnindexset); try { check(SUB, M); try_success("getMatrix(int,int,int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, jb, je); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, jb, je); try { check(SUB, M); try_success("getMatrix(int[],int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, columnindexset); try { check(SUB, M); try_success("getMatrix(int[],int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("set(int,int,double)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } try { B.set(ib, jb, 0.); tmp = B.get(ib, jb); try { check(tmp, 0.); try_success("set(int,int,double)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Matrix element not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException"); } M = new Matrix(2, 3, 0.); try { B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, jb, je, M); try { check(M.minus(B.getMatrix(ib, ie, jb, je)), M); try_success("setMatrix(int,int,int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, columnindexset, M); try { check(M.minus(B.getMatrix(ib, ie, columnindexset)), M); try_success("setMatrix(int,int,int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, jb, je, M); try { check(M.minus(B.getMatrix(rowindexset, jb, je)), M); try_success("setMatrix(int[],int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, columnindexset, M); try { check(M.minus(B.getMatrix(rowindexset, columnindexset)), M); try_success("setMatrix(int[],int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } print("\nTesting array-like methods...\n"); S = new Matrix(columnwise, nonconformld); R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); A = R; try { S = A.minus(S); errorCount = try_failure(errorCount, "minus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minus conformance check... ", ""); } if (A.minus(R).norm1() != 0.) { errorCount = try_failure(errorCount, "minus... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minus... ", ""); } A = R.copy(); A.minusEquals(R); Z = new Matrix(A.getRowDimension(), A.getColumnDimension()); try { A.minusEquals(S); errorCount = try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minusEquals conformance check... ", ""); } if (A.minus(Z).norm1() != 0.) { errorCount = try_failure(errorCount, "minusEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minusEquals... ", ""); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); C = A.minus(B); try { S = A.plus(S); errorCount = try_failure(errorCount, "plus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plus conformance check... ", ""); } try { check(C.plus(B), A); try_success("plus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)"); } C = A.minus(B); C.plusEquals(B); try { A.plusEquals(S); errorCount = try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plusEquals conformance check... ", ""); } try { check(C, A); try_success("plusEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)"); } A = R.uminus(); try { check(A.plus(R), Z); try_success("uminus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)"); } A = R.copy(); O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0); C = A.arrayLeftDivide(R); try { S = A.arrayLeftDivide(S); errorCount = try_failure(errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivide conformance check... ", ""); } try { check(C, O); try_success("arrayLeftDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)"); } try { A.arrayLeftDivideEquals(S); errorCount = try_failure(errorCount, "arrayLeftDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivideEquals conformance check... ", ""); } A.arrayLeftDivideEquals(R); try { check(A, O); try_success("arrayLeftDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)"); } A = R.copy(); try { A.arrayRightDivide(S); errorCount = try_failure(errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivide conformance check... ", ""); } C = A.arrayRightDivide(R); try { check(C, O); try_success("arrayRightDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)"); } try { A.arrayRightDivideEquals(S); errorCount = try_failure(errorCount, "arrayRightDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivideEquals conformance check... ", ""); } A.arrayRightDivideEquals(R); try { check(A, O); try_success("arrayRightDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)"); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); try { S = A.arrayTimes(S); errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimes conformance check... ", ""); } C = A.arrayTimes(B); try { check(C.arrayRightDivideEquals(B), A); try_success("arrayTimes... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)"); } try { A.arrayTimesEquals(S); errorCount = try_failure(errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimesEquals conformance check... ", ""); } A.arrayTimesEquals(B); try { check(A.arrayRightDivideEquals(B), R); try_success("arrayTimesEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)"); } print("\nTesting I/O methods...\n"); try { DecimalFormat fmt = new DecimalFormat("0.0000E00"); fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read()...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } catch (Exception e) { try { e.printStackTrace(System.out); warningCount = try_warning(warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); DecimalFormat fmt = new DecimalFormat("0.0000"); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read() (2nd attempt) ...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } } R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); String tmpname = "TMPMATRIX.serial"; try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname)); out.writeObject(R); ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname)); A = (Matrix) sin.readObject(); try { check(A, R); try_success("writeObject(Matrix)/readObject(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "Matrix not serialized correctly"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; check write permission in current directory and retry"); } catch (Exception e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "unexpected error in serialization test"); } print("\nTesting linear algebra methods...\n"); A = new Matrix(columnwise, 3); T = new Matrix(tvals); T = A.transpose(); try { check(A.transpose(), T); try_success("transpose...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful"); } A.transpose(); try { check(A.norm1(), columnsummax); try_success("norm1...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation"); } try { check(A.normInf(), rowsummax); try_success("normInf()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation"); } try { check(A.normF(), Math.sqrt(sumofsquares)); try_success("normF...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation"); } try { check(A.trace(), sumofdiagonals); try_success("trace()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation"); } try { check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.); try_success("det()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation"); } SQ = new Matrix(square); try { check(A.times(A.transpose()), SQ); try_success("times(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation"); } try { check(A.times(0.), Z); try_success("times(double)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(double)...", "incorrect Matrix-scalar product calculation"); } A = new Matrix(columnwise, 4); QRDecomposition QR = A.qr(); R = QR.getR(); try { check(A, QR.getQ().times(R)); try_success("QRDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation"); } SingularValueDecomposition SVD = A.svd(); try { check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose()))); try_success("SingularValueDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation"); } DEF = new Matrix(rankdef); try { check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1); try_success("rank()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation"); } B = new Matrix(condmat); SVD = B.svd(); double[] singularvalues = SVD.getSingularValues(); try { check(B.cond(), singularvalues[0] / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]); try_success("cond()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation"); } int n = A.getColumnDimension(); A = A.getMatrix(0, n - 1, 0, n - 1); A.set(0, 0, 0.); LUDecomposition LU = A.lu(); try { check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU())); try_success("LUDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation"); } X = A.inverse(); try { check(A.times(X), Matrix.identity(3, 3)); try_success("inverse()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation"); } O = new Matrix(SUB.getRowDimension(), 1, 1.0); SOL = new Matrix(sqSolution); SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1); try { check(SQ.solve(SOL), O); try_success("solve()...", ""); } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "solve()...", e1.getMessage()); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "solve()...", e.getMessage()); } A = new Matrix(pvals); CholeskyDecomposition Chol = A.chol(); Matrix L = Chol.getL(); try { check(A, L.times(L.transpose())); try_success("CholeskyDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation"); } X = Chol.solve(Matrix.identity(3, 3)); try { check(A.times(X), Matrix.identity(3, 3)); try_success("CholeskyDecomposition solve()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation"); } EigenvalueDecomposition Eig = A.eig(); Matrix D = Eig.getD(); Matrix V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (symmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation"); } A = new Matrix(evals); Eig = A.eig(); D = Eig.getD(); V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (nonsymmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation"); } print("\nTestMatrix completed.\n"); print("Total errors reported: " + Integer.toString(errorCount) + "\n"); print("Total warnings reported: " + Integer.toString(warningCount) + "\n"); } Code Sample 2: void loadImage(Frame frame, URL url) throws Exception { URLConnection conn = url.openConnection(); String mimeType = conn.getContentType(); long length = conn.getContentLength(); InputStream is = conn.getInputStream(); loadImage(frame, is, length, mimeType); }
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 byte[] getResponseContent() throws IOException { if (responseContent == null) { InputStream is = getResponseStream(); if (is == null) { responseContent = new byte[0]; } else { ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); IOUtils.copy(is, baos); responseContent = baos.toByteArray(); } } return responseContent; }
00
Code Sample 1: void search(String query, String display) { try { String safeUrl; try { safeUrl = baseUrl + URLEncoder.encode(query, "UTF-8"); } catch (UnsupportedEncodingException ex) { safeUrl = baseUrl + query; Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } URL url_connection = new URL(safeUrl); url_connection.openConnection(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(url_connection.openStream()); Vector<SoundEntry> entries = new Vector<SoundEntry>(); Vector<String> path = new Vector<String>(); path.add("Results"); for (Hashtable<String, String> field : DocumentManager.getSubTable(document, path, "Entry")) { entries.add(new SoundEntry(field)); } int index; ButtonTabComponent btc = new ButtonTabComponent(tpnResults); btc.setInheritsPopupMenu(true); if (entries.isEmpty()) { JLabel msg = new JLabel("No results found"); tpnResults.add(display, msg); index = tpnResults.indexOfComponent(msg); } else { Enumeration<String> iter = entries.firstElement().fields.keys(); while (iter.hasMoreElements()) { String field = iter.nextElement(); if (!header.contains(field)) { header.addDefaultField(field); } } JTable result = new JTable(); Vector<String> fieldNames = header.getShownNames(); DefaultTableModel model = new DefaultTableModel(fieldNames, 0); for (SoundEntry entry : entries) { model.addRow(entry.getShownFields(header.getShownNames())); } result.setModel(model); result.setColumnSelectionAllowed(false); result.setSelectionMode(0); result.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { ((JTable) e.getSource()).getComponentAt(e.getPoint()); int row = ((JTable) e.getSource()).rowAtPoint(e.getPoint()); SoundEntry entry = ((ButtonTabComponent) tpnResults.getTabComponentAt(tpnResults.getSelectedIndex())).records.get(row); String file = entry.fields.get("FileName"); String title = entry.fields.get("Title"); if (file != null && !file.isEmpty()) { try { AudioSource src = new AudioSource(new URL(file), title); src.attachAudioStateListener(new AudioStateListener() { public void AudioStateReceived(AudioStateEvent event) { if (event.getAudioState() != AudioStateEvent.AudioState.CLOSED && event.getAudioState() != AudioStateEvent.AudioState.CLOSING) { llblStatus.setText(event.getAudioState() + ": " + ((AudioSource) event.getSource()).getTitle().toString()); } } }); audioPlayer.open(src); } catch (Exception j) { } } } }); JScrollPane scrollPane = new JScrollPane(result); tpnResults.add(display, scrollPane); index = tpnResults.indexOfComponent(scrollPane); btc.records = entries; } tpnResults.setTabComponentAt(index, btc); tpnResults.setSelectedIndex(index); } catch (SAXException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } } Code Sample 2: private void Download(String uri) throws MalformedURLException { URL url = new URL(uri); try { bm = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException ex) { bm = getError(); } }
00
Code Sample 1: public void run() { result.setValid(false); try { final HttpResponse response = client.execute(method, context); result.setValid(ArrayUtils.contains(validCodes, response.getStatusLine().getStatusCode())); result.setResult(response.getStatusLine().getStatusCode()); } catch (final ClientProtocolException e) { LOGGER.error(e); result.setValid(false); } catch (final IOException e) { LOGGER.error(e); result.setValid(false); } } Code Sample 2: public InputStream sendGetMessage(Properties args) throws IOException { String argString = ""; if (args != null) { argString = "?" + toEncodedString(args); } URL url = new URL(servlet.toExternalForm() + argString); URLConnection con = url.openConnection(); con.setUseCaches(false); sendHeaders(con); return con.getInputStream(); }
00
Code Sample 1: public static void get_PK_data() { try { FileWriter file_writer = new FileWriter("xml_data/PK_data_dump.xml"); BufferedWriter file_buffered_writer = new BufferedWriter(file_writer); URL fdt = new URL("http://opendata.5t.torino.it/get_pk"); URLConnection url_connection = fdt.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(url_connection.getInputStream())); String input_line; int num_lines = 0; while ((input_line = in.readLine()) != null) { file_buffered_writer.write(input_line + "\n"); num_lines++; } System.out.println("Parking :: Writed " + num_lines + " lines."); in.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } Code Sample 2: public static File copyToLibDirectory(final File file) throws FileNotFoundException, IOException { if (file == null || !file.exists()) { throw new FileNotFoundException(); } File directory = new File("lib/"); File dest = new File(directory, file.getName()); File parent = dest.getParentFile(); while (parent != null && !parent.equals(directory)) { parent = parent.getParentFile(); } if (parent.equals(directory)) { return file; } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(file).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } return dest; }
00
Code Sample 1: private void copyOneFile(String oldPath, String newPath) { File copiedFile = new File(newPath); try { FileInputStream source = new FileInputStream(oldPath); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } Code Sample 2: public List<BoardObject> favBoard() throws NetworkException, ContentException { HttpClient client = HttpConfig.newInstance(); HttpGet get = new HttpGet(HttpConfig.bbsURL() + HttpConfig.BBS_FAV); try { HttpResponse response = client.execute(get); HttpEntity entity = response.getEntity(); if (HTTPUtil.isHttp200(response) && HTTPUtil.isXmlContentType(response)) { Document doc = XmlOperator.readDocument(entity.getContent()); return BBSBodyParseHelper.parseFavBoardList(doc); } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
11
Code Sample 1: private void chopFileDisk() throws IOException { File tempFile = new File("" + logFile + ".tmp"); BufferedInputStream bis = null; BufferedOutputStream bos = null; long startCopyPos; byte readBuffer[] = new byte[2048]; int readCount; long totalBytesRead = 0; if (reductionRatio > 0 && logFile.length() > 0) { startCopyPos = logFile.length() / reductionRatio; } else { startCopyPos = 0; } try { bis = new BufferedInputStream(new FileInputStream(logFile)); bos = new BufferedOutputStream(new FileOutputStream(tempFile)); do { readCount = bis.read(readBuffer, 0, readBuffer.length); if (readCount > 0) { totalBytesRead += readCount; if (totalBytesRead > startCopyPos) { bos.write(readBuffer, 0, readCount); } } } while (readCount > 0); } finally { if (bos != null) { try { bos.close(); } catch (IOException ex) { } } if (bis != null) { try { bis.close(); } catch (IOException ex) { } } } if (tempFile.isFile()) { if (!logFile.delete()) { throw new IOException("Error when attempting to delete the " + logFile + " file."); } if (!tempFile.renameTo(logFile)) { throw new IOException("Error when renaming the " + tempFile + " to " + logFile + "."); } } } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { LogUtil.d(TAG, "Copying file %s to %s", src, dst); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dst).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { closeSafe(inChannel); closeSafe(outChannel); } }
11
Code Sample 1: public static void copyFile(File in, File out) { int len; byte[] buffer = new byte[1024]; try { FileInputStream fin = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); while ((len = fin.read(buffer)) >= 0) fout.write(buffer, 0, len); fin.close(); fout.close(); } catch (IOException ex) { } } Code Sample 2: public static boolean copyFileChannel(final File _fileFrom, final File _fileTo, final boolean _append) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(_fileFrom).getChannel(); dstChannel = new FileOutputStream(_fileTo, _append).getChannel(); if (_append) { dstChannel.transferFrom(srcChannel, dstChannel.size(), srcChannel.size()); } else { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } srcChannel.close(); dstChannel.close(); } catch (final IOException e) { return false; } finally { try { if (srcChannel != null) { srcChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } try { if (dstChannel != null) { dstChannel.close(); } } catch (final IOException _evt) { FuLog.error(_evt); } } return true; }
00
Code Sample 1: public static String getHashedPasswordTc(String password) throws java.security.NoSuchAlgorithmException { java.security.MessageDigest d = java.security.MessageDigest.getInstance("MD5"); d.reset(); d.update(password.getBytes()); byte[] buf = d.digest(); char[] cbf = new char[buf.length * 2]; for (int jj = 0, kk = 0; jj < buf.length; jj++) { cbf[kk++] = "0123456789abcdef".charAt((buf[jj] >> 4) & 0x0F); cbf[kk++] = "0123456789abcdef".charAt(buf[jj] & 0x0F); } return new String(cbf); } Code Sample 2: public static void BubbleSortFloat2(float[] num) { int last_exchange; int right_border = num.length - 1; do { last_exchange = 0; for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) { float temp = num[j]; num[j] = num[j + 1]; num[j + 1] = temp; last_exchange = j; } } right_border = last_exchange; } while (right_border > 0); }
11
Code Sample 1: protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/zip"); response.setHeader("Content-Disposition", "inline; filename=c:/server1.zip"); try { BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("server.zip"); ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; java.util.Properties props = new java.util.Properties(); props.load(new java.io.FileInputStream(ejb.bprocess.util.NewGenLibRoot.getRoot() + "/SystemFiles/ENV_VAR.txt")); String jbossHomePath = props.getProperty("JBOSS_HOME"); jbossHomePath = jbossHomePath.replaceAll("deploy", "log"); FileInputStream fis = new FileInputStream(new File(jbossHomePath + "/server.log")); origin = new BufferedInputStream(fis, BUFFER); ZipEntry entry = new ZipEntry(jbossHomePath + "/server.log"); zipOut.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER)) != -1) { zipOut.write(data, 0, count); } origin.close(); zipOut.closeEntry(); java.io.FileInputStream fis1 = new java.io.FileInputStream(new java.io.File("server.zip")); java.nio.channels.FileChannel fc1 = fis1.getChannel(); int length1 = (int) fc1.size(); byte buffer[] = new byte[length1]; System.out.println("size of zip file = " + length1); fis1.read(buffer); OutputStream out1 = response.getOutputStream(); out1.write(buffer); fis1.close(); out1.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: @Override public boolean identification(String username, String password) { this.getLogger().info(DbUserServiceImpl.class, ">>>identification " + username + "<<<"); try { IFeelerUser user = this.getDbServ().queryFeelerUser(username); if (user == null) { return false; } MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes()); if (user.getPassword().equals(new String(md5.digest()))) { if (!this.localUUIDList.contains(user.getUuid())) { this.localUUIDList.add(user.getUuid()); } return true; } else { return false; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public void testJDBCSavepoints() throws Exception { String sql; String msg; int i; PreparedStatement ps; ResultSet rs; Savepoint sp1; Savepoint sp2; Savepoint sp3; Savepoint sp4; Savepoint sp5; Savepoint sp6; Savepoint sp7; int rowcount = 0; sql = "drop table t if exists"; stmt.executeUpdate(sql); sql = "create table t(id int, fn varchar, ln varchar, zip int)"; stmt.executeUpdate(sql); conn1.setAutoCommit(true); conn1.setAutoCommit(false); sql = "insert into t values(?,?,?,?)"; ps = conn1.prepareStatement(sql); ps.setString(2, "Mary"); ps.setString(3, "Peterson-Clancy"); i = 0; for (; i < 10; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp1 = conn1.setSavepoint("savepoint1"); for (; i < 20; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp2 = conn1.setSavepoint("savepoint2"); for (; i < 30; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp3 = conn1.setSavepoint("savepoint3"); for (; i < 40; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp4 = conn1.setSavepoint("savepoint4"); for (; i < 50; i++) { ps.setInt(1, i); ps.setInt(4, i); ps.executeUpdate(); } sp5 = conn1.setSavepoint("savepoint5"); sp6 = conn1.setSavepoint("savepoint6"); sp7 = conn1.setSavepoint("savepoint7"); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) from t value"; try { assertEquals(msg, 50, rowcount); } catch (Exception e) { } conn2.setAutoCommit(false); conn2.setSavepoint("savepoint1"); conn2.setSavepoint("savepoint2"); msg = "savepoint released succesfully on non-originating connection"; try { conn2.releaseSavepoint(sp2); assertTrue(msg, false); } catch (Exception e) { } try { conn2.rollback(sp1); msg = "succesful rollback to savepoint on " + "non-originating connection"; assertTrue(msg, false); } catch (Exception e) { } msg = "direct execution of <release savepoint> statement failed to " + "release JDBC-created SQL-savepoint with identical savepoint name"; try { conn2.createStatement().executeUpdate("release savepoint \"savepoint2\""); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } msg = "direct execution of <rollback to savepoint> statement failed to " + "roll back to existing JDBC-created SQL-savepoint with identical " + "savepoint name"; try { conn2.createStatement().executeUpdate("rollback to savepoint \"savepoint1\""); } catch (Exception e) { e.printStackTrace(); try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.releaseSavepoint(sp6); msg = "savepoint released succesfully > 1 times"; try { conn1.releaseSavepoint(sp6); assertTrue(msg, false); } catch (Exception e) { } msg = "savepoint released successfully after preceding savepoint released"; try { conn1.releaseSavepoint(sp7); assertTrue(msg, false); } catch (Exception e) { } msg = "preceding same-point savepoint destroyed by following savepoint release"; try { conn1.releaseSavepoint(sp5); } catch (Exception e) { try { assertTrue(msg, false); } catch (Exception e2) { } } conn1.rollback(sp4); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select * rowcount after 50 inserts - 10 rolled back:"; try { assertEquals(msg, 40, rowcount); } catch (Exception e) { } msg = "savepoint rolled back succesfully > 1 times"; try { conn1.rollback(sp4); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp3); rs = stmt.executeQuery("select count(*) from t"); rs.next(); rowcount = rs.getInt(1); rs.close(); msg = "select count(*) after 50 inserts - 20 rolled back:"; try { assertEquals(msg, 30, rowcount); } catch (Exception e) { } msg = "savepoint released succesfully after use in rollback"; try { conn1.releaseSavepoint(sp3); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(sp1); msg = "savepoint rolled back without raising an exception after " + "rollback to a preceeding savepoint"; try { conn1.rollback(sp2); assertTrue(msg, false); } catch (Exception e) { } conn1.rollback(); msg = "savepoint released succesfully when it should have been " + "destroyed by a full rollback"; try { conn1.releaseSavepoint(sp1); assertTrue(msg, false); } catch (Exception e) { } conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.rollback(); conn1.setAutoCommit(false); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); conn1.setAutoCommit(false); sp1 = conn1.setSavepoint("savepoint1"); conn1.createStatement().executeUpdate("savepoint \"savepoint1\""); }
11
Code Sample 1: public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } this.currentGafFilePath = this.url; try { if (this.httpURL != null) { LOG.info("Reading URL :" + httpURL); InputStream is = this.httpURL.openStream(); int index = this.httpURL.toString().lastIndexOf('/'); String file = this.httpURL.toString().substring(index + 1); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), "tmp-" + file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); is = new FileInputStream(downloadLocation); if (url.endsWith(".gz")) { is = new GZIPInputStream(is); } this.currentGafFile = this.currentGafFilePath.substring(this.currentGafFilePath.lastIndexOf("/") + 1); this.httpURL = null; return is; } else { String file = files[counter++].getName(); this.currentGafFile = file; if (!this.currentGafFilePath.endsWith(file)) currentGafFilePath += file; LOG.info("Returning input stream for the file: " + file); _connect(); ftpClient.changeWorkingDirectory(path); InputStream is = ftpClient.retrieveFileStream(file); File downloadLocation = new File(GoConfigManager.getInstance().getGafUploadDir(), file); OutputStream out = new FileOutputStream(downloadLocation); IOUtils.copy(is, out); out.close(); System.out.println("Download complete....."); is = new FileInputStream(downloadLocation); if (file.endsWith(".gz")) { is = new GZIPInputStream(is); } return is; } } catch (IOException ex) { throw new RuntimeException(ex); } } Code Sample 2: public boolean copyFile(File source, File dest) { try { FileReader in = new FileReader(source); FileWriter out = new FileWriter(dest); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return true; } catch (Exception e) { return false; } }
11
Code Sample 1: public void copyFile(File in, File out) throws Exception { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public static 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); } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public boolean backupLastAuditSchema(File lastAuditSchema) { boolean isBkupFileOK = false; String writeTimestamp = DateFormatUtils.format(new java.util.Date(), configFile.getTimestampPattern()); File target = new File(configFile.getAuditSchemaFileDir() + File.separator + configFile.getAuditSchemaFileName() + ".bkup_" + writeTimestamp); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(lastAuditSchema).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((target != null) && (target.exists()) && (target.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } return isBkupFileOK; }
00
Code Sample 1: public String readURL(URL url) throws JasenException { OutputStream out = new ByteArrayOutputStream(); InputStream in = null; String html = null; NonBlockingStreamReader reader = null; try { in = url.openStream(); reader = new NonBlockingStreamReader(); reader.read(in, out, readBufferSize, readTimeout, null); html = new String(((ByteArrayOutputStream) out).toByteArray()); } catch (IOException e) { throw new JasenException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } return html; } Code Sample 2: public void setDefaultMailBox(final int domainId, final int userId) { final EmailAddress defaultMailbox = cmDB.getDefaultMailbox(domainId); try { connection.setAutoCommit(false); new ProcessEnvelope().executeNull(new ExecuteProcessAbstractImpl(connection, false, false, true, true) { @Override public void executeProcessReturnNull() throws SQLException { psImpl = connImpl.prepareStatement(sqlCommands.getProperty(defaultMailbox == null ? "domain.setDefaultMailbox" : "domain.updateDefaultMailbox")); if (defaultMailbox == null) { psImpl.setInt(1, domainId); psImpl.setInt(2, userId); } else { psImpl.setInt(1, userId); psImpl.setInt(2, domainId); } psImpl.executeUpdate(); } }); connection.commit(); cmDB.updateDomains(null, null); } catch (SQLException sqle) { log.error(sqle); if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { } } } finally { if (connection != null) { try { connection.setAutoCommit(true); } catch (SQLException ex) { } } } }
11
Code Sample 1: private static String connect(String apiURL, boolean secure) throws IOException { String baseUrl; if (secure) baseUrl = "https://todoist.com/API/"; else baseUrl = "http://todoist.com/API/"; URL url = new URL(baseUrl + apiURL); URLConnection c = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder toReturn = new StringBuilder(""); String toAppend; while ((toAppend = in.readLine()) != null) toReturn.append(toAppend); return toReturn.toString(); } Code Sample 2: private Component createLicensePane(String propertyKey) { if (licesePane == null) { String licenseText = ""; BufferedReader in = null; try { String filename = "conf/LICENSE.txt"; java.net.URL url = FileUtil.toURL(filename); in = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while (true) { line = in.readLine(); if (line == null) break; licenseText += line; } } catch (Exception e) { log.error(e); } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } } licenseText = StringUtils.replace(licenseText, "<br>", "\n"); licenseText = StringUtils.replace(licenseText, "<p>", "\n\n"); StyleContext context = new StyleContext(); StyledDocument document = new DefaultStyledDocument(context); Style style = context.getStyle(StyleContext.DEFAULT_STYLE); StyleConstants.setAlignment(style, StyleConstants.ALIGN_CENTER); StyleConstants.setSpaceAbove(style, 4); StyleConstants.setSpaceBelow(style, 4); StyleConstants.setFontSize(style, 14); try { document.insertString(document.getLength(), licenseText, style); } catch (BadLocationException e) { log.error(e); } JTextPane textPane = new JTextPane(document); textPane.setEditable(false); licesePane = new JScrollPane(textPane); } return licesePane; }
11
Code Sample 1: public static void main(String[] args) { if (args.length != 1) { System.out.println("Usage: GUnzip source"); return; } String zipname, source; if (args[0].endsWith(".gz")) { zipname = args[0]; source = args[0].substring(0, args[0].length() - 3); } else { zipname = args[0] + ".gz"; source = args[0]; } GZIPInputStream zipin; try { FileInputStream in = new FileInputStream(zipname); zipin = new GZIPInputStream(in); } catch (IOException e) { System.out.println("Couldn't open " + zipname + "."); return; } byte[] buffer = new byte[sChunk]; try { FileOutputStream out = new FileOutputStream(source); int length; while ((length = zipin.read(buffer, 0, sChunk)) != -1) out.write(buffer, 0, length); out.close(); } catch (IOException e) { System.out.println("Couldn't decompress " + args[0] + "."); } try { zipin.close(); } catch (IOException e) { } } Code Sample 2: private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { if (destFile.exists() && destFile.isDirectory()) { throw new IOException("Destination '" + destFile + "' exists but is a directory"); } FileInputStream input = new FileInputStream(srcFile); try { FileOutputStream output = new FileOutputStream(destFile); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } if (srcFile.length() != destFile.length()) { throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); } if (preserveFileDate) { destFile.setLastModified(srcFile.lastModified()); } }
00
Code Sample 1: private void copyFiles(File oldFolder, File newFolder) { for (File fileToCopy : oldFolder.listFiles()) { File copiedFile = new File(newFolder.getAbsolutePath() + "\\" + fileToCopy.getName()); try { FileInputStream source = new FileInputStream(fileToCopy); FileOutputStream destination = new FileOutputStream(copiedFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); long size = sourceFileChannel.size(); sourceFileChannel.transferTo(0, size, destinationFileChannel); source.close(); destination.close(); } catch (Exception exc) { exc.printStackTrace(); } } } Code Sample 2: public static int sendButton(String url, String id, String command) throws ClientProtocolException, IOException { String connectString = url + "/rest/button/" + id + "/" + command; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(connectString); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); return code; }
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 JavaCodeAnalyzer(String filenameIn, String filenameOut, String lineLength) { try { File tmp = File.createTempFile("JavaCodeAnalyzer", "tmp"); BufferedReader br = new BufferedReader(new FileReader(filenameIn)); BufferedWriter out = new BufferedWriter(new FileWriter(tmp)); while (br.ready()) { out.write(br.read()); } br.close(); out.close(); jco = new JavaCodeOutput(tmp, filenameOut, lineLength); SourceCodeParser p = new JavaCCParserFactory().createParser(new FileReader(tmp), null); List statements = p.parseCompilationUnit(); ListIterator it = statements.listIterator(); eh = new ExpressionHelper(this, jco); Node n; printLog("Parsed file " + filenameIn + "\n"); while (it.hasNext()) { n = (Node) it.next(); parseObject(n); } tmp.delete(); } catch (Exception e) { System.err.println(getClass() + ": " + e); } }
11
Code Sample 1: public static final int executeSql(final Connection conn, final String sql, final boolean rollback) throws SQLException { if (null == sql) return 0; Statement stmt = null; try { stmt = conn.createStatement(); final int updated = stmt.executeUpdate(sql); return updated; } catch (final SQLException e) { if (rollback) conn.rollback(); throw e; } finally { closeAll(null, stmt, null); } } Code Sample 2: @Override public final boolean delete() throws RecordException { if (frozen) { throw new RecordException("The object is frozen."); } Connection conn = ConnectionManager.getConnection(); LoggableStatement pStat = null; Class<? extends Record> actualClass = this.getClass(); StatementBuilder builder = null; try { builder = new StatementBuilder("delete from " + TableNameResolver.getTableName(actualClass) + " where id = :id"); Field f = FieldHandler.findField(this.getClass(), "id"); builder.set("id", FieldHandler.getValue(f, this)); pStat = builder.getPreparedStatement(conn); log.log(pStat.getQueryString()); int i = pStat.executeUpdate(); return i == 1; } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { throw new RecordException("Error executing rollback"); } throw new RecordException(e); } finally { try { if (pStat != null) { pStat.close(); } conn.commit(); conn.close(); } catch (SQLException e) { throw new RecordException("Error closing connection"); } } }
00
Code Sample 1: public RFC1345List(URL url) { if (url == null) return; try { BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream()))); final String linePattern = " XX??????? HHHH X"; String line; mnemos = new HashMap(); nextline: while ((line = br.readLine()) != null) { if (line.length() < 9) continue nextline; if (line.charAt(7) == ' ' || line.charAt(8) != ' ') { line = line.substring(0, 8) + " " + line.substring(8); } if (line.length() < linePattern.length()) continue nextline; for (int i = 0; i < linePattern.length(); i++) { char c = line.charAt(i); switch(linePattern.charAt(i)) { case ' ': if (c != ' ') continue nextline; break; case 'X': if (c == ' ') continue nextline; break; case '?': break; case 'H': if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) ; else continue nextline; break; default: throw new RuntimeException("Pattern broken!"); } } char c = (char) Integer.parseInt(line.substring(16, 20), 16); String mnemo = line.substring(1, 16).trim(); if (mnemo.length() < 2) throw new RuntimeException(); mnemos.put(mnemo, new Character(c)); } br.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { ex.printStackTrace(); } } Code Sample 2: public String readFile(String filename) throws UnsupportedEncodingException, FileNotFoundException, IOException { File f = new File(baseDir); f = new File(f, filename); StringWriter w = new StringWriter(); Reader fr = new InputStreamReader(new FileInputStream(f), "UTF-8"); IOUtils.copy(fr, w); fr.close(); w.close(); String contents = w.toString(); return contents; }
11
Code Sample 1: private static String getSummaryText(File packageFile) { String retVal = null; Reader in = null; try { in = new FileReader(packageFile); StringWriter out = new StringWriter(); IOUtils.copy(in, out); StringBuffer buf = out.getBuffer(); int pos1 = buf.indexOf("<body>"); int pos2 = buf.lastIndexOf("</body>"); if (pos1 >= 0 && pos1 < pos2) { retVal = buf.substring(pos1 + 6, pos2); } else { retVal = ""; } } catch (FileNotFoundException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } return retVal; } Code Sample 2: public java.io.File gzip(java.io.File file) throws Exception { java.io.File tmp = null; InputStream is = null; OutputStream os = null; try { tmp = java.io.File.createTempFile(file.getName(), ".gz"); tmp.deleteOnExit(); is = new BufferedInputStream(new FileInputStream(file)); os = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(tmp))); byte[] buf = new byte[4096]; int nread = -1; while ((nread = is.read(buf)) != -1) { os.write(buf, 0, nread); } os.flush(); } finally { os.close(); is.close(); } return tmp; }
11
Code Sample 1: public static void main(String[] argv) throws IOException { int i; for (i = 0; i < argv.length; i++) { if (argv[i].charAt(0) != '-') break; ++i; switch(argv[i - 1].charAt(1)) { case 'b': try { flag_predict_probability = (atoi(argv[i]) != 0); } catch (NumberFormatException e) { exit_with_help(); } break; default: System.err.printf("unknown option: -%d%n", argv[i - 1].charAt(1)); exit_with_help(); break; } } if (i >= argv.length || argv.length <= i + 2) { exit_with_help(); } BufferedReader reader = null; Writer writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(argv[i]), Linear.FILE_CHARSET)); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(argv[i + 2]), Linear.FILE_CHARSET)); Model model = Linear.loadModel(new File(argv[i + 1])); doPredict(reader, writer, model); } finally { closeQuietly(reader); closeQuietly(writer); } } Code Sample 2: public static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
00
Code Sample 1: private void checkUrl(URL url) throws IOException { File urlFile = new File(url.getFile()); assertEquals(file.getCanonicalPath(), urlFile.getCanonicalPath()); System.out.println("Using url " + url); InputStream openStream = url.openStream(); assertNotNull(openStream); } Code Sample 2: public static boolean insert(final Departamento ObjDepartamento) { int result = 0; final Connection c = DBConnection.getConnection(); PreparedStatement pst = null; if (c == null) { return false; } try { c.setAutoCommit(false); final String sql = "insert into departamento " + "(nome, sala, telefone, id_orgao)" + " values (?, ?, ?, ?)"; pst = c.prepareStatement(sql); pst.setString(1, ObjDepartamento.getNome()); pst.setString(2, ObjDepartamento.getSala()); pst.setString(3, ObjDepartamento.getTelefone()); pst.setInt(4, (ObjDepartamento.getOrgao()).getCodigo()); result = pst.executeUpdate(); c.commit(); } catch (final SQLException e) { try { c.rollback(); } catch (final SQLException e1) { e1.printStackTrace(); } System.out.println("[DepartamentoDAO.insert] Erro ao inserir -> " + e.getMessage()); } finally { DBConnection.closePreparedStatement(pst); DBConnection.closeConnection(c); } if (result > 0) { return true; } else { return false; } }
00
Code Sample 1: public BufferedImage extract() throws DjatokaException { boolean useRegion = false; int left = 0; int top = 0; int width = 50; int height = 50; boolean useleftDouble = false; Double leftDouble = 0.0; boolean usetopDouble = false; Double topDouble = 0.0; boolean usewidthDouble = false; Double widthDouble = 0.0; boolean useheightDouble = false; Double heightDouble = 0.0; if (params.getRegion() != null) { StringTokenizer st = new StringTokenizer(params.getRegion(), "{},"); String token; if ((token = st.nextToken()).contains(".")) { topDouble = Double.parseDouble(token); usetopDouble = true; } else top = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { leftDouble = Double.parseDouble(token); useleftDouble = true; } else left = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { heightDouble = Double.parseDouble(token); useheightDouble = true; } else height = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { widthDouble = Double.parseDouble(token); usewidthDouble = true; } else width = Integer.parseInt(token); useRegion = true; } try { if (is != null) { File f = File.createTempFile("tmp", ".jp2"); f.deleteOnExit(); FileOutputStream fos = new FileOutputStream(f); sourceFile = f.getAbsolutePath(); IOUtils.copyStream(is, fos); is.close(); fos.close(); } } catch (IOException e) { throw new DjatokaException(e); } try { Jp2_source inputSource = new Jp2_source(); Kdu_compressed_source input = null; Jp2_family_src jp2_family_in = new Jp2_family_src(); Jp2_locator loc = new Jp2_locator(); jp2_family_in.Open(sourceFile, true); inputSource.Open(jp2_family_in, loc); inputSource.Read_header(); input = inputSource; Kdu_codestream codestream = new Kdu_codestream(); codestream.Create(input); Kdu_channel_mapping channels = new Kdu_channel_mapping(); if (inputSource.Exists()) channels.Configure(inputSource, false); else channels.Configure(codestream); int ref_component = channels.Get_source_component(0); Kdu_coords ref_expansion = getReferenceExpansion(ref_component, channels, codestream); Kdu_dims image_dims = new Kdu_dims(); codestream.Get_dims(ref_component, image_dims); Kdu_coords imageSize = image_dims.Access_size(); Kdu_coords imagePosition = image_dims.Access_pos(); if (useleftDouble) left = imagePosition.Get_x() + (int) Math.round(leftDouble * imageSize.Get_x()); if (usetopDouble) top = imagePosition.Get_y() + (int) Math.round(topDouble * imageSize.Get_y()); if (useheightDouble) height = (int) Math.round(heightDouble * imageSize.Get_y()); if (usewidthDouble) width = (int) Math.round(widthDouble * imageSize.Get_x()); if (useRegion) { imageSize.Set_x(width); imageSize.Set_y(height); imagePosition.Set_x(left); imagePosition.Set_y(top); } int reduce = 1 << params.getLevelReductionFactor(); imageSize.Set_x(imageSize.Get_x() * ref_expansion.Get_x()); imageSize.Set_y(imageSize.Get_y() * ref_expansion.Get_y()); imagePosition.Set_x(imagePosition.Get_x() * ref_expansion.Get_x() / reduce - ((ref_expansion.Get_x() / reduce - 1) / 2)); imagePosition.Set_y(imagePosition.Get_y() * ref_expansion.Get_y() / reduce - ((ref_expansion.Get_y() / reduce - 1) / 2)); Kdu_dims view_dims = new Kdu_dims(); view_dims.Assign(image_dims); view_dims.Access_size().Set_x(imageSize.Get_x()); view_dims.Access_size().Set_y(imageSize.Get_y()); int region_buf_size = imageSize.Get_x() * imageSize.Get_y(); int[] region_buf = new int[region_buf_size]; Kdu_region_decompressor decompressor = new Kdu_region_decompressor(); decompressor.Start(codestream, channels, -1, params.getLevelReductionFactor(), 16384, image_dims, ref_expansion, new Kdu_coords(1, 1), false, Kdu_global.KDU_WANT_OUTPUT_COMPONENTS); Kdu_dims new_region = new Kdu_dims(); Kdu_dims incomplete_region = new Kdu_dims(); Kdu_coords viewSize = view_dims.Access_size(); incomplete_region.Assign(image_dims); int[] imgBuffer = new int[viewSize.Get_x() * viewSize.Get_y()]; int[] kduBuffer = null; while (decompressor.Process(region_buf, image_dims.Access_pos(), 0, 0, region_buf_size, incomplete_region, new_region)) { Kdu_coords newOffset = new_region.Access_pos(); Kdu_coords newSize = new_region.Access_size(); newOffset.Subtract(view_dims.Access_pos()); kduBuffer = region_buf; int imgBuffereIdx = newOffset.Get_x() + newOffset.Get_y() * viewSize.Get_x(); int kduBufferIdx = 0; int xDiff = viewSize.Get_x() - newSize.Get_x(); for (int j = 0; j < newSize.Get_y(); j++, imgBuffereIdx += xDiff) { for (int i = 0; i < newSize.Get_x(); i++) { imgBuffer[imgBuffereIdx++] = kduBuffer[kduBufferIdx++]; } } } BufferedImage image = new BufferedImage(imageSize.Get_x(), imageSize.Get_y(), BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, viewSize.Get_x(), viewSize.Get_y(), imgBuffer, 0, viewSize.Get_x()); if (params.getRotationDegree() > 0) { image = ImageProcessingUtils.rotate(image, params.getRotationDegree()); } decompressor.Native_destroy(); channels.Native_destroy(); if (codestream.Exists()) codestream.Destroy(); inputSource.Native_destroy(); input.Native_destroy(); jp2_family_in.Native_destroy(); return image; } catch (KduException e) { e.printStackTrace(); throw new DjatokaException(e); } catch (Exception e) { e.printStackTrace(); throw new DjatokaException(e); } } Code Sample 2: public static void main(String[] args) { URL url = Thread.currentThread().getContextClassLoader().getResource("org/jeditor/resources/jeditor.properties"); try { PropertyResourceBundle prb = new PropertyResourceBundle(url.openStream()); String version = prb.getString("version"); String date = prb.getString("date"); System.out.println("jEditor version " + version + " build on " + date); System.out.println("Distributed under GPL license"); } catch (IOException ex) { ex.printStackTrace(); } }
11
Code Sample 1: public boolean moveFileSafely(final File in, final File out) throws IOException { FileInputStream fis = null; FileOutputStream fos = null; FileChannel inChannel = null; FileChannel outChannel = null; final File tempOut = File.createTempFile("move", ".tmp"); try { fis = new FileInputStream(in); fos = new FileOutputStream(tempOut); inChannel = fis.getChannel(); outChannel = fos.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); } finally { try { if (inChannel != null) inChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", inChannel); } try { if (outChannel != null) outChannel.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close channel %s", outChannel); } try { if (fis != null) fis.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fis); } try { if (fos != null) fos.close(); } catch (IOException e) { LogUtils.debugf(JRobinConverter.class, "failed to close stream %s", fos); } } out.delete(); if (!out.exists()) { tempOut.renameTo(out); return in.delete(); } return false; } Code Sample 2: public static void TestDBStore() throws PDException, Exception { StoreDDBB StDB = new StoreDDBB("jdbc:derby://localhost:1527/Prodoc", "Prodoc", "Prodoc", "org.apache.derby.jdbc.ClientDriver;STBLOB"); System.out.println("Driver[" + StDB.getDriver() + "] Tabla [" + StDB.getTable() + "]"); StDB.Connect(); FileInputStream in = new FileInputStream("/tmp/readme.htm"); StDB.Insert("12345678-1", "1.0", in); int TAMBUFF = 1024 * 64; byte Buffer[] = new byte[TAMBUFF]; InputStream Bytes; Bytes = StDB.Retrieve("12345678-1", "1.0"); FileOutputStream fo = new FileOutputStream("/tmp/12345679.htm"); int readed = Bytes.read(Buffer); while (readed != -1) { fo.write(Buffer, 0, readed); readed = Bytes.read(Buffer); } Bytes.close(); fo.close(); StDB.Delete("12345678-1", "1.0"); StDB.Disconnect(); }
00
Code Sample 1: public int read(String name) { status = STATUS_OK; try { name = name.trim(); if (name.indexOf("://") > 0) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; } Code Sample 2: public void run() { try { status = UploadStatus.INITIALISING; if (megaUploadAccount.loginsuccessful) { login = true; host = megaUploadAccount.username + " | MegaUpload.com"; } else { login = false; host = "MegaUpload.com"; } initialize(); HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); filelength = file.length(); generateMegaUploadID(); if (login) { status = UploadStatus.GETTINGCOOKIE; usercookie = MegaUploadAccount.getUserCookie(); postURL = megauploadlink + "upload_done.php?UPLOAD_IDENTIFIER=" + uploadID + "&" + usercookie + "&s=" + filelength; } else { postURL = megauploadlink + "upload_done.php?UPLOAD_IDENTIFIER=" + uploadID + "&user=undefined&s=" + filelength; } HttpPost httppost = new HttpPost(postURL); httppost.setHeader("Cookie", usercookie); MultipartEntity mpEntity = new MultipartEntity(); mpEntity.addPart("", new MonitoredFileBody(file, uploadProgress)); httppost.setEntity(mpEntity); NULogger.getLogger().info("Now uploading your file into megaupload..........................."); status = UploadStatus.UPLOADING; HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); NULogger.getLogger().info(response.getStatusLine().toString()); if (resEntity != null) { status = UploadStatus.GETTINGLINK; downloadlink = EntityUtils.toString(resEntity); downloadlink = CommonUploaderTasks.parseResponse(downloadlink, "downloadurl = '", "'"); downURL = downloadlink; NULogger.getLogger().log(Level.INFO, "Download Link : {0}", downURL); uploadFinished(); } } catch (Exception ex) { Logger.getLogger(MegaUpload.class.getName()).log(Level.SEVERE, null, ex); uploadFailed(); } }
00
Code Sample 1: private boolean tryGet(String url, Hashtable<String, String> req) throws Exception { boolean result = false; Enumeration<String> keys = req.keys(); String key; String value; String data = ""; while (keys.hasMoreElements()) { key = keys.nextElement(); value = req.get(key); data += URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8") + "&"; } URLConnection conn = new URL(url).openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line != null) result = true; } wr.close(); rd.close(); result = true; return result; } Code Sample 2: public static void extractFile(String jarArchive, String fileToExtract, String destination) { FileWriter writer = null; ZipInputStream zipStream = null; try { FileInputStream inputStream = new FileInputStream(jarArchive); BufferedInputStream bufferedStream = new BufferedInputStream(inputStream); zipStream = new ZipInputStream(bufferedStream); writer = new FileWriter(new File(destination)); ZipEntry zipEntry = null; while ((zipEntry = zipStream.getNextEntry()) != null) { if (zipEntry.getName().equals(fileToExtract)) { int size = (int) zipEntry.getSize(); for (int i = 0; i < size; i++) { writer.write(zipStream.read()); } } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipStream != null) try { zipStream.close(); } catch (IOException e) { e.printStackTrace(); } if (writer != null) try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }
11
Code Sample 1: public String getDigest(String algorithm, String data) throws IOException, NoSuchAlgorithmException { MessageDigest md = java.security.MessageDigest.getInstance(algorithm); md.reset(); md.update(data.getBytes()); return md.digest().toString(); } Code Sample 2: public static String MD5Digest(String source) { MessageDigest digest; try { digest = java.security.MessageDigest.getInstance("MD5"); digest.update(source.getBytes("UTF8")); byte[] hash = digest.digest(); String strHash = byteArrayToHexString(hash); return strHash; } catch (NoSuchAlgorithmException e) { String msg = "%s: %s"; msg = String.format(msg, e.getClass().getName(), e.getMessage()); logger.error(msg); return null; } catch (UnsupportedEncodingException e) { String msg = "%s: %s"; msg = String.format(msg, e.getClass().getName(), e.getMessage()); logger.error(msg); return null; } }
11
Code Sample 1: public static void copyFile(String original, String destination) throws Exception { File original_file = new File(original); File destination_file = new File(destination); if (!original_file.exists()) throw new Exception("File with path " + original + " does not exist."); if (destination_file.exists()) throw new Exception("File with path " + destination + " already exists."); FileReader in = new FileReader(original_file); FileWriter out = new FileWriter(destination_file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public static void copyFile(final File in, final File out) throws IOException { final FileChannel inChannel = new FileInputStream(in).getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) { inChannel.close(); } if (outChannel != null) { outChannel.close(); } } }
00
Code Sample 1: public boolean checkConnection() { int tries = 3; for (int i = 0; i < tries; i++) { try { final URL url = new URL(wsURL); final URLConnection conn = url.openConnection(); conn.setReadTimeout(3000); conn.getContent(); return true; } catch (IOException ex) { Logger.getLogger(ExternalSalesHelper.class.getName()).log(Level.SEVERE, null, ex); } try { Thread.currentThread().sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(OrdersSync.class.getName()).log(Level.SEVERE, null, ex); } } return false; } Code Sample 2: String chooseHGVersion(String version) { String line = ""; try { URL connectURL = new URL("http://genome.ucsc.edu/cgi-bin/hgGateway?db=" + version); InputStream urlStream = connectURL.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(urlStream)); while ((line = reader.readLine()) != null) { if (line.indexOf("hgsid") != -1) { line = line.substring(line.indexOf("hgsid")); line = line.substring(line.indexOf("VALUE=\"") + 7); line = line.substring(0, line.indexOf("\"")); return line; } } } catch (Exception e) { e.printStackTrace(); } return line; }
11
Code Sample 1: public 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: protected void createFile(File sourceActionDirectory, File destinationActionDirectory, LinkedList<String> segments) throws DuplicateActionFileException { File currentSrcDir = sourceActionDirectory; File currentDestDir = destinationActionDirectory; String segment = ""; for (int i = 0; i < segments.size() - 1; i++) { segment = segments.get(i); currentSrcDir = new File(currentSrcDir, segment); currentDestDir = new File(currentDestDir, segment); } if (currentSrcDir != null && currentDestDir != null) { File srcFile = new File(currentSrcDir, segments.getLast()); if (srcFile.exists()) { File destFile = new File(currentDestDir, segments.getLast()); if (destFile.exists()) { throw new DuplicateActionFileException(srcFile.toURI().toASCIIString()); } try { FileChannel srcChannel = new FileInputStream(srcFile).getChannel(); FileChannel destChannel = new FileOutputStream(destFile).getChannel(); ByteBuffer buffer = ByteBuffer.allocate((int) srcChannel.size()); while (srcChannel.position() < srcChannel.size()) { srcChannel.read(buffer); } srcChannel.close(); buffer.rewind(); destChannel.write(buffer); destChannel.close(); } catch (Exception ex) { ex.printStackTrace(); } } } }
11
Code Sample 1: private ByteBuffer readProgram(URL url) throws IOException { StringBuilder program = new StringBuilder(); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = in.readLine()) != null) { program.append(line).append("\n"); } } finally { if (in != null) in.close(); } ByteBuffer buffer = BufferUtils.createByteBuffer(program.length()); for (int i = 0; i < program.length(); i++) { buffer.put((byte) (program.charAt(i) & 0xFF)); } buffer.flip(); return buffer; } Code Sample 2: void loadSVG(String svgFileURL) { try { URL url = new URL(svgFileURL); URLConnection c = url.openConnection(); c.setRequestProperty("Accept-Encoding", "gzip"); InputStream is = c.getInputStream(); String encoding = c.getContentEncoding(); if ("gzip".equals(encoding) || "x-gzip".equals(encoding) || svgFileURL.toLowerCase().endsWith(".svgz")) { is = new GZIPInputStream(is); } is = new BufferedInputStream(is); Document svgDoc = AppletUtils.parse(is, false); if (svgDoc != null) { if (grMngr.mainView.isBlank() == null) { grMngr.mainView.setBlank(cfgMngr.backgroundColor); } SVGReader.load(svgDoc, grMngr.mSpace, true, svgFileURL); grMngr.seekBoundingBox(); grMngr.buildLogicalStructure(); ConfigManager.defaultFont = VText.getMainFont(); grMngr.reveal(); if (grMngr.previousLocations.size() == 1) { grMngr.previousLocations.removeElementAt(0); } if (grMngr.rView != null) { grMngr.rView.getGlobalView(grMngr.mSpace.getCamera(1), 100); } grMngr.cameraMoved(null, null, 0); } else { System.err.println("An error occured while loading file " + svgFileURL); } } catch (Exception ex) { grMngr.reveal(); ex.printStackTrace(); } }
00
Code Sample 1: public Long createSite(Site site, List<String> hosts) { if (log.isDebugEnabled()) { log.debug("site: " + site); if (site != null) { log.debug(" language: " + site.getDefLanguage()); log.debug(" country: " + site.getDefCountry()); log.debug(" variant: " + site.getDefVariant()); log.debug(" companyId: " + site.getCompanyId()); } } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_PORTAL_LIST_SITE"); seq.setTableName("WM_PORTAL_LIST_SITE"); seq.setColumnName("ID_SITE"); Long siteId = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_PORTAL_LIST_SITE (" + "ID_SITE, ID_FIRM, DEF_LANGUAGE, DEF_COUNTRY, DEF_VARIANT, " + "NAME_SITE, ADMIN_EMAIL, IS_CSS_DYNAMIC, CSS_FILE, " + "IS_REGISTER_ALLOWED " + ")values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ?," + " ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, siteId); RsetTools.setLong(ps, num++, site.getCompanyId()); ps.setString(num++, site.getDefLanguage()); ps.setString(num++, site.getDefCountry()); ps.setString(num++, site.getDefVariant()); ps.setString(num++, site.getSiteName()); ps.setString(num++, site.getAdminEmail()); ps.setInt(num++, site.getCssDynamic() ? 1 : 0); ps.setString(num++, site.getCssFile()); ps.setInt(num++, site.getRegisterAllowed() ? 1 : 0); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); if (hosts != null) { for (String s : hosts) { VirtualHost host = new VirtualHostBean(null, siteId, s); InternalDaoFactory.getInternalVirtualHostDao().createVirtualHost(dbDyn, host); } } dbDyn.commit(); return siteId; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new site"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } } Code Sample 2: public static int sendButton(String url, String id, String command) throws ClientProtocolException, IOException { String connectString = url + "/rest/button/" + id + "/" + command; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(connectString); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); return code; }
00
Code Sample 1: private static Map loadHandlerList(final String resourceName, ClassLoader loader) { if (loader == null) loader = ClassLoader.getSystemClassLoader(); final Map result = new HashMap(); try { final Enumeration resources = loader.getResources(resourceName); if (resources != null) { while (resources.hasMoreElements()) { final URL url = (URL) resources.nextElement(); final Properties mapping; InputStream urlIn = null; try { urlIn = url.openStream(); mapping = new Properties(); mapping.load(urlIn); } catch (IOException ioe) { continue; } finally { if (urlIn != null) try { urlIn.close(); } catch (Exception ignore) { } } for (Enumeration keys = mapping.propertyNames(); keys.hasMoreElements(); ) { final String protocol = (String) keys.nextElement(); final String implClassName = mapping.getProperty(protocol); final Object currentImpl = result.get(protocol); if (currentImpl != null) { if (implClassName.equals(currentImpl.getClass().getName())) continue; else throw new IllegalStateException("duplicate " + "protocol handler class [" + implClassName + "] for protocol " + protocol); } result.put(protocol, loadURLStreamHandler(implClassName, loader)); } } } } catch (IOException ignore) { } return result; } Code Sample 2: public static void copyFile(File sourceFile, File destFile) { FileChannel source = null; FileChannel destination = null; try { if (!destFile.exists()) { destFile.createNewFile(); } source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } catch (Exception e) { e.printStackTrace(); } } }
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 String execute(HttpServletRequest request, HttpServletResponse response, User user, String parameter) throws Exception { long resourceId = ServletRequestUtils.getLongParameter(request, "resourceId", 0L); BinaryAttribute binaryAttribute = resourceManager.readAttribute(resourceId, parameter, user); response.addHeader("Content-Disposition", "attachment; filename=\"" + binaryAttribute.getName() + '"'); String contentType = binaryAttribute.getContentType(); if (contentType != null) { if ("application/x-zip-compressed".equalsIgnoreCase(contentType)) { response.setContentType("application/octet-stream"); } else { response.setContentType(contentType); } } else { response.setContentType("application/octet-stream"); } IOUtils.copy(binaryAttribute.getInputStream(), response.getOutputStream()); return null; }
00
Code Sample 1: public static SpeciesTree create(String url) throws IOException { SpeciesTree tree = new SpeciesTree(); tree.setUrl(url); System.out.println("Fetching URL: " + url); BufferedReader in = new BufferedReader(new InputStreamReader(new URL(url).openStream())); String toParse = null; Properties properties = new Properties(); properties.load(in); String line = properties.getProperty("TREE"); if (line == null) return null; int end = line.indexOf(';'); if (end < 0) end = line.length(); toParse = line.substring(0, end).trim(); System.out.print("Parsing... "); parse(tree, toParse, properties); return tree; } Code Sample 2: public static void main(String[] args) throws Exception { System.out.println("Opening destination cbrout.jizz"); OutputStream out = new BufferedOutputStream(new FileOutputStream("cbrout.jizz")); System.out.println("Opening source output.jizz"); InputStream in = new CbrLiveStream(new BufferedInputStream(new FileInputStream("output.jizz")), System.currentTimeMillis() + 10000, 128); System.out.println("Starting read/write loop"); boolean started = false; int len; byte[] buf = new byte[4 * 1024]; while ((len = in.read(buf)) > -1) { if (!started) { System.out.println("Starting at " + new Date()); started = true; } out.write(buf, 0, len); } System.out.println("Finished at " + new Date()); out.close(); in.close(); }
11
Code Sample 1: public static final void copy(String source, String destination) { BufferedInputStream from = null; BufferedOutputStream to = null; try { from = new BufferedInputStream(new FileInputStream(source)); to = new BufferedOutputStream(new FileOutputStream(destination)); byte[] buffer = new byte[65535]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " copying file"); } try { to.close(); from.close(); } catch (Exception e) { LogWriter.writeLog("Exception " + e + " closing files"); } } Code Sample 2: public static void sendSimpleHTMLMessage(Map<String, String> recipients, String object, String htmlContent, String from) { String message; try { File webinfDir = ClasspathUtils.getClassesDir().getParentFile(); File mailDir = new File(webinfDir, "mail"); File templateFile = new File(mailDir, "HtmlMessageTemplate.html"); StringWriter sw = new StringWriter(); Reader r = new BufferedReader(new FileReader(templateFile)); IOUtils.copy(r, sw); sw.close(); message = sw.getBuffer().toString(); message = message.replaceAll("%MESSAGE_HTML%", htmlContent).replaceAll("%APPLICATION_URL%", FGDSpringUtils.getExternalServerURL()); } catch (IOException e) { throw new RuntimeException(e); } Properties prop = getRealSMTPServerProperties(); if (prop != null) { try { MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(message, "text/html"); multipart.addBodyPart(messageBodyPart); sendHTML(recipients, object, multipart, from); } catch (MessagingException e) { throw new RuntimeException(e); } } else { StringBuffer contenuCourriel = new StringBuffer(); for (Entry<String, String> recipient : recipients.entrySet()) { if (recipient.getValue() == null) { contenuCourriel.append("À : " + recipient.getKey()); } else { contenuCourriel.append("À : " + recipient.getValue() + "<" + recipient.getKey() + ">"); } contenuCourriel.append("\n"); } contenuCourriel.append("Sujet : " + object); contenuCourriel.append("\n"); contenuCourriel.append("Message : "); contenuCourriel.append("\n"); contenuCourriel.append(message); } }
00
Code Sample 1: @Override public void checkConnection(byte[] options) throws Throwable { Properties opts = PropertiesUtils.deserializeProperties(options); String server = opts.getProperty(TRANSFER_OPTION_SERVER); String username = opts.getProperty(TRANSFER_OPTION_USERNAME); String password = opts.getProperty(TRANSFER_OPTION_PASSWORD); String filePath = opts.getProperty(TRANSFER_OPTION_FILEPATH); URL url = new URL(PROTOCOL_PREFIX + username + ":" + password + "@" + server + filePath + ";type=i"); URLConnection urlc = url.openConnection(BackEnd.getProxy(Proxy.Type.SOCKS)); urlc.setConnectTimeout(Preferences.getInstance().preferredTimeOut * 1000); urlc.setReadTimeout(Preferences.getInstance().preferredTimeOut * 1000); urlc.connect(); } Code Sample 2: public boolean setDeleteCliente(int IDcliente) { boolean delete = false; try { stm = conexion.prepareStatement("delete clientes where IDcliente='" + IDcliente + "'"); stm.executeUpdate(); conexion.commit(); delete = true; } catch (SQLException e) { System.out.println("Error en la eliminacion del registro en tabla clientes " + e.getMessage()); try { conexion.rollback(); } catch (SQLException ee) { System.out.println(ee.getMessage()); } return delete = false; } return delete; }
00
Code Sample 1: public static String getSignature(String s) { try { final AsciiEncoder coder = new AsciiEncoder(); final MessageDigest msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(s.getBytes("UTF-8")); final byte[] digest = msgDigest.digest(); return coder.encode(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new IllegalStateException(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new IllegalStateException(); } } 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(); }
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 String[] putFECSplitFile(String uri, File file, int htl, boolean mode) { FcpFECUtils fecutils = null; Vector segmentHeaders = null; Vector segmentFileMaps = new Vector(); Vector checkFileMaps = new Vector(); Vector segmentKeyMaps = new Vector(); Vector checkKeyMaps = new Vector(); int fileLength = (int) file.length(); String output = new String(); int maxThreads = frame1.frostSettings.getIntValue("splitfileUploadThreads"); Thread[] chunkThreads = null; String[][] chunkResults = null; Thread[] checkThreads = null; String[][] checkResults = null; int threadCount = 0; String board = getBoard(file); { fecutils = new FcpFECUtils(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getIntValue("nodePort")); synchronized (fecutils.getClass()) { try { segmentHeaders = fecutils.FECSegmentFile("OnionFEC_a_1_2", fileLength); } catch (Exception e) { } } int chunkCnt = 0; int checkCnt = 0; synchronized (fecutils.getClass()) { try { Socket fcpSock; BufferedInputStream fcpIn; PrintStream fcpOut; for (int i = 0; i < segmentHeaders.size(); i++) { int blockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount; int blockNo = 0; fcpSock = new Socket(InetAddress.getByName(frame1.frostSettings.getValue("nodeAddress")), frame1.frostSettings.getIntValue("nodePort")); fcpSock.setSoTimeout(1800000); fcpOut = new PrintStream(fcpSock.getOutputStream()); fcpIn = new BufferedInputStream(fcpSock.getInputStream()); FileInputStream fileIn = new FileInputStream(file); File[] chunkFiles = new File[blockCount]; { System.out.println("Processing segment " + i); fileIn.skip(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset); long segLength = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockCount * ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize; System.out.println("segLength = " + Long.toHexString(segLength)); String headerString = "SegmentHeader\n" + ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).reconstruct() + "EndMessage\n"; String dataHeaderString = "\0\0\0\2FECEncodeSegment\nMetadataLength=" + Long.toHexString(headerString.length()) + "\nDataLength=" + Long.toHexString(headerString.length() + segLength) + "\nData\n" + headerString; System.out.print(dataHeaderString); fcpOut.print(dataHeaderString); long count = 0; while (count < segLength) { byte[] buffer = new byte[(int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).BlockSize]; System.out.println(Long.toHexString(((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).Offset + count)); int inbytes = fileIn.read(buffer); if (inbytes < 0) { System.out.println("End of input file - no data"); for (int j = 0; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes < buffer.length) { System.out.println("End of input file - not enough data"); for (int j = inbytes; j < buffer.length; j++) buffer[j] = 0; inbytes = buffer.length; } if (inbytes > segLength - count) inbytes = (int) (segLength - count); fcpOut.write(buffer); File uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-" + chunkCnt + ".tmp"); chunkFiles[blockNo] = uploadMe; uploadMe.deleteOnExit(); FileOutputStream fileOut = new FileOutputStream(uploadMe); fileOut.write(buffer, 0, (int) inbytes); fileOut.close(); count += inbytes; chunkCnt++; ; blockNo++; if (blockNo >= blockCount) break; } segmentFileMaps.add(chunkFiles); fcpOut.flush(); fileIn.close(); } int checkNo = 0; int checkBlockCount = (int) ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockCount; File[] checkFiles = new File[checkBlockCount]; File uploadMe = null; FileOutputStream outFile = null; { String currentLine; long checkBlockSize = ((FcpFECUtilsSegmentHeader) segmentHeaders.get(i)).CheckBlockSize; int checkPtr = 0; int length = 0; do { boolean started = false; currentLine = fecutils.getLine(fcpIn).trim(); if (currentLine.equals("DataChunk")) { started = true; } if (currentLine.startsWith("Length=")) { length = Integer.parseInt((currentLine.split("="))[1], 16); } if (currentLine.equals("Data")) { int currentRead; byte[] buffer = new byte[(int) length]; if (uploadMe == null) { uploadMe = new File(frame1.keypool + String.valueOf(System.currentTimeMillis()) + "-chk-" + checkCnt + ".tmp"); uploadMe.deleteOnExit(); outFile = new FileOutputStream(uploadMe); } currentRead = fcpIn.read(buffer); while (currentRead < length) { currentRead += fcpIn.read(buffer, currentRead, length - currentRead); } outFile.write(buffer); checkPtr += currentRead; if (checkPtr == checkBlockSize) { outFile.close(); checkFiles[checkNo] = uploadMe; uploadMe = null; checkNo++; checkCnt++; checkPtr = 0; } } } while (currentLine.length() > 0); checkFileMaps.add(checkFiles); } fcpOut.close(); fcpIn.close(); fcpSock.close(); } } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } int chunkNo = 0; int uploadedBytes = 0; for (int i = 0; i < segmentFileMaps.size(); i++) { File[] currentFileMap = (File[]) segmentFileMaps.get(i); chunkThreads = new Thread[currentFileMap.length]; chunkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Chunk: " + chunkNo); while (getActiveThreads(chunkThreads) >= maxThreads) mixed.wait(5000); chunkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, chunkResults, threadCount, mode); chunkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); chunkNo++; } while (getActiveThreads(chunkThreads) > 0) { if (DEBUG) System.out.println("Active Splitfile inserts remaining: " + getActiveThreads(chunkThreads)); mixed.wait(3000); } segmentKeyMaps.add(chunkResults); } int checkNo = 0; for (int i = 0; i < checkFileMaps.size(); i++) { File[] currentFileMap = (File[]) checkFileMaps.get(i); checkThreads = new Thread[currentFileMap.length]; checkResults = new String[currentFileMap.length][2]; threadCount = 0; for (int j = 0; j < currentFileMap.length; j++) { if (DEBUG) System.out.println("Check: " + checkNo); while (getActiveThreads(checkThreads) >= maxThreads) mixed.wait(5000); checkThreads[threadCount] = new putKeyThread("CHK@", currentFileMap[j], htl, checkResults, threadCount, mode); checkThreads[threadCount].start(); threadCount++; uploadedBytes += currentFileMap[j].length(); updateUploadTable(file, uploadedBytes, mode); mixed.wait(1000); checkNo++; } while (getActiveThreads(checkThreads) > 0) { if (DEBUG) System.out.println("Active Checkblock inserts remaining: " + getActiveThreads(checkThreads)); mixed.wait(3000); } checkKeyMaps.add(checkResults); } checkThreads = null; } String redirect = null; { synchronized (fecutils.getClass()) { try { redirect = fecutils.FECMakeMetadata(segmentHeaders, segmentKeyMaps, checkKeyMaps, "Frost"); } catch (Exception e) { System.out.println("putFECSplitFile NOT GOOD " + e.toString()); } } String[] sortedRedirect = redirect.split("\n"); for (int z = 0; z < sortedRedirect.length; z++) System.out.println(sortedRedirect[z]); int sortStart = -1; int sortEnd = -1; for (int line = 0; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("Document")) { sortStart = line + 1; break; } } for (int line = sortStart; line < sortedRedirect.length; line++) { if (sortedRedirect[line].equals("End")) { sortEnd = line; break; } } System.out.println("sortStart " + sortStart + " sortEnd " + sortEnd); if (sortStart < sortEnd) Arrays.sort(sortedRedirect, sortStart, sortEnd); redirect = new String(); for (int line = 0; line < sortedRedirect.length; line++) redirect += sortedRedirect[line] + "\n"; System.out.println(redirect); } int tries = 0; String[] result = { "Error", "Error" }; while (!result[0].equals("Success") && !result[0].equals("KeyCollision") && tries < 8) { tries++; try { FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); output = connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, mode); } catch (FcpToolsException e) { if (DEBUG) System.out.println("FcpToolsException " + e); frame1.displayWarning(e.toString()); } catch (UnknownHostException e) { if (DEBUG) System.out.println("UnknownHostException"); frame1.displayWarning(e.toString()); } catch (IOException e) { if (DEBUG) System.out.println("IOException"); frame1.displayWarning(e.toString()); } result = result(output); mixed.wait(3000); if (DEBUG) System.out.println("*****" + result[0] + " " + result[1] + " "); } if ((result[0].equals("Success") || result[0].equals("KeyCollision")) && mode) { try { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); String dirdate = cal.get(Calendar.YEAR) + "."; dirdate += cal.get(Calendar.MONTH) + 1 + "."; dirdate += cal.get(Calendar.DATE); String fileSeparator = System.getProperty("file.separator"); String destination = frame1.keypool + board + fileSeparator + dirdate + fileSeparator; FcpConnection connection = new FcpConnection(frame1.frostSettings.getValue("nodeAddress"), frame1.frostSettings.getValue("nodePort")); String contentKey = result(connection.putKeyFromFile(uri, null, redirect.getBytes(), htl, false))[1]; String prefix = new String("freenet:"); if (contentKey.startsWith(prefix)) contentKey = contentKey.substring(prefix.length()); FileAccess.writeFile("Already uploaded today", destination + contentKey + ".lck"); } catch (Exception e) { } } return result; }
00
Code Sample 1: private static Vector<String> getIgnoreList() { try { URL url = DeclarationTranslation.class.getClassLoader().getResource("ignorelist"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); Vector<String> ret = new Vector<String>(); String line = null; while ((line = bufferedReader.readLine()) != null) { ret.add(line); } return ret; } catch (Exception e) { return null; } } Code Sample 2: @SuppressWarnings("unused") private static int chkPasswd(final String sInputPwd, final String sSshaPwd) { assert sInputPwd != null; assert sSshaPwd != null; int r = ERR_LOGIN_ACCOUNT; try { BASE64Decoder decoder = new BASE64Decoder(); byte[] ba = decoder.decodeBuffer(sSshaPwd); assert ba.length >= FIXED_HASH_SIZE; byte[] hash = new byte[FIXED_HASH_SIZE]; byte[] salt = new byte[FIXED_SALT_SIZE]; System.arraycopy(ba, 0, hash, 0, FIXED_HASH_SIZE); System.arraycopy(ba, FIXED_HASH_SIZE, salt, 0, FIXED_SALT_SIZE); MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(sInputPwd.getBytes()); md.update(salt); byte[] baPwdHash = md.digest(); if (MessageDigest.isEqual(hash, baPwdHash)) { r = ERR_LOGIN_OK; } } catch (Exception exc) { exc.printStackTrace(); } return r; }
11
Code Sample 1: public void add(Site site) throws Exception { DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { String sqlStr = "insert into t_ip_site (id,name,description,ascii_name,site_path,remark_number,increment_index,use_status,appserver_id) VALUES(?,?,?,?,?,?,?,?,?)"; dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setInt(1, site.getSiteID()); preparedStatement.setString(2, site.getName()); preparedStatement.setString(3, site.getDescription()); preparedStatement.setString(4, site.getAsciiName()); preparedStatement.setString(5, site.getPath()); preparedStatement.setInt(6, site.getRemarkNumber()); preparedStatement.setString(7, site.getIncrementIndex().trim()); preparedStatement.setString(8, String.valueOf(site.getUseStatus())); preparedStatement.setString(9, String.valueOf(site.getAppserverID())); preparedStatement.executeUpdate(); String[] path = new String[1]; path[0] = site.getPath(); selfDefineAdd(path, site, connection, preparedStatement); connection.commit(); int resID = site.getSiteID() + Const.SITE_TYPE_RES; String resName = site.getName(); int resTypeID = Const.RES_TYPE_ID; int operateTypeID = Const.OPERATE_TYPE_ID; String remark = ""; AuthorityManager am = new AuthorityManager(); am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark); site.wirteFile(); } catch (SQLException ex) { connection.rollback(); log.error("����վ��ʧ��!", ex); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } } Code Sample 2: protected boolean store(Context context) throws DataStoreException, ServletException { Connection db = context.getConnection(); Statement st = null; String q = null; Integer subscriber = context.getValueAsInteger("subscriber"); int amount = 0; if (subscriber == null) { throw new DataAuthException("Don't know who moderator is"); } Object response = context.get("Response"); if (response == null) { throw new DataStoreException("Don't know what to moderate"); } else { Context scratch = (Context) context.clone(); TableDescriptor.getDescriptor("response", "response", scratch).fetch(scratch); Integer author = scratch.getValueAsInteger("author"); if (subscriber.equals(author)) { throw new SelfModerationException("You may not moderate your own responses"); } } context.put("moderator", subscriber); context.put("moderated", response); if (db != null) { try { st = db.createStatement(); q = "select mods from subscriber where subscriber = " + subscriber.toString(); ResultSet r = st.executeQuery(q); if (r.next()) { if (r.getInt("mods") < 1) { throw new DataAuthException("You have no moderation points left"); } } else { throw new DataAuthException("Don't know who moderator is"); } Object reason = context.get("reason"); q = "select score from modreason where modreason = " + reason; r = st.executeQuery(q); if (r.next()) { amount = r.getInt("score"); context.put("amount", new Integer(amount)); } else { throw new DataStoreException("Don't recognise reason (" + reason + ") to moderate"); } context.put(keyField, null); if (super.store(context, db)) { db.setAutoCommit(false); q = "update RESPONSE set Moderation = " + "( select sum( Amount) from MODERATION " + "where Moderated = " + response + ") " + "where Response = " + response; st.executeUpdate(q); q = "update subscriber set mods = mods - 1 " + "where subscriber = " + subscriber; st.executeUpdate(q); q = "select author from response " + "where response = " + response; r = st.executeQuery(q); if (r.next()) { int author = r.getInt("author"); if (author != 0) { int points = -1; if (amount > 0) { points = 1; } StringBuffer qb = new StringBuffer("update subscriber "); qb.append("set score = score + ").append(amount); qb.append(", mods = mods + ").append(points); qb.append(" where subscriber = ").append(author); st.executeUpdate(qb.toString()); } } db.commit(); } } catch (Exception e) { try { db.rollback(); } catch (Exception whoops) { throw new DataStoreException("Shouldn't happen: " + "failed to back out " + "failed insert: " + whoops.getMessage()); } throw new DataStoreException("Failed to store moderation: " + e.getMessage()); } finally { if (st != null) { try { st.close(); } catch (Exception noclose) { } context.releaseConnection(db); } } } return true; }
11
Code Sample 1: private byte[] getMD5(String string) throws IMException { byte[] buffer = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(string.getBytes("utf-8")); buffer = md.digest(); buffer = getHexString(buffer); } catch (NoSuchAlgorithmException e) { throw new IMException(e); } catch (UnsupportedEncodingException ue) { throw new IMException(ue); } return buffer; } Code Sample 2: public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
00
Code Sample 1: public AudioInputStream getAudioInputStream(URL url, String userAgent) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReaderWorkaround.getAudioInputStream(URL,String): begin"); } long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED; URLConnection conn = url.openConnection(); boolean isShout = false; int toRead = 4; byte[] head = new byte[toRead]; if (userAgent != null) conn.setRequestProperty("User-Agent", userAgent); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Icy-Metadata", "1"); conn.setRequestProperty("Connection", "close"); BufferedInputStream bInputStream = new BufferedInputStream(conn.getInputStream()); bInputStream.mark(toRead); int read = bInputStream.read(head, 0, toRead); if ((read > 2) && (((head[0] == 'I') | (head[0] == 'i')) && ((head[1] == 'C') | (head[1] == 'c')) && ((head[2] == 'Y') | (head[2] == 'y')))) { isShout = true; } bInputStream.reset(); InputStream inputStream = null; if (isShout == true) { IcyInputStream icyStream = new IcyInputStream(bInputStream); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { String metaint = conn.getHeaderField("icy-metaint"); if (metaint != null) { IcyInputStream icyStream = new IcyInputStream(bInputStream, metaint); icyStream.addTagParseListener(IcyListener.getInstance()); inputStream = icyStream; } else { inputStream = bInputStream; } } AudioInputStream audioInputStream = null; try { audioInputStream = getAudioInputStream(inputStream, lFileLengthInBytes); } catch (UnsupportedAudioFileException e) { inputStream.close(); throw e; } catch (IOException e) { inputStream.close(); throw e; } if (TDebug.TraceAudioFileReader) { TDebug.out("MpegAudioFileReaderWorkaround.getAudioInputStream(URL,String): end"); } return audioInputStream; } Code Sample 2: public static String md5hash(String text) { java.security.MessageDigest md; try { md = java.security.MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.update(text.getBytes()); byte[] md5bytes = md.digest(); return new String(org.apache.commons.codec.binary.Hex.encodeHex(md5bytes)); }
00
Code Sample 1: public byte[] md5(String clearText) { MessageDigest md; byte[] digest; try { md = MessageDigest.getInstance("MD5"); md.update(clearText.getBytes()); digest = md.digest(); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.toString()); } return digest; } Code Sample 2: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(realPath + filename)); IOUtils.copy(is, fos); response.setStatus(response.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(response.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); }
00
Code Sample 1: @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(); } } Code Sample 2: public void delete(Connection conn, boolean commit) throws SQLException { PreparedStatement stmt = null; if (isNew()) { String errorMessage = "Unable to delete non-persistent DAO '" + getClass().getName() + "'"; if (log.isErrorEnabled()) { log.error(errorMessage); } throw new SQLException(errorMessage); } try { stmt = conn.prepareStatement(getDeleteSql()); stmt.setObject(1, getPrimaryKey()); int rowCount = stmt.executeUpdate(); if (rowCount != 1) { if (commit) { conn.rollback(); } String errorMessage = "Invalid number of rows changed!"; if (log.isErrorEnabled()) { log.error(errorMessage); } throw new SQLException(errorMessage); } else if (commit) { conn.commit(); } } finally { OvJdbcUtils.closeStatement(stmt); } }
00
Code Sample 1: public static void copyFile(File sourceFile, File destinationFile) throws IOException { if (!destinationFile.exists()) { destinationFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destinationFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } } Code Sample 2: public Web(String urlString) throws java.net.MalformedURLException, java.io.IOException { final java.net.URL url = new java.net.URL(urlString); final java.net.URLConnection uconn = url.openConnection(); if (!(uconn instanceof java.net.HttpURLConnection)) throw new java.lang.IllegalArgumentException("URL protocol must be HTTP."); final java.net.HttpURLConnection conn = (java.net.HttpURLConnection) uconn; conn.setConnectTimeout(100000); conn.setReadTimeout(100000); conn.setInstanceFollowRedirects(true); conn.setRequestProperty("User-agent", "spider"); conn.connect(); responseHeader = conn.getHeaderFields(); responseCode = conn.getResponseCode(); responseURL = conn.getURL(); length = conn.getContentLength(); final String type = conn.getContentType(); if (type != null) { final String[] parts = type.split(";"); MIMEtype = parts[0].trim(); for (int i = 1; i < parts.length && charset == null; i++) { final String t = parts[i].trim(); final int index = t.toLowerCase().indexOf("charset="); if (index != -1) charset = t.substring(index + 8); } } final java.io.InputStream stream = conn.getErrorStream(); if (stream != null) { content = readStream(length, stream); } else if ((inputStream = conn.getContent()) != null && inputStream instanceof java.io.InputStream) { content = readStream(length, (java.io.InputStream) inputStream); } conn.disconnect(); }
00
Code Sample 1: public static String Md5By32(String plainText) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.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)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } Code Sample 2: @Test public void testStandardTee() throws Exception { final byte[] test = "test".getBytes(); final InputStream source = new ByteArrayInputStream(test); final ByteArrayOutputStream destination1 = new ByteArrayOutputStream(); final ByteArrayOutputStream destination2 = new ByteArrayOutputStream(); final TeeOutputStream tee = new TeeOutputStream(destination1, destination2); org.apache.commons.io.IOUtils.copy(source, tee); tee.close(); assertArrayEquals("the two arrays are equals", test, destination1.toByteArray()); assertArrayEquals("the two arrays are equals", test, destination2.toByteArray()); assertEquals("byte count", test.length, tee.getSize()); }
11
Code Sample 1: public void run(Preprocessor pp) throws SijappException { for (int i = 0; i < this.filenames.length; i++) { File srcFile = new File(this.srcDir, this.filenames[i]); BufferedReader reader; try { InputStreamReader isr = new InputStreamReader(new FileInputStream(srcFile), "CP1251"); reader = new BufferedReader(isr); } catch (Exception e) { throw (new SijappException("File " + srcFile.getPath() + " could not be read")); } File destFile = new File(this.destDir, this.filenames[i]); BufferedWriter writer; try { (new File(destFile.getParent())).mkdirs(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destFile), "CP1251"); writer = new BufferedWriter(osw); } catch (Exception e) { throw (new SijappException("File " + destFile.getPath() + " could not be written")); } try { pp.run(reader, writer); } catch (SijappException e) { try { reader.close(); } catch (IOException f) { } try { writer.close(); } catch (IOException f) { } try { destFile.delete(); } catch (SecurityException f) { } throw (new SijappException(srcFile.getPath() + ":" + e.getMessage())); } try { reader.close(); } catch (IOException e) { } try { writer.close(); } catch (IOException e) { } } } Code Sample 2: private void writeFile(FileInputStream inFile, FileOutputStream outFile) throws IOException { byte[] buf = new byte[2048]; int read; while ((read = inFile.read(buf)) > 0 && !stopped) outFile.write(buf, 0, read); inFile.close(); }
00
Code Sample 1: public static byte[] ComputeForBinary(String ThisString) throws Exception { byte[] Result; MessageDigest MD5Hasher; MD5Hasher = MessageDigest.getInstance("MD5"); MD5Hasher.update(ThisString.getBytes("iso-8859-1")); Result = MD5Hasher.digest(); return Result; } Code Sample 2: public void testReleaseOnIOException() throws Exception { localServer.register("/dropdead", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { BasicHttpEntity entity = new BasicHttpEntity() { @Override public void writeTo(final OutputStream outstream) throws IOException { byte[] tmp = new byte[5]; outstream.write(tmp); outstream.flush(); DefaultHttpServerConnection conn = (DefaultHttpServerConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION); try { conn.sendResponseHeader(response); } catch (HttpException ignore) { } } }; entity.setChunked(true); response.setEntity(entity); } }); HttpParams params = defaultParams.copy(); ConnManagerParams.setMaxTotalConnections(params, 1); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1)); ThreadSafeClientConnManager mgr = createTSCCM(params, null); assertEquals(0, mgr.getConnectionsInPool()); DefaultHttpClient client = new DefaultHttpClient(mgr, params); HttpGet httpget = new HttpGet("/dropdead"); HttpHost target = getServerHttp(); HttpResponse response = client.execute(target, httpget); ClientConnectionRequest connreq = mgr.requestConnection(new HttpRoute(target), null); try { connreq.getConnection(250, TimeUnit.MILLISECONDS); fail("ConnectionPoolTimeoutException should have been thrown"); } catch (ConnectionPoolTimeoutException expected) { } HttpEntity e = response.getEntity(); assertNotNull(e); try { EntityUtils.toByteArray(e); fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException expected) { } assertEquals(0, mgr.getConnectionsInPool()); connreq = mgr.requestConnection(new HttpRoute(target), null); ManagedClientConnection conn = connreq.getConnection(250, TimeUnit.MILLISECONDS); mgr.releaseConnection(conn, -1, null); mgr.shutdown(); }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } catch (FileNotFoundException fnfe) { Log.debug(fnfe); } finally { if (in != null) in.close(); if (out != null) out.close(); } } Code Sample 2: public void writeOutput(String directory) throws IOException { File f = new File(directory); int i = 0; if (f.isDirectory()) { for (AppInventorScreen screen : screens.values()) { File screenFile = new File(getScreenFilePath(f.getAbsolutePath(), screen)); screenFile.getParentFile().mkdirs(); screenFile.createNewFile(); FileWriter out = new FileWriter(screenFile); String initial = files.get(i).toString(); Map<String, String> types = screen.getTypes(); String[] lines = initial.split("\n"); for (String key : types.keySet()) { if (!key.trim().equals(screen.getName().trim())) { String value = types.get(key); boolean varFound = false; boolean importFound = false; for (String line : lines) { if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*=.*;$")) varFound = true; if (line.matches("^\\s*(public|private)\\s+" + value + "\\s+" + key + "\\s*;$")) varFound = true; if (line.matches("^\\s*import\\s+.*" + value + "\\s*;$")) importFound = true; } if (!varFound) initial = initial.replaceFirst("(?s)(?<=\\{\n)", "\tprivate " + value + " " + key + ";\n"); if (!importFound) initial = initial.replaceFirst("(?=import)", "import com.google.devtools.simple.runtime.components.android." + value + ";\n"); } } out.write(initial); out.close(); i++; } File manifestFile = new File(getManifestFilePath(f.getAbsolutePath(), manifest)); manifestFile.getParentFile().mkdirs(); manifestFile.createNewFile(); FileWriter out = new FileWriter(manifestFile); out.write(manifest.toString()); out.close(); File projectFile = new File(getProjectFilePath(f.getAbsolutePath(), project)); projectFile.getParentFile().mkdirs(); projectFile.createNewFile(); out = new FileWriter(projectFile); out.write(project.toString()); out.close(); String[] copyResourceFilenames = { "proguard.cfg", "project.properties", "libSimpleAndroidRuntime.jar", "\\.classpath", "res/drawable/icon.png", "\\.settings/org.eclipse.jdt.core.prefs" }; for (String copyResourceFilename : copyResourceFilenames) { InputStream is = getClass().getResourceAsStream("/resources/" + copyResourceFilename.replace("\\.", "")); File outputFile = new File(f.getAbsoluteFile() + File.separator + copyResourceFilename.replace("\\.", ".")); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; if (is == null) System.out.println("/resources/" + copyResourceFilename.replace("\\.", "")); if (os == null) System.out.println(f.getAbsolutePath() + File.separator + copyResourceFilename.replace("\\.", ".")); while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } for (String assetName : assets) { InputStream is = new FileInputStream(new File(assetsDir.getAbsolutePath() + File.separator + assetName)); File outputFile = new File(f.getAbsoluteFile() + File.separator + assetName); outputFile.getParentFile().mkdirs(); OutputStream os = new FileOutputStream(outputFile); byte[] buf = new byte[1024]; int readBytes; while ((readBytes = is.read(buf)) > 0) { os.write(buf, 0, readBytes); } } File assetsOutput = new File(getAssetsFilePath(f.getAbsolutePath())); new File(assetsDir.getAbsoluteFile() + File.separator + "assets").renameTo(assetsOutput); } }
00
Code Sample 1: protected File downloadFile(String href) { Map<String, File> currentDownloadDirMap = downloadedFiles.get(downloadDir); if (currentDownloadDirMap != null) { File downloadedFile = currentDownloadDirMap.get(href); if (downloadedFile != null) { return downloadedFile; } } else { downloadedFiles.put(downloadDir, new HashMap<String, File>()); currentDownloadDirMap = downloadedFiles.get(downloadDir); } URL url; File result; try { FilesystemUtils.forceMkdirIfNotExists(downloadDir); url = generateUrl(href); result = createUniqueFile(downloadDir, href); } catch (IOException e) { LOG.warn("Failed to create file for download", e); return null; } currentDownloadDirMap.put(href, result); LOG.info("Downloading " + url); try { IOUtils.copy(url.openStream(), new FileOutputStream(result)); } catch (IOException e) { LOG.warn("Failed to download file " + url); } return result; } Code Sample 2: public void load() throws ResourceInstantiationException { if (null == url) { throw new ResourceInstantiationException("URL not set (null)."); } try { BufferedReader defReader = new BomStrippingInputStreamReader((url).openStream(), ENCODING); String line; LinearNode node; while (null != (line = defReader.readLine())) { node = new LinearNode(line); try { this.add(node); } catch (GateRuntimeException ex) { throw new ResourceInstantiationException(ex); } } defReader.close(); isModified = false; } catch (Exception x) { throw new ResourceInstantiationException(x); } }
11
Code Sample 1: public void postProcess() throws StopWriterVisitorException { dxfWriter.postProcess(); try { FileChannel fcinDxf = new FileInputStream(fTemp).getChannel(); FileChannel fcoutDxf = new FileOutputStream(m_Fich).getChannel(); DriverUtilities.copy(fcinDxf, fcoutDxf); fTemp.delete(); } catch (FileNotFoundException e) { throw new StopWriterVisitorException(getName(), e); } catch (IOException e) { throw new StopWriterVisitorException(getName(), e); } } Code Sample 2: public static void copyFile1(File srcFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(destFile); FileChannel source = fis.getChannel(); FileChannel destination = fos.getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); fis.close(); fos.close(); }
11
Code Sample 1: public static String computeMD5(InputStream input) { InputStream digestStream = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); digestStream = new DigestInputStream(input, md5); IOUtils.copy(digestStream, new NullOutputStream()); return new String(Base64.encodeBase64(md5.digest()), "UTF-8"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(digestStream); } } Code Sample 2: public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { File inputFile = src; File outputFile = dst; FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } Code Sample 2: public static void downloadFile(HttpServletResponse response, String file) throws IOException { response.setContentType(FileUtils.getContentType(file)); response.setContentLength(FileUtils.getContentLength(file)); response.setHeader("Content-type", ResponseUtils.DOWNLOAD_CONTENT_TYPE); response.setHeader("Content-Disposition", "attachment; filename=\"" + FileUtils.getFileName(file) + "\""); response.setHeader("Content-Length", Integer.toString(FileUtils.getContentLength(file))); InputStream input = new FileInputStream(file); OutputStream output = response.getOutputStream(); IOUtils.copy(input, output, true); }
00
Code Sample 1: public String connectToServlet() { URL urlStory = null; BufferedReader brStory; String result = ""; try { urlStory = new URL(getCodeBase(), "http://localhost:8080/javawebconsole/ToApplet"); } catch (MalformedURLException MUE) { MUE.printStackTrace(); } try { brStory = new BufferedReader(new InputStreamReader(urlStory.openStream())); while (brStory.ready()) { result += brStory.readLine(); } } catch (IOException IOE) { IOE.printStackTrace(); } return result; } Code Sample 2: public void login() { loginsuccessful = false; try { cookies = new StringBuilder(); HttpParams params = new BasicHttpParams(); params.setParameter("http.useragent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6"); DefaultHttpClient httpclient = new DefaultHttpClient(params); NULogger.getLogger().info("Trying to log in to crocko.com"); HttpPost httppost = new HttpPost("https://www.crocko.com/accounts/login"); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("login", getUsername())); formparams.add(new BasicNameValuePair("password", getPassword())); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); httppost.setEntity(entity); HttpResponse httpresponse = httpclient.execute(httppost); NULogger.getLogger().info("Getting cookies........"); NULogger.getLogger().info(EntityUtils.toString(httpresponse.getEntity())); Iterator<Cookie> it = httpclient.getCookieStore().getCookies().iterator(); Cookie escookie = null; while (it.hasNext()) { escookie = it.next(); cookies.append(escookie.getName()).append("=").append(escookie.getValue()).append(";"); if (escookie.getName().equals("PHPSESSID")) { sessionid = escookie.getValue(); NULogger.getLogger().info(sessionid); } } if (cookies.toString().contains("logacc")) { NULogger.getLogger().info(cookies.toString()); loginsuccessful = true; username = getUsername(); password = getPassword(); NULogger.getLogger().info("Crocko login successful :)"); } if (!loginsuccessful) { NULogger.getLogger().info("Crocko.com Login failed :("); loginsuccessful = false; username = ""; password = ""; JOptionPane.showMessageDialog(NeembuuUploader.getInstance(), "<html><b>" + HOSTNAME + "</b> " + TranslationProvider.get("neembuuuploader.accounts.loginerror") + "</html>", HOSTNAME, JOptionPane.WARNING_MESSAGE); AccountsManager.getInstance().setVisible(true); } httpclient.getConnectionManager().shutdown(); } catch (Exception e) { NULogger.getLogger().log(Level.SEVERE, "{0}: {1}", new Object[] { getClass().getName(), e.toString() }); System.err.println(e); } }
11
Code Sample 1: public static void copy(File srcFile, File destFile) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream(srcFile); out = new FileOutputStream(destFile); final byte[] buf = new byte[4096]; int read; while ((read = in.read(buf)) >= 0) { out.write(buf, 0, read); } } finally { try { if (in != null) in.close(); } catch (IOException ioe) { } try { if (out != null) out.close(); } catch (IOException ioe) { } } } Code Sample 2: private static void cut() { File inputFile = new File(inputFileName); BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), inputCharSet)); } catch (FileNotFoundException e) { System.err.print("Invalid File Name!"); System.err.flush(); System.exit(1); } catch (UnsupportedEncodingException e) { System.err.print("Invalid Char Set Name!"); System.err.flush(); System.exit(1); } switch(cutMode) { case charMode: { int outputFileIndex = 1; char[] readBuf = new char[charPerFile]; while (true) { int readCount = 0; try { readCount = in.read(readBuf); } catch (IOException e) { System.err.println("Read IO Error!"); System.err.flush(); System.exit(1); } if (-1 == readCount) break; else { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + "-" + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), outputCharSet)); out.write(readBuf, 0, readCount); out.flush(); out.close(); outputFileIndex++; } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } } } break; } case lineMode: { boolean isFileEnd = false; int outputFileIndex = 1; while (!isFileEnd) { try { int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = inputFileName.substring(ppos + 1); DecimalFormat outputFileIndexFormat = new DecimalFormat("0000"); File outputFile = new File(prefixInputFileName + outputFileIndexFormat.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); int p = 0; while (p < linePerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } out.println(line); ++p; } out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } break; } case htmlMode: { boolean isFileEnd = false; int outputFileIndex = 1; int ppos = inputFileName.lastIndexOf("."); String prefixInputFileName = inputFileName.substring(0, ppos); String postfixInputFileName = "html"; DecimalFormat df = new DecimalFormat("0000"); while (!isFileEnd) { try { File outputFile = new File(prefixInputFileName + "-" + df.format(outputFileIndex) + "." + postfixInputFileName); PrintStream out = new PrintStream(new FileOutputStream(outputFile), false, outputCharSet); out.println("<html><head><title>" + prefixInputFileName + "-" + df.format(outputFileIndex) + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><div id=\"content\">"); int p = 0; while (p < pPerFile) { String line = in.readLine(); if (null == line) { isFileEnd = true; break; } if (line.length() > 0) out.println("<p>" + line + "</p>"); ++p; } out.println("</div><a href=\"" + prefixInputFileName + "-" + df.format(outputFileIndex + 1) + "." + postfixInputFileName + "\">NEXT</a></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } ++outputFileIndex; } try { File indexFile = new File("index.html"); PrintStream out = new PrintStream(new FileOutputStream(indexFile), false, outputCharSet); out.println("<html><head><title>" + "Index" + "</title>" + "<meta http-equiv=\"Content-Type\"" + " content=\"text/html; " + "charset=" + outputCharSet + "\" />" + "<link rel =\"stylesheet\" " + "type=\"text/css\" " + "href=\"stylesheet.css\" />" + "</head><body><h2>" + htmlTitle + "</h2><div id=\"content\"><ul>"); for (int i = 1; i < outputFileIndex; i++) { out.println("<li><a href=\"" + prefixInputFileName + "-" + df.format(i) + "." + postfixInputFileName + "\">" + df.format(i) + "</a></li>"); } out.println("</ul></body></html>"); out.flush(); out.close(); } catch (IOException e) { System.err.println("Write IO Error!"); System.err.flush(); System.exit(1); } break; } } }
00
Code Sample 1: public static void executeUpdate(Database db, String... statements) throws SQLException { Connection con = null; Statement stmt = null; try { con = getConnection(db); con.setAutoCommit(false); stmt = con.createStatement(); for (String statement : statements) { stmt.executeUpdate(statement); } con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { } throw e; } finally { closeStatement(stmt); closeConnection(con); } } Code Sample 2: private static String GetSHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return LoginHttpPostProcessor.ConvertToHex(sha1hash); }
00
Code Sample 1: public static void readAsFile(String fileName, String url) { BufferedInputStream in = null; BufferedOutputStream out = null; URLConnection conn = null; try { conn = new URL(url).openConnection(); conn.setDoInput(true); in = new BufferedInputStream(conn.getInputStream()); out = new BufferedOutputStream(new FileOutputStream(fileName)); int b; while ((b = in.read()) != -1) { out.write(b); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } finally { if (null != in) { try { in.close(); } catch (IOException e) { } } if (null != out) { try { out.flush(); out.close(); } catch (IOException e) { } } } } Code Sample 2: public static void copy(FileInputStream source, FileOutputStream dest) throws IOException { FileChannel in = null, out = null; try { in = source.getChannel(); out = dest.getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
00
Code Sample 1: public void connect(String username, String passwordMd5) { this.username = username; this.passwordMd5 = passwordMd5; StringBuffer handshakeUrl = new StringBuffer(); handshakeUrl.append("http://ws.audioscrobbler.com/radio/handshake.php?version="); handshakeUrl.append(LastFM.VERSION); handshakeUrl.append("&platform=linux&username="); handshakeUrl.append(this.username); handshakeUrl.append("&passwordmd5="); handshakeUrl.append(this.passwordMd5); handshakeUrl.append("&language=en&player=aTunes"); URL url; try { url = new URL(handshakeUrl.toString()); URLConnection connection = url.openConnection(); InputStream inputStream = new BufferedInputStream(connection.getInputStream()); byte[] buffer = new byte[4069]; int read = 0; StringBuffer result = new StringBuffer(); while ((read = inputStream.read(buffer)) > -1) { result.append((new String(buffer, 0, read))); } String[] rows = result.toString().split("\n"); this.data = new HashMap<String, String>(); for (String row : rows) { row = row.trim(); int firstEquals = row.indexOf("="); data.put(row.substring(0, firstEquals), row.substring(firstEquals + 1)); } String streamingUrl = data.get("stream_url"); streamingUrl = streamingUrl.substring(7); int delimiter = streamingUrl.indexOf("/"); String hostname = streamingUrl.substring(0, delimiter); String path = streamingUrl.substring(delimiter + 1); String[] tokens = hostname.split(":"); hostname = tokens[0]; int port = Integer.parseInt(tokens[1]); this.lastFmSocket = new Socket(hostname, port); OutputStreamWriter osw = new OutputStreamWriter(this.lastFmSocket.getOutputStream()); osw.write("GET /" + path + " HTTP/1.0\r\n"); osw.write("Host: " + hostname + "\r\n"); osw.write("\r\n"); osw.flush(); this.lastFmInputStream = this.lastFmSocket.getInputStream(); result = new StringBuffer(); while ((read = this.lastFmInputStream.read(buffer)) > -1) { String line = new String(buffer, 0, read); result.append(line); if (line.contains("\r\n\r\n")) break; } String response = result.toString(); logger.info("Result: " + response); if (!response.startsWith("HTTP/1.0 200 OK")) { this.lastFmSocket.close(); throw new LastFmException("Could not handshake with lastfm. Check credential!"); } StringBuffer sb = new StringBuffer(); sb.append("http://"); sb.append(this.data.get("base_url")); sb.append(this.data.get("base_path")); sb.append("/xspf.php?sk="); sb.append(this.data.get("session")); sb.append("&discovery=1&desktop="); sb.append(LastFM.VERSION); logger.info(sb.toString()); this.playlistUrl = new URL(sb.toString()); this.playlist = this.playlistParser.fetchPlaylist(this.playlistUrl.toString()); Iterator<LastFmTrack> it = this.playlist.iterator(); while (it.hasNext()) { System.out.println(it.next().getCreator()); } this.connected = true; } catch (MalformedURLException e) { throw new LastFmException("Could not handshake with lastfm", e.getCause()); } catch (IOException e) { throw new LastFmException("Could not initialise lastfm", e.getCause()); } } Code Sample 2: @Test public void testCopy_inputStreamToWriter_nullIn() throws Exception { ByteArrayOutputStream baout = new ByteArrayOutputStream(); OutputStream out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); try { IOUtils.copy((InputStream) null, writer); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: public static FileChannel newFileChannel(File file, String rw, boolean enableException) throws IOException { if (file == null) return null; if (rw == null || rw.length() == 0) { return null; } rw = rw.toLowerCase(); if (rw.equals(MODE_READ)) { if (FileUtil.exists(file, enableException)) { FileInputStream fis = new FileInputStream(file); FileChannel ch = fis.getChannel(); setObjectMap(ch.hashCode(), fis, FIS); return ch; } } else if (rw.equals(MODE_WRITE)) { FileOutputStream fos = new FileOutputStream(file); FileChannel ch = fos.getChannel(); setObjectMap(ch.hashCode(), fos, FOS_W); return ch; } else if (rw.equals(MODE_APPEND)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, "rw"); FileChannel ch = raf.getChannel(); ch.position(ch.size()); setObjectMap(ch.hashCode(), raf, FOS_A); return ch; } } else if (rw.equals(MODE_READ_WRITE)) { if (FileUtil.exists(file, enableException)) { RandomAccessFile raf = new RandomAccessFile(file, rw); FileChannel ch = raf.getChannel(); setObjectMap(ch.hashCode(), raf, RAF); return ch; } } else { throw new IllegalArgumentException("Illegal read/write type : [" + rw + "]\n" + "You can use following types for: \n" + " (1) Read Only = \"r\"\n" + " (2) Write Only = \"w\"\n" + " (3) Read/Write = \"rw\"\n" + " (4) Append = \"a\""); } return null; }
11
Code Sample 1: public BufferedImage extract() throws DjatokaException { boolean useRegion = false; int left = 0; int top = 0; int width = 50; int height = 50; boolean useleftDouble = false; Double leftDouble = 0.0; boolean usetopDouble = false; Double topDouble = 0.0; boolean usewidthDouble = false; Double widthDouble = 0.0; boolean useheightDouble = false; Double heightDouble = 0.0; if (params.getRegion() != null) { StringTokenizer st = new StringTokenizer(params.getRegion(), "{},"); String token; if ((token = st.nextToken()).contains(".")) { topDouble = Double.parseDouble(token); usetopDouble = true; } else top = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { leftDouble = Double.parseDouble(token); useleftDouble = true; } else left = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { heightDouble = Double.parseDouble(token); useheightDouble = true; } else height = Integer.parseInt(token); if ((token = st.nextToken()).contains(".")) { widthDouble = Double.parseDouble(token); usewidthDouble = true; } else width = Integer.parseInt(token); useRegion = true; } try { if (is != null) { File f = File.createTempFile("tmp", ".jp2"); f.deleteOnExit(); FileOutputStream fos = new FileOutputStream(f); sourceFile = f.getAbsolutePath(); IOUtils.copyStream(is, fos); is.close(); fos.close(); } } catch (IOException e) { throw new DjatokaException(e); } try { Jp2_source inputSource = new Jp2_source(); Kdu_compressed_source input = null; Jp2_family_src jp2_family_in = new Jp2_family_src(); Jp2_locator loc = new Jp2_locator(); jp2_family_in.Open(sourceFile, true); inputSource.Open(jp2_family_in, loc); inputSource.Read_header(); input = inputSource; Kdu_codestream codestream = new Kdu_codestream(); codestream.Create(input); Kdu_channel_mapping channels = new Kdu_channel_mapping(); if (inputSource.Exists()) channels.Configure(inputSource, false); else channels.Configure(codestream); int ref_component = channels.Get_source_component(0); Kdu_coords ref_expansion = getReferenceExpansion(ref_component, channels, codestream); Kdu_dims image_dims = new Kdu_dims(); codestream.Get_dims(ref_component, image_dims); Kdu_coords imageSize = image_dims.Access_size(); Kdu_coords imagePosition = image_dims.Access_pos(); if (useleftDouble) left = imagePosition.Get_x() + (int) Math.round(leftDouble * imageSize.Get_x()); if (usetopDouble) top = imagePosition.Get_y() + (int) Math.round(topDouble * imageSize.Get_y()); if (useheightDouble) height = (int) Math.round(heightDouble * imageSize.Get_y()); if (usewidthDouble) width = (int) Math.round(widthDouble * imageSize.Get_x()); if (useRegion) { imageSize.Set_x(width); imageSize.Set_y(height); imagePosition.Set_x(left); imagePosition.Set_y(top); } int reduce = 1 << params.getLevelReductionFactor(); imageSize.Set_x(imageSize.Get_x() * ref_expansion.Get_x()); imageSize.Set_y(imageSize.Get_y() * ref_expansion.Get_y()); imagePosition.Set_x(imagePosition.Get_x() * ref_expansion.Get_x() / reduce - ((ref_expansion.Get_x() / reduce - 1) / 2)); imagePosition.Set_y(imagePosition.Get_y() * ref_expansion.Get_y() / reduce - ((ref_expansion.Get_y() / reduce - 1) / 2)); Kdu_dims view_dims = new Kdu_dims(); view_dims.Assign(image_dims); view_dims.Access_size().Set_x(imageSize.Get_x()); view_dims.Access_size().Set_y(imageSize.Get_y()); int region_buf_size = imageSize.Get_x() * imageSize.Get_y(); int[] region_buf = new int[region_buf_size]; Kdu_region_decompressor decompressor = new Kdu_region_decompressor(); decompressor.Start(codestream, channels, -1, params.getLevelReductionFactor(), 16384, image_dims, ref_expansion, new Kdu_coords(1, 1), false, Kdu_global.KDU_WANT_OUTPUT_COMPONENTS); Kdu_dims new_region = new Kdu_dims(); Kdu_dims incomplete_region = new Kdu_dims(); Kdu_coords viewSize = view_dims.Access_size(); incomplete_region.Assign(image_dims); int[] imgBuffer = new int[viewSize.Get_x() * viewSize.Get_y()]; int[] kduBuffer = null; while (decompressor.Process(region_buf, image_dims.Access_pos(), 0, 0, region_buf_size, incomplete_region, new_region)) { Kdu_coords newOffset = new_region.Access_pos(); Kdu_coords newSize = new_region.Access_size(); newOffset.Subtract(view_dims.Access_pos()); kduBuffer = region_buf; int imgBuffereIdx = newOffset.Get_x() + newOffset.Get_y() * viewSize.Get_x(); int kduBufferIdx = 0; int xDiff = viewSize.Get_x() - newSize.Get_x(); for (int j = 0; j < newSize.Get_y(); j++, imgBuffereIdx += xDiff) { for (int i = 0; i < newSize.Get_x(); i++) { imgBuffer[imgBuffereIdx++] = kduBuffer[kduBufferIdx++]; } } } BufferedImage image = new BufferedImage(imageSize.Get_x(), imageSize.Get_y(), BufferedImage.TYPE_INT_RGB); image.setRGB(0, 0, viewSize.Get_x(), viewSize.Get_y(), imgBuffer, 0, viewSize.Get_x()); if (params.getRotationDegree() > 0) { image = ImageProcessingUtils.rotate(image, params.getRotationDegree()); } decompressor.Native_destroy(); channels.Native_destroy(); if (codestream.Exists()) codestream.Destroy(); inputSource.Native_destroy(); input.Native_destroy(); jp2_family_in.Native_destroy(); return image; } catch (KduException e) { e.printStackTrace(); throw new DjatokaException(e); } catch (Exception e) { e.printStackTrace(); throw new DjatokaException(e); } } Code Sample 2: public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } }
00
Code Sample 1: public static void main(String[] args) { if (args.length != 2) throw new IllegalArgumentException(); String inFileName = args[0]; String outFileName = args[1]; File fInput = new File(inFileName); Scanner in = null; try { in = new Scanner(fInput); } catch (FileNotFoundException e) { e.printStackTrace(); } PrintWriter out = null; try { out = new PrintWriter(outFileName); } catch (FileNotFoundException e) { e.printStackTrace(); } while (in.hasNextLine()) { out.println(in.nextLine()); } in.close(); out.close(); } Code Sample 2: @SuppressWarnings("unchecked") public static synchronized MetaDataBean getMetaDataByUrl(URL url) { if (url == null) throw new IllegalArgumentException("Properties url for meta data is null"); MetaDataBean mdb = metaDataByUrl.get(url); if (mdb != null) return mdb; log.info("Loading metadata " + url); Properties properties = new Properties(); try { properties.load(url.openStream()); } catch (IOException e) { throw new RuntimeException(e); } mdb = new MetaDataBean((Map) properties); metaDataByUrl.put(url, mdb); mdb.instanceValue = url.toString(); return mdb; }
11
Code Sample 1: public static void copy(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws IOException { InputStream input = (InputStream) ((NativeJavaObject) args[0]).unwrap(); OutputStream output = (OutputStream) ((NativeJavaObject) args[1]).unwrap(); IOUtils.copy(input, output); } 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: protected synchronized String encryptThis(String seed, String text) throws EncryptionException { String encryptedValue = null; String textToEncrypt = text; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(textToEncrypt.getBytes("UTF-8")); encryptedValue = (new BASE64Encoder()).encode(md.digest()); } catch (Exception e) { throw new EncryptionException(e); } return encryptedValue; } Code Sample 2: private static KeyStore createKeyStore(final URL url, final String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { if (url == null) { throw new IllegalArgumentException("Keystore url may not be null"); } LOG.debug("Initializing key store"); KeyStore keystore = KeyStore.getInstance("jks"); InputStream is = null; try { is = url.openStream(); keystore.load(is, password != null ? password.toCharArray() : null); } finally { if (is != null) is.close(); } return keystore; }
00
Code Sample 1: public String generateKey(String className, String methodName, String text, String meaning) { 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 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: @Override protected void doFetch(HttpServletRequest request, HttpServletResponse response) throws IOException, GadgetException { if (request.getHeader("If-Modified-Since") != null) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } String host = request.getHeader("Host"); if (!lockedDomainService.isSafeForOpenProxy(host)) { String msg = "Embed request for url " + getParameter(request, URL_PARAM, "") + " made to wrong domain " + host; logger.info(msg); throw new GadgetException(GadgetException.Code.INVALID_PARAMETER, msg); } HttpRequest rcr = buildHttpRequest(request, URL_PARAM); HttpResponse results = requestPipeline.execute(rcr); if (results.isError()) { HttpRequest fallbackRcr = buildHttpRequest(request, FALLBACK_URL_PARAM); if (fallbackRcr != null) { results = requestPipeline.execute(fallbackRcr); } } if (contentRewriterRegistry != null) { try { results = contentRewriterRegistry.rewriteHttpResponse(rcr, results); } catch (RewritingException e) { throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e); } } for (Map.Entry<String, String> entry : results.getHeaders().entries()) { String name = entry.getKey(); if (!DISALLOWED_RESPONSE_HEADERS.contains(name.toLowerCase())) { response.addHeader(name, entry.getValue()); } } String responseType = results.getHeader("Content-Type"); if (!StringUtils.isEmpty(rcr.getRewriteMimeType())) { String requiredType = rcr.getRewriteMimeType(); if (requiredType.endsWith("/*") && !StringUtils.isEmpty(responseType)) { requiredType = requiredType.substring(0, requiredType.length() - 2); if (!responseType.toLowerCase().startsWith(requiredType.toLowerCase())) { response.setContentType(requiredType); responseType = requiredType; } } else { response.setContentType(requiredType); responseType = requiredType; } } setResponseHeaders(request, response, results); if (results.getHttpStatusCode() != HttpResponse.SC_OK) { response.sendError(results.getHttpStatusCode()); } IOUtils.copy(results.getResponse(), response.getOutputStream()); } Code Sample 2: public void actionPerformed(ActionEvent e) { if (saveForWebChooser == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("HTML files"); fileFilter.addExtension("html"); saveForWebChooser = new JFileChooser(); saveForWebChooser.setFileFilter(fileFilter); saveForWebChooser.setDialogTitle("Save for Web..."); saveForWebChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentSaveForWebDirectory"))); } if (saveForWebChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentSaveForWebDirectory", saveForWebChooser.getCurrentDirectory().getAbsolutePath()); File pathFile = saveForWebChooser.getSelectedFile().getParentFile(); String name = saveForWebChooser.getSelectedFile().getName(); if (!name.toLowerCase().endsWith(".html") && name.indexOf('.') == -1) { name = name + ".html"; } String resource = MIDletClassLoader.getClassResourceName(this.getClass().getName()); URL url = this.getClass().getClassLoader().getResource(resource); String path = url.getPath(); int prefix = path.indexOf(':'); String mainJarFileName = path.substring(prefix + 1, path.length() - resource.length()); File appletJarDir = new File(new File(mainJarFileName).getParent(), "lib"); File appletJarFile = new File(appletJarDir, "microemu-javase-applet.jar"); if (!appletJarFile.exists()) { appletJarFile = null; } if (appletJarFile == null) { } if (appletJarFile == null) { ExtensionFileFilter fileFilter = new ExtensionFileFilter("JAR packages"); fileFilter.addExtension("jar"); JFileChooser appletChooser = new JFileChooser(); appletChooser.setFileFilter(fileFilter); appletChooser.setDialogTitle("Select MicroEmulator applet jar package..."); appletChooser.setCurrentDirectory(new File(Config.getRecentDirectory("recentAppletJarDirectory"))); if (appletChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) { Config.setRecentDirectory("recentAppletJarDirectory", appletChooser.getCurrentDirectory().getAbsolutePath()); appletJarFile = appletChooser.getSelectedFile(); } else { return; } } JadMidletEntry jadMidletEntry; Iterator it = common.jad.getMidletEntries().iterator(); if (it.hasNext()) { jadMidletEntry = (JadMidletEntry) it.next(); } else { Message.error("MIDlet Suite has no entries"); return; } String midletInput = common.jad.getJarURL(); DeviceEntry deviceInput = selectDevicePanel.getSelectedDeviceEntry(); if (deviceInput != null && deviceInput.getDescriptorLocation().equals(DeviceImpl.DEFAULT_LOCATION)) { deviceInput = null; } File htmlOutputFile = new File(pathFile, name); if (!allowOverride(htmlOutputFile)) { return; } File appletPackageOutputFile = new File(pathFile, "microemu-javase-applet.jar"); if (!allowOverride(appletPackageOutputFile)) { return; } File midletOutputFile = new File(pathFile, midletInput.substring(midletInput.lastIndexOf("/") + 1)); if (!allowOverride(midletOutputFile)) { return; } File deviceOutputFile = null; String deviceDescriptorLocation = null; if (deviceInput != null) { deviceOutputFile = new File(pathFile, deviceInput.getFileName()); if (!allowOverride(deviceOutputFile)) { return; } deviceDescriptorLocation = deviceInput.getDescriptorLocation(); } try { AppletProducer.createHtml(htmlOutputFile, (DeviceImpl) DeviceFactory.getDevice(), jadMidletEntry.getClassName(), midletOutputFile, appletPackageOutputFile, deviceOutputFile); AppletProducer.createMidlet(new URL(midletInput), midletOutputFile); IOUtils.copyFile(appletJarFile, appletPackageOutputFile); if (deviceInput != null) { IOUtils.copyFile(new File(Config.getConfigPath(), deviceInput.getFileName()), deviceOutputFile); } } catch (IOException ex) { Logger.error(ex); } } }
11
Code Sample 1: public void copyServer(int id) throws Exception { File in = new File("servers" + File.separatorChar + "server_" + id); File serversDir = new File("servers" + File.separatorChar); int newNumber = serversDir.listFiles().length + 1; System.out.println("New File Number: " + newNumber); File out = new File("servers" + File.separatorChar + "server_" + newNumber); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (Exception e) { e.printStackTrace(); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } getServer(newNumber - 1); } Code Sample 2: public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
00
Code Sample 1: public void search() throws Exception { URL searchurl = new URL("" + "http://www.ncbi.nlm.nih.gov/blast/Blast.cgi" + "?CMD=Put" + "&DATABASE=" + this.database + "&PROGRAM=" + this.program + "&QUERY=" + this.sequence.seqString()); BufferedReader reader = new BufferedReader(new InputStreamReader(searchurl.openStream(), "UTF-8")); String line = ""; while ((line = reader.readLine()) != null) { if (line.contains("Request ID")) this.rid += line.substring(70, 81); } reader.close(); } Code Sample 2: public XMLResourceBundle() throws MissingResourceException { String systemId = getShortName() + ".xml"; URL url; if ((url = getClass().getResource(systemId)) != null) { InputStream is = null; try { is = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); xmlReader.setContentHandler(new MessageContentHandler()); xmlReader.parse(new InputSource(is)); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } catch (SAXException se) { System.err.println(se.getMessage()); se.printStackTrace(); } catch (ParserConfigurationException pce) { System.err.println(pce.getMessage()); pce.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } } } else { throw new MissingResourceException("Resource file '" + systemId + "' could not be found.", systemId, null); } }
11
Code Sample 1: public static boolean copy(File src, File dest) { boolean result = true; String files[] = null; if (src.isDirectory()) { files = src.list(); result = dest.mkdir(); } else { files = new String[1]; files[0] = ""; } if (files == null) { files = new String[0]; } for (int i = 0; (i < files.length) && result; i++) { File fileSrc = new File(src, files[i]); File fileDest = new File(dest, files[i]); if (fileSrc.isDirectory()) { result = copy(fileSrc, fileDest); } else { FileChannel ic = null; FileChannel oc = null; try { ic = (new FileInputStream(fileSrc)).getChannel(); oc = (new FileOutputStream(fileDest)).getChannel(); ic.transferTo(0, ic.size(), oc); } catch (IOException e) { log.error(sm.getString("expandWar.copy", fileSrc, fileDest), e); result = false; } finally { if (ic != null) { try { ic.close(); } catch (IOException e) { } } if (oc != null) { try { oc.close(); } catch (IOException e) { } } } } } return result; } Code Sample 2: private void invokeTest(String queryfile, String target) { try { String query = IOUtils.toString(XPathMarkBenchmarkTest.class.getResourceAsStream(queryfile)).trim(); String args = EXEC_CMD + " \"" + query + "\" \"" + target + '"'; System.out.println("Invoke command: \n " + args); Process proc = Runtime.getRuntime().exec(args, null, benchmarkDir); InputStream is = proc.getInputStream(); File outFile = new File(outDir, queryfile + ".result"); IOUtils.copy(is, new FileOutputStream(outFile)); is.close(); int ret = proc.waitFor(); if (ret != 0) { System.out.println("process exited with value : " + ret); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } catch (InterruptedException irre) { throw new IllegalStateException(irre); } }
11
Code Sample 1: public void testAddFiles() throws Exception { File original = ZipPlugin.getFileInPlugin(new Path("testresources/test.zip")); File copy = new File(original.getParentFile(), "1test.zip"); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(original); out = new FileOutputStream(copy); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); } finally { Util.close(in); Util.close(out); } ArchiveFile archive = new ArchiveFile(ZipPlugin.createArchive(copy.getPath())); archive.addFiles(new String[] { ZipPlugin.getFileInPlugin(new Path("testresources/add.txt")).getPath() }, new NullProgressMonitor()); IArchive[] children = archive.getChildren(); boolean found = false; for (IArchive child : children) { if (child.getLabel(IArchive.NAME).equals("add.txt")) found = true; } assertTrue(found); copy.delete(); } Code Sample 2: @Test public void testCopy_readerToWriter_nullOut() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); Reader reader = new InputStreamReader(in, "US-ASCII"); try { IOUtils.copy(reader, (Writer) null); fail(); } catch (NullPointerException ex) { } }
11
Code Sample 1: private static void generateFile(String inputFilename, String outputFilename) throws Exception { File inputFile = new File(inputFilename); if (inputFile.exists() == false) { throw new Exception(Messages.getString("ScriptDocToBinary.Input_File_Does_Not_Exist") + inputFilename); } Environment environment = new Environment(); environment.initBuiltInObjects(); NativeObjectsReader reader = new NativeObjectsReader(environment); InputStream input = new FileInputStream(inputFile); System.out.println(Messages.getString("ScriptDocToBinary.Reading_Documentation") + inputFilename); reader.loadXML(input); checkFile(outputFilename); File binaryFile = new File(outputFilename); FileOutputStream outputStream = new FileOutputStream(binaryFile); TabledOutputStream output = new TabledOutputStream(outputStream); reader.getScriptDoc().write(output); output.close(); System.out.println(Messages.getString("ScriptDocToBinary.Finished")); System.out.println(); } Code Sample 2: public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test1.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test2.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.decrypt(reader, writer, key, mode); }
00
Code Sample 1: public InstanceMonitor(String awsAccessId, String awsSecretKey, String bucketName, boolean first) throws IOException { this.awsAccessId = awsAccessId; this.awsSecretKey = awsSecretKey; props = new Properties(); while (true) { try { s3 = new RestS3Service(new AWSCredentials(awsAccessId, awsSecretKey)); bucket = new S3Bucket(bucketName); S3Object obj = s3.getObject(bucket, EW_PROPERTIES); props.load(obj.getDataInputStream()); break; } catch (S3ServiceException ex) { logger.error("problem fetching props from bucket, retrying", ex); try { Thread.sleep(1000); } catch (InterruptedException iex) { } } } URL url = new URL("http://169.254.169.254/latest/meta-data/hostname"); hostname = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/instance-id"); instanceId = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); url = new URL("http://169.254.169.254/latest/meta-data/public-ipv4"); externalIP = new BufferedReader(new InputStreamReader(url.openStream())).readLine(); this.dns = new NetticaAPI(props.getProperty(NETTICA_USER), props.getProperty(NETTICA_PASS)); this.userData = awsAccessId + " " + awsSecretKey + " " + bucketName; this.first = first; logger.info("InstanceMonitor initialized, first=" + first); } Code Sample 2: 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) { } } } }
00
Code Sample 1: public static void copyResourceToFile(Class owningClass, String resourceName, File destinationDir) { final byte[] resourceBytes = readResource(owningClass, resourceName); final ByteArrayInputStream inputStream = new ByteArrayInputStream(resourceBytes); final File destinationFile = new File(destinationDir, resourceName); final FileOutputStream fileOutputStream; try { fileOutputStream = new FileOutputStream(destinationFile); } catch (FileNotFoundException e) { throw new RuntimeException(e); } try { IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new RuntimeException(e); } } Code Sample 2: public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
00
Code Sample 1: public static InputStream getResourceRelativeAsStream(final String name, final Class context) { final URL url = getResourceRelative(name, context); if (url == null) { return null; } try { return url.openStream(); } catch (IOException e) { return null; } } Code Sample 2: private void bokActionPerformed(java.awt.event.ActionEvent evt) { Vector vret = this.uniformtitlepanel.getEnteredValuesKeys(); String[] patlib = newgen.presentation.NewGenMain.getAppletInstance().getPatronLibraryIds(); String xmlreq = newgen.presentation.administration.AdministrationXMLGenerator.getInstance().saveUniformTitleSH("2", vret, patlib); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "UniformTitleSubjectHeadingServlet"); java.net.URLConnection urlconn = (java.net.URLConnection) url.openConnection(); urlconn.setDoOutput(true); java.io.OutputStream dos = urlconn.getOutputStream(); dos.write(xmlreq.getBytes()); java.io.InputStream ios = urlconn.getInputStream(); SAXBuilder saxb = new SAXBuilder(); Document retdoc = saxb.build(ios); Element rootelement = retdoc.getRootElement(); if (rootelement.getChild("Error") == null) { this.showInformationMessage(ResourceBundle.getBundle("Administration").getString("DataSavedInDatabase")); } else { this.showErrorMessage(ResourceBundle.getBundle("Administration").getString("ErrorPleaseContactTheVendor")); } } catch (Exception e) { System.out.println(e); } }
00
Code Sample 1: public String getString(String arg) throws Exception { URL url = new URL(arg); URLConnection con = url.openConnection(); con.setUseCaches(false); con.connect(); InputStreamReader src = new InputStreamReader(con.getInputStream(), "ISO-8859-1"); StringBuffer stb = new StringBuffer(); char[] buf = new char[1024]; int l; while ((l = src.read(buf, 0, 1024)) >= 0) { stb.append(buf, 0, l); } String res = stb.toString(); if (res.startsWith("<pannenleiter-exception")) { builder.start(new TreeNode((TreeWidget) null, false), false); InputSource xmlInput = new InputSource(new StringReader(res)); parser.setDocumentHandler(builder); parser.parse(xmlInput); } return res; } Code Sample 2: public ArrayList<Tweet> getTimeLine() { try { HttpGet get = new HttpGet("http://api.linkedin.com/v1/people/~/network/updates?scope=self"); consumer.sign(get); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); return null; } StringBuffer sBuf = new StringBuffer(); String linea; BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while ((linea = reader.readLine()) != null) { sBuf.append(linea); } reader.close(); response.getEntity().consumeContent(); get.abort(); SAXParserFactory spf = SAXParserFactory.newInstance(); StringReader XMLout = new StringReader(sBuf.toString()); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xmlParserLinkedin gwh = new xmlParserLinkedin(); xr.setContentHandler(gwh); xr.parse(new InputSource(XMLout)); return gwh.getParsedData(); } } catch (UnsupportedEncodingException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (IOException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthMessageSignerException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthExpectationFailedException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (OAuthCommunicationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (ParserConfigurationException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } catch (SAXException e) { this.enviarMensaje("Error: No ha sido posible recoger el timeline de Linkedin"); } return null; }
00
Code Sample 1: public void execute() throws BuildException { Project proj = getProject(); if (templateFile == null) throw new BuildException("Template file not set"); if (targetFile == null) throw new BuildException("Target file not set"); try { File template = new File(templateFile); File target = new File(targetFile); if (!template.exists()) throw new BuildException("Template file does not exist " + template.toString()); if (!template.canRead()) throw new BuildException("Cannot read template file: " + template.toString()); if (((!append) && (!overwrite)) && (!target.exists())) throw new BuildException("Target file already exists and append and overwrite are false " + target.toString()); if (VERBOSE) { System.out.println("ProcessTemplate: tmpl in " + template.toString()); System.out.println("ProcessTemplate: file out " + target.toString()); } BufferedReader reader = new BufferedReader(new FileReader(template)); BufferedWriter writer = new BufferedWriter(new FileWriter(targetFile, append)); parse(reader, writer); writer.flush(); writer.close(); } catch (Exception e) { if (VERBOSE) e.printStackTrace(); throw new BuildException(e); } } Code Sample 2: public String[] getFile() { List<String> records = new ArrayList<String>(); FTPClient ftp = new FTPClient(); try { int reply; FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX); ftp.configure(conf); ftp.connect(host, port); System.out.println("Connected to " + host + "."); System.out.print(ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); } ftp.login(user, password); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused login."); } InputStream is = ftp.retrieveFileStream(remotedir + "/" + remotefile); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { if (!line.equals("")) { records.add(line); } } br.close(); isr.close(); is.close(); ftp.logout(); } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { ioe.printStackTrace(); } } } return records.toArray(new String[0]); }
00
Code Sample 1: private static void executeSQLScript() { File f = new File(System.getProperty("user.dir") + "/resources/umc.sql"); if (f.exists()) { Connection con = null; PreparedStatement pre_stmt = null; try { Class.forName("org.sqlite.JDBC"); con = DriverManager.getConnection("jdbc:sqlite:database/umc.db", "", ""); BufferedReader br = new BufferedReader(new FileReader(f)); String line = ""; con.setAutoCommit(false); while ((line = br.readLine()) != null) { if (!line.equals("") && !line.startsWith("--") && !line.contains("--")) { log.debug(line); pre_stmt = con.prepareStatement(line); pre_stmt.executeUpdate(); } } con.commit(); File dest = new File(f.getAbsolutePath() + ".executed"); if (dest.exists()) dest.delete(); f.renameTo(dest); f.delete(); } catch (Throwable exc) { log.error("Fehler bei Ausführung der SQL Datei", exc); try { con.rollback(); } catch (SQLException exc1) { } } finally { try { if (pre_stmt != null) pre_stmt.close(); if (con != null) con.close(); } catch (SQLException exc2) { log.error("Fehler bei Ausführung von SQL Datei", exc2); } } } } Code Sample 2: public void createVendorSignature() { byte b; try { _vendorMessageDigest = MessageDigest.getInstance("MD5"); _vendorSig = Signature.getInstance("MD5/RSA/PKCS#1"); _vendorSig.initSign((PrivateKey) _vendorPrivateKey); _vendorMessageDigest.update(getBankString().getBytes()); _vendorMessageDigestBytes = _vendorMessageDigest.digest(); _vendorSig.update(_vendorMessageDigestBytes); _vendorSignatureBytes = _vendorSig.sign(); } catch (Exception e) { } ; }
00
Code Sample 1: private static URL getURL(String name) throws EfreetException { URL url = ClassLoader.getSystemResource(name + ".xml"); try { if (url == null) { try { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup("java:/comp/env"); String xmlFileDir = (String) envContext.lookup("xml/efreet"); url = new URL("file:" + xmlFileDir + "/" + name + ".xml"); } catch (NameNotFoundException nnfe) { logger.warn("Name not found on context "); } catch (NamingException e) { logger.error("Error retrieving Context : ", e); } } try { if (url != null) { url.openConnection(); } } catch (FileNotFoundException fnfe) { url = null; } if (url == null) { url = Thread.currentThread().getContextClassLoader().getResource(name + ".xml"); } } catch (IOException ioe) { logger.error("Error reading XML file", ioe); throw new EfreetException(ioe.getMessage()); } return url; } Code Sample 2: public static String sha1Hash(String input) { try { MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1"); sha1Digest.update(input.getBytes()); return byteArrayToString(sha1Digest.digest()); } catch (Exception e) { logger.error(e.getMessage(), e); } return ""; }
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: @Override public void download(String remoteFilePath, String localFilePath) { InputStream remoteStream = null; try { remoteStream = client.get(remoteFilePath); } catch (IOException e) { e.printStackTrace(); } OutputStream localStream = null; try { localStream = new FileOutputStream(new File(localFilePath)); } catch (FileNotFoundException e1) { e1.printStackTrace(); } try { IOUtils.copy(remoteStream, localStream); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: public static void copyFile3(File srcFile, File destFile) throws IOException { InputStream in = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int len; while((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } Code Sample 2: public static void copy(File from_file, File to_file) throws IOException { if (!from_file.exists()) { throw new IOException("FileCopy: no such source file: " + from_file.getPath()); } if (!from_file.isFile()) { throw new IOException("FileCopy: can't copy directory: " + from_file.getPath()); } if (!from_file.canRead()) { throw new IOException("FileCopy: source file is unreadable: " + from_file.getPath()); } if (to_file.isDirectory()) { to_file = new File(to_file, from_file.getName()); } if (to_file.exists()) { if (!to_file.canWrite()) { throw new IOException("FileCopy: destination file is unwriteable: " + to_file.getPath()); } int choice = JOptionPane.showConfirmDialog(null, "Overwrite existing file " + to_file.getPath(), "File Exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (choice != JOptionPane.YES_OPTION) { throw new IOException("FileCopy: existing file was not overwritten."); } } else { String parent = to_file.getParent(); if (parent == null) { parent = Globals.getDefaultPath(); } 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(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) { } } } }
11
Code Sample 1: public void dispatch(com.sun.star.util.URL aURL, com.sun.star.beans.PropertyValue[] aArguments) { if (aURL.Protocol.compareTo("org.openoffice.oosvn.oosvn:") == 0) { OoDocProperty docProperty = getProperty(); settings.setCancelFired(false); if (aURL.Path.compareTo("svnUpdate") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (NullPointerException ex) { new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; new DialogFileChooser(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = -1; if (logs.length == 0) { error("Sorry, the specified repository is empty."); return; } new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); if (settings.getCancelFired()) return; File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File[] tempFiles = tempDir.listFiles(); File anyOdt = null; File thisOdt = null; for (int j = 0; j < tempFiles.length; j++) { if (tempFiles[j].toString().endsWith(".odt")) anyOdt = tempFiles[j]; if (tempFiles[j].toString().equals(settings.getCheckoutDoc()) && settings.getCheckoutDoc() != null) thisOdt = tempFiles[j]; } if (thisOdt != null) anyOdt = thisOdt; String url; if (settings.getCheckoutDoc() == null || !settings.getCheckoutDoc().equals(anyOdt.getName())) { File newOdt = new File(settings.getCheckoutPath() + "/" + anyOdt.getName()); if (newOdt.exists()) newOdt.delete(); anyOdt.renameTo(newOdt); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } url = "file:///" + newOdt.getPath().replace("\\", "/"); svnInfo.renameTo(newSvnInfo); anyOdt = newOdt; loadDocumentFromUrl(url); settings.setCheckoutDoc(anyOdt.getName()); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } else { try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } url = "file:///" + anyOdt.getPath().replace("\\", "/"); XDispatchProvider xDispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, m_xFrame); PropertyValue property[] = new PropertyValue[1]; property[0] = new PropertyValue(); property[0].Name = "URL"; property[0].Value = url; XMultiServiceFactory xMSF = createProvider(); Object objDispatchHelper = m_xServiceManager.createInstanceWithContext("com.sun.star.frame.DispatchHelper", m_xContext); XDispatchHelper xDispatchHelper = (XDispatchHelper) UnoRuntime.queryInterface(XDispatchHelper.class, objDispatchHelper); xDispatchHelper.executeDispatch(xDispatchProvider, ".uno:CompareDocuments", "", 0, property); } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnCommit") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Collection logs = svnWorker.getLogs(settings); long headRevision = svnWorker.getHeadRevisionNumber(logs); long committedRevision = -1; new DialogCommitMessage(new javax.swing.JFrame(), true, settings).setVisible(true); if (settings.getCancelFired()) return; try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } if (headRevision == 0) { File impDir = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import"); if (impDir.exists()) if (deleteFileDir(impDir) == false) { error("Error while creating temporary import directory."); return; } if (!impDir.mkdirs()) { error("Error while creating temporary import directory."); return; } File impFile = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.import/" + settings.getCheckoutDoc()); try { FileChannel srcChannel = new FileInputStream(settings.getCheckoutPath() + "/" + settings.getCheckoutDoc()).getChannel(); FileChannel dstChannel = new FileOutputStream(impFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { error("Error while importing file", ex); return; } final String checkoutPath = settings.getCheckoutPath(); try { settings.setCheckoutPath(impDir.toString()); committedRevision = svnWorker.importDirectory(settings, false).getNewRevision(); } catch (Exception ex) { settings.setCheckoutPath(checkoutPath); error("Error while importing file", ex); return; } settings.setCheckoutPath(checkoutPath); if (impDir.exists()) if (deleteFileDir(impDir) == false) error("Error while creating temporary import directory."); try { File newSvnInfo = new File(settings.getCheckoutPath() + "/.svn"); if (newSvnInfo.exists()) { if (deleteFileDir(newSvnInfo) == false) { error("Error while deleting temporary checkout dir."); } } File tempDir = new File(settings.getCheckoutPath() + svnWorker.tempDir); if (tempDir.exists()) { if (deleteFileDir(tempDir) == false) { error("Error while deleting temporary checkout dir."); } } svnWorker.checkout(settings); File svnInfo = new File(settings.getCheckoutPath() + svnWorker.tempDir + "/.svn"); svnInfo.renameTo(newSvnInfo); if (deleteFileDir(tempDir) == false) { error("Error while managing working copy"); } try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when re-newing settings.", ex); } } catch (Exception ex) { error("Error while checking out a working copy for the location", ex); } showMessageBox("Import succesful", "Succesfully imported as revision no. " + committedRevision); return; } else { try { committedRevision = svnWorker.commit(settings, false).getNewRevision(); } catch (Exception ex) { error("Error while committing changes. If the file is not working copy, you must use 'Checkout / Update' first.", ex); } if (committedRevision == -1) { showMessageBox("Update - no changes", "No changes was made. Maybe you must just save the changes."); } else { showMessageBox("Commit succesfull", "Commited as revision no. " + committedRevision); } } } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("svnHistory") == 0) { try { try { settings = getSerializedSettings(docProperty); } catch (Exception ex) { error("Error getting settings", ex); return; } Object[][] logs = getLogs(settings); long checkVersion = settings.getCheckoutVersion(); settings.setCheckoutVersion(-99); new DialogSVNHistory(new javax.swing.JFrame(), true, settings, logs).setVisible(true); settings.setCheckoutVersion(checkVersion); } catch (Exception ex) { error(ex); } return; } if (aURL.Path.compareTo("settings") == 0) { try { settings = getSerializedSettings(docProperty); } catch (NoSerializedSettingsException ex) { try { settings.setCheckout(docProperty.getDocURL()); } catch (Exception exx) { } } catch (Exception ex) { error("Error getting settings; maybe you" + " need to save your document." + " If this is your first" + " checkout of the document, use Checkout" + " function directly."); return; } new DialogSettings(new javax.swing.JFrame(), true, settings).setVisible(true); try { settings.serializeOut(); } catch (Exception ex) { error("Error occured when saving settings.", ex); } return; } if (aURL.Path.compareTo("about") == 0) { showMessageBox("OoSvn :: About", "Autor: �t�p�n Cenek ([email protected])"); return; } } } Code Sample 2: public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) { log.fatal("not a http request"); return; } HttpServletRequest httpRequest = (HttpServletRequest) request; String uri = httpRequest.getRequestURI(); int pathStartIdx = 0; String resourceName = null; pathStartIdx = uri.indexOf(path); if (pathStartIdx <= -1) { log.fatal("the url pattern must match: " + path + " found uri: " + uri); return; } resourceName = uri.substring(pathStartIdx + path.length()); int suffixIdx = uri.lastIndexOf('.'); if (suffixIdx <= -1) { log.fatal("no file suffix found for resource: " + uri); return; } String suffix = uri.substring(suffixIdx + 1).toLowerCase(); String mimeType = (String) mimeTypes.get(suffix); if (mimeType == null) { log.fatal("no mimeType found for resource: " + uri); log.fatal("valid mimeTypes are: " + mimeTypes.keySet()); return; } String themeName = getThemeName(); if (themeName == null) { themeName = this.themeName; } if (!themeName.startsWith("/")) { themeName = "/" + themeName; } InputStream is = null; is = ResourceFilter.class.getResourceAsStream(themeName + resourceName); if (is != null) { IOUtils.copy(is, response.getOutputStream()); response.setContentType(mimeType); response.flushBuffer(); IOUtils.closeQuietly(response.getOutputStream()); IOUtils.closeQuietly(is); } else { log.fatal("error loading resource: " + resourceName); } }
11
Code Sample 1: private void _PostParser(Document document, AnnotationManager annoMan, Document htmldoc, String baseurl) { xformer = annoMan.getTransformer(); builder = annoMan.getBuilder(); String annohash = ""; if (document == null) return; NodeList ndlist = document.getElementsByTagNameNS(annoNS, "body"); if (ndlist.getLength() != 1) { System.out.println("Sorry Annotation Body was found " + ndlist.getLength() + " times"); return; } Element bodynode = (Element) ndlist.item(0); Node htmlNode = bodynode.getElementsByTagName("html").item(0); if (htmlNode == null) htmlNode = bodynode.getElementsByTagName("HTML").item(0); Document newdoc = builder.newDocument(); Element rootelem = newdoc.createElementNS(rdfNS, "r:RDF"); rootelem.setAttribute("xmlns:r", rdfNS); rootelem.setAttribute("xmlns:a", annoNS); rootelem.setAttribute("xmlns:d", dubNS); rootelem.setAttribute("xmlns:t", threadNS); newdoc.appendChild(rootelem); Element tmpelem; NodeList tmpndlist; Element annoElem = newdoc.createElementNS(annoNS, "a:Annotation"); rootelem.appendChild(annoElem); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "context").item(0); String context = tmpelem.getChildNodes().item(0).getNodeValue(); annoElem.setAttributeNS(annoNS, "a:context", context); NodeList elemcontl = tmpelem.getElementsByTagNameNS(alNS, "context-element"); Node ncontext_element = null; if (elemcontl.getLength() > 0) { Node old_context_element = elemcontl.item(0); ncontext_element = newdoc.importNode(old_context_element, true); } tmpndlist = document.getElementsByTagNameNS(dubNS, "title"); annoElem.setAttributeNS(dubNS, "d:title", tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "Default"); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "creator").item(0); annoElem.setAttributeNS(dubNS, "d:creator", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(annoNS, "created").item(0); annoElem.setAttributeNS(annoNS, "a:created", tmpelem.getChildNodes().item(0).getNodeValue()); tmpelem = (Element) document.getElementsByTagNameNS(dubNS, "date").item(0); annoElem.setAttributeNS(dubNS, "d:date", tmpelem.getChildNodes().item(0).getNodeValue()); tmpndlist = document.getElementsByTagNameNS(dubNS, "language"); String language = (tmpndlist.getLength() > 0 ? tmpndlist.item(0).getChildNodes().item(0).getNodeValue() : "en"); annoElem.setAttributeNS(dubNS, "d:language", language); Node typen = newdoc.importNode(document.getElementsByTagNameNS(rdfNS, "type").item(0), true); annoElem.appendChild(typen); Element contextn = newdoc.createElementNS(annoNS, "a:context"); contextn.setAttributeNS(rdfNS, "r:resource", context); annoElem.appendChild(contextn); Node annotatesn = newdoc.importNode(document.getElementsByTagNameNS(annoNS, "annotates").item(0), true); annoElem.appendChild(annotatesn); Element newbodynode = newdoc.createElementNS(annoNS, "a:body"); annoElem.appendChild(newbodynode); if (ncontext_element != null) { contextn.appendChild(ncontext_element); } else { System.out.println("No context element found, we create one..."); try { XPointer xptr = new XPointer(htmldoc); NodeRange xprange = xptr.getRange(context, htmldoc); Element context_elem = newdoc.createElementNS(alNS, "al:context-element"); context_elem.setAttributeNS(alNS, "al:text", xprange.getContentString()); context_elem.appendChild(newdoc.createTextNode(annoMan.generateContextString(xprange))); contextn.appendChild(context_elem); } catch (XPointerRangeException e2) { e2.printStackTrace(); } } WordFreq wf = new WordFreq(annoMan.extractTextFromNode(htmldoc)); Element docident = newdoc.createElementNS(alNS, "al:document-identifier"); annotatesn.appendChild(docident); docident.setAttributeNS(alNS, "al:orig-url", ((Element) annotatesn).getAttributeNS(rdfNS, "resource")); docident.setAttributeNS(alNS, "al:version", "1"); Iterator it = null; it = wf.getSortedWordlist(); Map.Entry ent; String word; int count; int i = 0; while (it.hasNext()) { ent = (Map.Entry) it.next(); word = ((String) ent.getKey()); count = ((Counter) ent.getValue()).count; if ((word.length() > 4) && (i < 10)) { Element wordelem = newdoc.createElementNS(alNS, "al:word"); wordelem.setAttributeNS(alNS, "al:freq", Integer.toString(count)); wordelem.appendChild(newdoc.createTextNode(word)); docident.appendChild(wordelem); i++; } } try { StringWriter strw = new StringWriter(); MessageDigest messagedigest = MessageDigest.getInstance("MD5"); xformer.transform(new DOMSource(newdoc), new StreamResult(strw)); messagedigest.update(strw.toString().getBytes()); byte[] md5bytes = messagedigest.digest(); annohash = ""; for (int b = 0; b < md5bytes.length; b++) { String s = Integer.toHexString(md5bytes[b] & 0xFF); annohash = annohash + ((s.length() == 1) ? "0" + s : s); } this.annohash = annohash; annoElem.setAttribute("xmlns:al", alNS); annoElem.setAttributeNS(alNS, "al:id", getAnnohash()); Location = (baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); newbodynode.setAttributeNS(rdfNS, "r:resource", baseurl + "/annotation/body/" + getAnnohash()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } annoMan.store(newdoc.getDocumentElement()); annoMan.createAnnoResource(newdoc.getDocumentElement(), getAnnohash()); if (htmlNode != null) annoMan.createAnnoBody(htmlNode, getAnnohash()); Location = (this.baseurl + "/annotation/" + getAnnohash()); annoElem.setAttributeNS(rdfNS, "r:about", Location); this.responseDoc = newdoc; } Code Sample 2: public String login(HttpSession callingSession, String username, String password) { String token = null; String customer = null; int timeoutInSeconds = 0; HashSet<Integer> tileProviderIds = new HashSet<Integer>(); boolean bLoginOk = false; String dbPassword = (String) em.createNamedQuery("getCustomerPasswordByUsername").setParameter("username", username).getSingleResult(); if (dbPassword.equals(password)) { CustomerElement ce = (CustomerElement) em.createNamedQuery("getCustomerByUsername").setParameter("username", username).getSingleResult(); customer = ce.getName(); timeoutInSeconds = ce.getTimeout(); String[] tileProviderIdsArray = ce.getTileProvideridsArray(); for (String tileProviderId : tileProviderIdsArray) tileProviderIds.add(Integer.parseInt(tileProviderId)); bLoginOk = true; } if (bLoginOk) { token = SessionHandler.getInstance().alreadyGotValidSession(customer); if (token == null) { Random random = new Random(); token = callingSession.getId() + new Date().getTime() + random.nextLong(); MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { logger.error("Unable to digest the token.", e); } md5.update(token.getBytes()); byte[] array = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } token = sb.toString(); SessionHandler.getInstance().registerValidSession(token, customer, timeoutInSeconds, tileProviderIds); } } return token; }
00
Code Sample 1: private byte[] rawHttpPost(URL serverTimeStamp, Hashtable reqProperties, byte[] postData) { logger.info("[rawHttpPost.in]:: " + Arrays.asList(new Object[] { serverTimeStamp, reqProperties, postData })); URLConnection urlConn; DataOutputStream printout; DataInputStream input; byte[] responseBody = null; try { urlConn = serverTimeStamp.openConnection(); urlConn.setDoInput(true); urlConn.setDoOutput(true); urlConn.setUseCaches(false); Iterator iter = reqProperties.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); urlConn.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } logger.debug("POSTing to: " + serverTimeStamp + " ..."); printout = new DataOutputStream(urlConn.getOutputStream()); printout.write(postData); printout.flush(); printout.close(); input = new DataInputStream(urlConn.getInputStream()); byte[] buffer = new byte[1024]; int bytesRead = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { baos.write(buffer, 0, bytesRead); } input.close(); responseBody = baos.toByteArray(); } catch (MalformedURLException me) { logger.warn("[rawHttpPost]:: ", me); } catch (IOException ioe) { logger.warn("[rawHttpPost]:: ", ioe); } return responseBody; } Code Sample 2: public static File copyFile(File fileToCopy, File copiedFile) { BufferedInputStream in = null; BufferedOutputStream outWriter = null; if (!copiedFile.exists()) { try { copiedFile.createNewFile(); } catch (IOException e1) { ExceptionHandlingService.INSTANCE.handleException(e1); return null; } } try { in = new BufferedInputStream(new FileInputStream(fileToCopy), 4096); outWriter = new BufferedOutputStream(new FileOutputStream(copiedFile), 4096); int c; while ((c = in.read()) != -1) outWriter.write(c); in.close(); outWriter.close(); } catch (FileNotFoundException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } catch (IOException e) { ExceptionHandlingService.INSTANCE.handleException(e); return null; } return copiedFile; }
00
Code Sample 1: public static String ReadURLStringAndWrite(URL url, String str) throws Exception { String stringToReverse = URLEncoder.encode(str, "UTF-8"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); out.write(stringToReverse); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String decodedString; String back = ""; while ((decodedString = in.readLine()) != null) { back += decodedString + "\n"; } in.close(); return back; } Code Sample 2: 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:&nbsp;</td><td>"); out.write(Long.toString(base)); out.write("</td></tr>\n<tr><td>Deleted:&nbsp;</td><td>"); out.write(Long.toString(deleted)); out.write("</td></tr>\n<tr><td>Modified:&nbsp;</td><td>"); out.write(Long.toString(modified)); out.write("</td></tr>\n<tr><td>Added:&nbsp;</td><td>"); out.write(Long.toString(added)); out.write("</td></tr>\n<tr><td>New & Changed:&nbsp;</td><td>"); out.write(Long.toString(added + modified)); out.write("</td></tr>\n"); } out.write("<tr><td>Total:&nbsp;</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: private void validateODFDoc(String url, String ver, ValidationReport commentary) throws IOException, MalformedURLException { logger.debug("Beginning document validation ..."); synchronized (ODFValidationSession.class) { PropertyMapBuilder builder = new PropertyMapBuilder(); String[] segments = url.split("/"); CommentatingErrorHandler h = new CommentatingErrorHandler(commentary, segments[segments.length - 1]); ValidateProperty.ERROR_HANDLER.put(builder, h); ValidationDriver driver = new ValidationDriver(builder.toPropertyMap()); InputStream candidateStream = null; try { logger.debug("Loading schema version " + ver); byte[] schemaBytes = getSchemaForVersion(ver); driver.loadSchema(new InputSource(new ByteArrayInputStream(schemaBytes))); URLConnection conn = new URL(url).openConnection(); candidateStream = conn.getInputStream(); logger.debug("Calling validate()"); commentary.incIndent(); boolean isValid = driver.validate(new InputSource(candidateStream)); logger.debug("Errors in instance:" + h.getInstanceErrCount()); if (h.getInstanceErrCount() > CommentatingErrorHandler.THRESHOLD) { commentary.addComment("(<i>" + (h.getInstanceErrCount() - CommentatingErrorHandler.THRESHOLD) + " error(s) omitted for the sake of brevity</i>)"); } commentary.decIndent(); if (isValid) { commentary.addComment("The document is valid"); } else { commentary.addComment("ERROR", "The document is invalid"); } } catch (SAXException e) { commentary.addComment("FATAL", "The resource is not conformant XML: " + e.getMessage()); logger.error(e.getMessage()); } finally { Utils.streamClose(candidateStream); } } } Code Sample 2: public int deleteFile(Integer[] fileID) throws SQLException { PreparedStatement pstmt = null; ResultSet rs = null; Connection conn = null; int nbrow = 0; try { DataSource ds = getDataSource(DEFAULT_DATASOURCE); conn = ds.getConnection(); conn.setAutoCommit(false); if (log.isDebugEnabled()) { log.debug("FileDAOImpl.deleteFile() " + DELETE_FILES_LOGIC); } for (int i = 0; i < fileID.length; i++) { pstmt = conn.prepareStatement(DELETE_FILES_LOGIC); pstmt.setInt(1, fileID[i].intValue()); nbrow = pstmt.executeUpdate(); } } catch (SQLException e) { conn.rollback(); log.error("FileDAOImpl.deleteFile() : erreur technique", e); throw e; } finally { conn.commit(); closeRessources(conn, pstmt, rs); } return nbrow; }
00
Code Sample 1: public String getUser() { try { HttpGet get = new HttpGet("http://twemoi.status.net/api/account/verify_credentials.xml"); consumer.sign(get); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(get); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); return ""; } StringBuffer sBuf = new StringBuffer(); String linea; BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); while ((linea = reader.readLine()) != null) { sBuf.append(linea); } reader.close(); response.getEntity().consumeContent(); get.abort(); String salida = sBuf.toString(); String user_name = salida.split("</screen_name>")[0].split("<screen_name>")[1]; return user_name; } } catch (UnsupportedEncodingException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (IOException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthMessageSignerException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthExpectationFailedException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } catch (OAuthCommunicationException e) { this.enviarMensaje("Error: Usuario no autenticado en la red de Status"); } return null; } Code Sample 2: @Override protected void write(InputStream in, OutputStream out, javax.sound.sampled.AudioFormat javaSoundFormat) throws IOException { if (USE_JAVASOUND) { super.write(in, out, javaSoundFormat); } else { try { byte[] header = JavaSoundCodec.createWavHeader(javaSoundFormat); if (header == null) throw new IOException("Unable to create wav header"); out.write(header); IOUtils.copyStream(in, out); } catch (InterruptedIOException e) { logger.log(Level.FINE, "" + e, e); throw e; } catch (IOException e) { logger.log(Level.WARNING, "" + e, e); throw e; } } }
00
Code Sample 1: private void copy(File sourceFile, File destinationFile) { try { FileChannel in = new FileInputStream(sourceFile).getChannel(); FileChannel out = new FileOutputStream(destinationFile).getChannel(); try { in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { } } catch (FileNotFoundException e) { } } Code Sample 2: public OperandToken evaluate(Token[] operands, GlobalValues globals) { String s = ""; String lineFile = ""; ; if (getNArgIn(operands) != 1) throwMathLibException("urlread: number of arguments < 1"); if (!(operands[0] instanceof CharToken)) throwMathLibException("urlread: argument must be String"); String urlString = ((CharToken) operands[0]).toString(); URL url = null; try { url = new URL(urlString); } catch (Exception e) { throwMathLibException("urlread: malformed url"); } try { BufferedReader inReader = new BufferedReader(new InputStreamReader(url.openStream())); while ((lineFile = inReader.readLine()) != null) { s += lineFile + "\n"; } inReader.close(); } catch (Exception e) { throwMathLibException("urlread: error input stream"); } return new CharToken(s); }
11
Code Sample 1: private void appendArchive() throws Exception { String cmd; if (profile == CompilationProfile.UNIX_GCC) { cmd = "cat"; } else if (profile == CompilationProfile.MINGW_WINDOWS) { cmd = "type"; } else { throw new Exception("Unknown cat equivalent for profile " + profile); } compFrame.writeLine("<span style='color: green;'>" + cmd + " \"" + imageArchive.getAbsolutePath() + "\" >> \"" + outputFile.getAbsolutePath() + "\"</span>"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile, true)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(imageArchive)); int read; while ((read = in.read()) != -1) { out.write(read); } in.close(); out.close(); } Code Sample 2: public long copyDirAllFilesToDirectoryRecursive(String baseDirStr, String destDirStr, boolean copyOutputsRtIDsDirs) throws Exception { long plussQuotaSize = 0; if (baseDirStr.endsWith(sep)) { baseDirStr = baseDirStr.substring(0, baseDirStr.length() - 1); } if (destDirStr.endsWith(sep)) { destDirStr = destDirStr.substring(0, destDirStr.length() - 1); } FileUtils.getInstance().createDirectory(destDirStr); BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File baseDir = new File(baseDirStr); baseDir.mkdirs(); if (!baseDir.exists()) { createDirectory(baseDirStr); } if ((baseDir.exists()) && (baseDir.isDirectory())) { String[] entryList = baseDir.list(); if (entryList.length > 0) { for (int pos = 0; pos < entryList.length; pos++) { String entryName = entryList[pos]; String oldPathFileName = baseDirStr + sep + entryName; File entryFile = new File(oldPathFileName); if (entryFile.isFile()) { String newPathFileName = destDirStr + sep + entryName; File newFile = new File(newPathFileName); if (newFile.exists()) { plussQuotaSize -= newFile.length(); newFile.delete(); } in = new BufferedInputStream(new FileInputStream(oldPathFileName), bufferSize); out = new BufferedOutputStream(new FileOutputStream(newPathFileName), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); plussQuotaSize += readLen; } out.flush(); in.close(); out.close(); } if (entryFile.isDirectory()) { boolean enableCopyDir = false; if (copyOutputsRtIDsDirs) { enableCopyDir = true; } else { if (entryFile.getParentFile().getName().equals("outputs")) { enableCopyDir = false; } else { enableCopyDir = true; } } if (enableCopyDir) { plussQuotaSize += this.copyDirAllFilesToDirectoryRecursive(baseDirStr + sep + entryName, destDirStr + sep + entryName, copyOutputsRtIDsDirs); } } } } } else { throw new Exception("Base dir not exist ! baseDirStr = (" + baseDirStr + ")"); } return plussQuotaSize; }