label
class label
2 classes
source_code
stringlengths
398
72.9k
11
Code Sample 1: protected String getHashCode(String value) { if (log.isDebugEnabled()) log.debug("getHashCode(...) -> begin"); String retVal = null; try { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(value.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < digest.length; i++) { sb.append(this.toHexString(digest[i])); } retVal = sb.toString(); if (log.isDebugEnabled()) log.debug("getHashCode(...) -> hashcode = " + retVal); } catch (Exception e) { log.error("getHashCode(...) -> error occured generating hashcode ", e); } if (log.isDebugEnabled()) log.debug("getHashCode(...) -> end"); return retVal; } Code Sample 2: PasswordTableWindow(String login) { super(login + ", tecle a senha de uso �nico"); this.login = login; Error.log(4001, "Autentica��o etapa 3 iniciada."); Container container = getContentPane(); container.setLayout(new FlowLayout()); btnNumber = new JButton[10]; btnOK = new JButton("OK"); btnClear = new JButton("Limpar"); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(2, 10)); ResultSet rs; Statement stmt; String sql; Vector<Integer> result = new Vector<Integer>(); sql = "select key from Senhas_De_Unica_Vez where login='" + login + "'"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { result.add(rs.getInt("key")); } rs.close(); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } Random rn = new Random(); int r = rn.nextInt(); if (result.size() == 0) { rn = new Random(); Vector<Integer> passwordVector = new Vector<Integer>(); Vector<String> hashVector = new Vector<String>(); for (int i = 0; i < 10; i++) { r = rn.nextInt() % 10000; if (r < 0) r = r * (-1); passwordVector.add(r); } try { BufferedWriter out = new BufferedWriter(new FileWriter(login + ".txt", false)); for (int i = 0; i < 10; i++) { out.append("" + i + " " + passwordVector.get(i) + "\n"); } out.close(); try { for (int i = 0; i < 10; i++) { MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(passwordVector.get(i).toString().getBytes()); BigInteger bigInt = new BigInteger(1, messageDigest.digest()); String digest = bigInt.toString(16); sql = "insert into Senhas_De_Unica_Vez (login,key,password) values " + "('" + login + "'," + i + ",'" + digest + "')"; try { theConn = DatabaseConnection.getConnection(); stmt = theConn.createStatement(); stmt.executeUpdate(sql); stmt.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { try { if (theConn != null) theConn.close(); } catch (Exception exception) { } } } } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } JOptionPane.showMessageDialog(null, "nova tabela de senhas criada para o usu�rio " + login + "."); Error.log(1002, "Sistema encerrado"); System.exit(0); } if (r < 0) r = r * (-1); int index = r % result.size(); if (index > result.size()) index = 0; key = result.get(index); labelKey = new JLabel("Chave n�mero " + key + " "); passwordField = new JPasswordField(12); ButtonHandler handler = new ButtonHandler(); for (int i = 0; i < 10; i++) { btnNumber[i] = new JButton("" + i); buttonPanel.add(btnNumber[i]); btnNumber[i].addActionListener(handler); } btnOK.addActionListener(handler); btnClear.addActionListener(handler); container.add(buttonPanel); container.add(passwordField); container.add(labelKey); container.add(btnOK); container.add(btnClear); setSize(325, 200); setVisible(true); }
00
Code Sample 1: public static void main(String[] args) throws IOException { long readfilelen = 0; BufferedRandomAccessFile brafReadFile, brafWriteFile; brafReadFile = new BufferedRandomAccessFile("C:\\WINNT\\Fonts\\STKAITI.TTF"); readfilelen = brafReadFile.initfilelen; brafWriteFile = new BufferedRandomAccessFile(".\\STKAITI.001", "rw", 10); byte buf[] = new byte[1024]; int readcount; long start = System.currentTimeMillis(); while ((readcount = brafReadFile.read(buf)) != -1) { brafWriteFile.write(buf, 0, readcount); } brafWriteFile.close(); brafReadFile.close(); System.out.println("BufferedRandomAccessFile Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); java.io.FileInputStream fdin = new java.io.FileInputStream("C:\\WINNT\\Fonts\\STKAITI.TTF"); java.io.BufferedInputStream bis = new java.io.BufferedInputStream(fdin, 1024); java.io.DataInputStream dis = new java.io.DataInputStream(bis); java.io.FileOutputStream fdout = new java.io.FileOutputStream(".\\STKAITI.002"); java.io.BufferedOutputStream bos = new java.io.BufferedOutputStream(fdout, 1024); java.io.DataOutputStream dos = new java.io.DataOutputStream(bos); start = System.currentTimeMillis(); for (int i = 0; i < readfilelen; i++) { dos.write(dis.readByte()); } dos.close(); dis.close(); System.out.println("DataBufferedios Copy & Write File: " + brafReadFile.filename + " FileSize: " + java.lang.Integer.toString((int) readfilelen >> 1024) + " (KB) " + "Spend: " + (double) (System.currentTimeMillis() - start) / 1000 + "(s)"); } Code Sample 2: public static void main(String[] args) { FTPClient client = new FTPClient(); try { File l_file = new File("C:/temp/testLoribel.html"); String l_url = "http://www.loribel.com/index.html"; GB_HttpTools.loadUrlToFile(l_url, l_file, ENCODING.ISO_8859_1); System.out.println("Try to connect..."); client.connect("ftp://ftp.phpnet.org"); System.out.println("Connected to server"); System.out.println("Try to connect..."); boolean b = client.login("fff", "ddd"); System.out.println("Login: " + b); String[] l_names = client.listNames(); GB_DebugTools.debugArray(GB_FtpDemo2.class, "names", l_names); b = client.makeDirectory("test02/toto"); System.out.println("Mkdir: " + b); String l_remote = "test02/test.xml"; InputStream l_local = new StringInputStream("Test111111111111111"); b = client.storeFile(l_remote, l_local); System.out.println("Copy file: " + b); } catch (Exception ex) { ex.printStackTrace(); } }
00
Code Sample 1: public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); resp.getWriter().println("Getting feed..."); String googleFeed = "http://news.google.com/news?ned=us&topic=h&output=rss"; String totalFeed = ""; try { URL url = new URL(googleFeed); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = null; while ((line = reader.readLine()) != null) { totalFeed += line; } reader.close(); parseFeedandPersist(totalFeed, resp); } catch (MalformedURLException e) { } catch (IOException e) { } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
00
Code Sample 1: private static byte[] getLoginHashSHA(final char[] password, final int seed) throws GGException { try { final MessageDigest hash = MessageDigest.getInstance("SHA1"); hash.update(new String(password).getBytes()); hash.update(GGUtils.intToByte(seed)); return hash.digest(); } catch (final NoSuchAlgorithmException e) { LOG.error("SHA1 algorithm not usable", e); throw new GGException("SHA1 algorithm not usable!", e); } } Code Sample 2: public String execute(Map params, String body, RenderContext renderContext) throws MacroException { loadData(); String from = (String) params.get("from"); if (body.length() > 0 && from != null) { try { URL url; String serverUser = null; String serverPassword = null; url = new URL(semformsSettings.getZRapServerUrl() + "ZRAP_QueryProcessor.php?from=" + URLEncoder.encode(from, "utf-8") + "&query=" + URLEncoder.encode(body, "utf-8")); if (url.getUserInfo() != null) { String[] userInfo = url.getUserInfo().split(":"); if (userInfo.length == 2) { serverUser = userInfo[0]; serverPassword = userInfo[1]; } } URLConnection connection = null; InputStreamReader bf; if (serverUser != null && serverPassword != null) { connection = url.openConnection(); String encoding = new sun.misc.BASE64Encoder().encode((serverUser + ":" + serverPassword).getBytes()); connection.setRequestProperty("Authorization", "Basic " + encoding); bf = new InputStreamReader(connection.getInputStream()); } else { bf = new InputStreamReader(url.openStream()); } BufferedReader bbf = new BufferedReader(bf); String line = bbf.readLine(); String buffer = ""; while (line != null) { buffer += line; line = bbf.readLine(); } return buffer; } catch (Exception e) { e.printStackTrace(); return "ERROR:" + e.getLocalizedMessage(); } } else return "Please write an RDQL query in the macro as body and an url of the model as 'from' parameter"; }
00
Code Sample 1: public void viewFile(int file_nx) { FTPClient ftp = new FTPClient(); boolean error = false; try { int reply; ftp.connect("tgftp.nws.noaa.gov"); ftp.login("anonymous", ""); Log.d("WXDroid", "Connected to tgftp.nws.noaa.gov."); Log.d("WXDroid", ftp.getReplyString()); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); System.err.println("FTP server refused connection."); System.exit(1); } ftp.changeWorkingDirectory("fax"); Log.d("WXDroid", "working directory: " + ftp.printWorkingDirectory()); ftp.setFileType(FTPClient.BINARY_FILE_TYPE); InputStream img_file = ftp.retrieveFileStream("PYAA10.gif"); Intent intent = new Intent(); intent.setClass(WXdroid.this, showProgressFTP.class); startActivity(intent); String storage_state = Environment.getExternalStorageState(); if (storage_state.contains("mounted")) { String filepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/NOAAWX/"; File imageDirectory = new File(filepath); File local_file = new File(filepath + "PYAA10.gif"); OutputStream out = new FileOutputStream(local_file); byte[] buffer = new byte[1024]; int count; while ((count = img_file.read(buffer)) != -1) { if (Thread.interrupted() == true) { String functionName = Thread.currentThread().getStackTrace()[2].getMethodName() + "()"; throw new InterruptedException("The function " + functionName + " was interrupted."); } out.write(buffer, 0, count); } showImage(); out.flush(); out.close(); img_file.close(); Log.d("WXDroid", "file saved: " + filepath + " " + local_file); } else { Log.d("WXDroid", "The SD card is not mounted"); } ftp.logout(); ftp.disconnect(); } catch (IOException e) { error = true; e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } } } Code Sample 2: private void analyseCorpus(final IStatusDisplayer fStatus) { final String sDistrosFile = "Distros.tmp"; final String sSymbolsFile = "Symbols.tmp"; Chunker = new EntropyChunker(); int Levels = 2; sgOverallGraph = new SymbolicGraph(1, Levels); siIndex = new SemanticIndex(sgOverallGraph); try { siIndex.MeaningExtractor = new LocalWordNetMeaningExtractor(); } catch (IOException ioe) { siIndex.MeaningExtractor = null; } try { DocumentSet dsSet = new DocumentSet(FilePathEdt.getText(), 1.0); dsSet.createSets(true, (double) 100 / 100); int iCurCnt, iTotal; String sFile = ""; Iterator iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } appendToLog("Training chunker..."); Chunker.train(dsSet.toFilenameSet(DocumentSet.FROM_WHOLE_SET)); appendToLog("Setting delimiters..."); setDelimiters(Chunker.getDelimiters()); iCurCnt = 0; cdDoc = new DistributionDocument[Levels]; for (int iCnt = 0; iCnt < Levels; iCnt++) cdDoc[iCnt] = new DistributionDocument(1, MinLevel + iCnt); fStatus.setVisible(true); ThreadList t = new ThreadList(Runtime.getRuntime().availableProcessors() + 1); appendToLog("(Pass 1/3) Loading files..." + sFile); TreeSet tsOverallSymbols = new TreeSet(); while (iIter.hasNext()) { sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); fStatus.setStatus("(Pass 1/3) Loading file..." + sFile, (double) iCurCnt / iTotal); final DistributionDocument[] cdDocArg = cdDoc; final String sFileArg = sFile; for (int iCnt = 0; iCnt < cdDoc.length; iCnt++) { final int iCntArg = iCnt; while (!t.addThreadFor(new Runnable() { public void run() { if (!RightToLeftText) cdDocArg[iCntArg].loadDataStringFromFile(sFileArg, false); else { cdDocArg[iCntArg].setDataString(utils.reverseString(utils.loadFileToString(sFileArg)), iCntArg, false); } } })) Thread.yield(); } try { t.waitUntilCompletion(); } catch (InterruptedException ex) { ex.printStackTrace(System.err); appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } sgOverallGraph.setDataString(((new StringBuffer().append((char) StreamTokenizer.TT_EOF))).toString()); sgOverallGraph.loadFromFile(sFile); fStatus.setStatus("Loaded file..." + sFile, (double) ++iCurCnt / iTotal); Thread.yield(); } Set sSymbols = null; File fPreviousSymbols = new File(sSymbolsFile); boolean bSymbolsLoadedOK = false; if (fPreviousSymbols.exists()) { System.err.println("ATTENTION: Using previous symbols..."); try { FileInputStream fis = new FileInputStream(fPreviousSymbols); ObjectInputStream ois = new ObjectInputStream(fis); sSymbols = (Set) ois.readObject(); ois.close(); bSymbolsLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); } } if (!bSymbolsLoadedOK) sSymbols = getSymbolsByProbabilities(sgOverallGraph.getDataString(), fStatus); int iMinSymbolSize = Integer.MAX_VALUE; int iMaxSymbolSize = Integer.MIN_VALUE; Iterator iSymbol = sSymbols.iterator(); while (iSymbol.hasNext()) { String sCurSymbol = (String) iSymbol.next(); if (iMaxSymbolSize < sCurSymbol.length()) iMaxSymbolSize = sCurSymbol.length(); if (iMinSymbolSize > sCurSymbol.length()) iMinSymbolSize = sCurSymbol.length(); } try { FileOutputStream fos = new FileOutputStream(sSymbolsFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(sSymbols); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } appendToLog("(Pass 2/3) Determining symbol distros per n-gram size..."); iIter = dsSet.getTrainingSet().iterator(); iTotal = dsSet.getTrainingSet().size(); if (iTotal == 0) { appendToLog("No input documents.\n"); appendToLog("======DONE=====\n"); return; } iCurCnt = 0; Distribution dSymbolsPerSize = new Distribution(); Distribution dNonSymbolsPerSize = new Distribution(); Distribution dSymbolSizes = new Distribution(); File fPreviousRun = new File(sDistrosFile); boolean bDistrosLoadedOK = false; if (fPreviousRun.exists()) { System.err.println("ATTENTION: Using previous distros..."); try { FileInputStream fis = new FileInputStream(fPreviousRun); ObjectInputStream ois = new ObjectInputStream(fis); dSymbolsPerSize = (Distribution) ois.readObject(); dNonSymbolsPerSize = (Distribution) ois.readObject(); dSymbolSizes = (Distribution) ois.readObject(); ois.close(); bDistrosLoadedOK = true; } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } catch (ClassNotFoundException ex) { ex.printStackTrace(System.err); dSymbolsPerSize = new Distribution(); dNonSymbolsPerSize = new Distribution(); dSymbolSizes = new Distribution(); } } if (!bDistrosLoadedOK) while (iIter.hasNext()) { fStatus.setStatus("(Pass 2/3) Parsing file..." + sFile, (double) iCurCnt++ / iTotal); sFile = ((CategorizedFileEntry) iIter.next()).getFileName(); String sDataString = ""; try { ByteArrayOutputStream bsOut = new ByteArrayOutputStream(); FileInputStream fiIn = new FileInputStream(sFile); int iData = 0; while ((iData = fiIn.read()) > -1) bsOut.write(iData); sDataString = bsOut.toString(); } catch (IOException ioe) { ioe.printStackTrace(System.err); } final Distribution dSymbolsPerSizeArg = dSymbolsPerSize; final Distribution dNonSymbolsPerSizeArg = dNonSymbolsPerSize; final Distribution dSymbolSizesArg = dSymbolSizes; final String sDataStringArg = sDataString; final Set sSymbolsArg = sSymbols; for (int iSymbolSize = iMinSymbolSize; iSymbolSize <= iMaxSymbolSize; iSymbolSize++) { final int iSymbolSizeArg = iSymbolSize; while (!t.addThreadFor(new Runnable() { public void run() { NGramDocument ndCur = new NGramDocument(iSymbolSizeArg, iSymbolSizeArg, 1, iSymbolSizeArg, iSymbolSizeArg); ndCur.setDataString(sDataStringArg); int iSymbolCnt = 0; int iNonSymbolCnt = 0; Iterator iExtracted = ndCur.getDocumentGraph().getGraphLevel(0).getVertexSet().iterator(); while (iExtracted.hasNext()) { String sCur = ((Vertex) iExtracted.next()).toString(); if (sSymbolsArg.contains(sCur)) { iSymbolCnt++; synchronized (dSymbolSizesArg) { dSymbolSizesArg.setValue(sCur.length(), dSymbolSizesArg.getValue(sCur.length()) + 1.0); } } else iNonSymbolCnt++; } synchronized (dSymbolsPerSizeArg) { dSymbolsPerSizeArg.setValue(iSymbolSizeArg, dSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iSymbolCnt); } synchronized (dNonSymbolsPerSizeArg) { dNonSymbolsPerSizeArg.setValue(iSymbolSizeArg, dNonSymbolsPerSizeArg.getValue(iSymbolSizeArg) + iNonSymbolCnt); } } })) Thread.yield(); } } if (!bDistrosLoadedOK) try { t.waitUntilCompletion(); try { FileOutputStream fos = new FileOutputStream(sDistrosFile); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(dSymbolsPerSize); oos.writeObject(dNonSymbolsPerSize); oos.writeObject(dSymbolSizes); oos.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(System.err); } catch (IOException ex) { ex.printStackTrace(System.err); } } catch (InterruptedException ex) { appendToLog("Interrupted..."); sgOverallGraph.removeNotificationListener(); return; } appendToLog("\n(Pass 3/3) Determining optimal n-gram range...\n"); NGramSizeEstimator nseEstimator = new NGramSizeEstimator(dSymbolsPerSize, dNonSymbolsPerSize); IntegerPair p = nseEstimator.getOptimalRange(); appendToLog("\nProposed n-gram sizes:" + p.first() + "," + p.second()); fStatus.setStatus("Determining optimal distance...", 0.0); DistanceEstimator de = new DistanceEstimator(dSymbolsPerSize, dNonSymbolsPerSize, nseEstimator); int iBestDist = de.getOptimalDistance(1, nseEstimator.getMaxRank() * 2, p.first(), p.second()); fStatus.setStatus("Determining optimal distance...", 1.0); appendToLog("\nOptimal distance:" + iBestDist); appendToLog("======DONE=====\n"); } finally { sgOverallGraph.removeNotificationListener(); } }
11
Code Sample 1: public static void copyFile(final File source, final File target) throws FileNotFoundException, IOException { FileChannel in = new FileInputStream(source).getChannel(), out = new FileOutputStream(target).getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (in.read(buffer) != -1) { buffer.flip(); out.write(buffer); buffer.clear(); } out.close(); in.close(); } Code Sample 2: public static void copyFile(File fromFile, File toFile) throws OWFileCopyException { try { FileChannel src = new FileInputStream(fromFile).getChannel(); FileChannel dest = new FileOutputStream(toFile).getChannel(); dest.transferFrom(src, 0, src.size()); src.close(); dest.close(); } catch (IOException e) { throw (new OWFileCopyException("An error occurred while copying a file", e)); } }
00
Code Sample 1: private void nioBuild() { try { final ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 4); final FileChannel out = new FileOutputStream(dest).getChannel(); for (File part : parts) { setState(part.getName(), BUILDING); FileChannel in = new FileInputStream(part).getChannel(); while (in.read(buffer) > 0) { buffer.flip(); written += out.write(buffer); buffer.clear(); } in.close(); } out.close(); } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
00
Code Sample 1: protected void serveStaticContent(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException { InputStream is = servletConfig.getServletContext().getResourceAsStream(pathInfo); if (is == null) { throw new ServletException("Static resource " + pathInfo + " is not available"); } try { int ind = pathInfo.lastIndexOf("."); if (ind != -1 && ind < pathInfo.length()) { String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1)); if (type != null) { response.setContentType(type); } } ServletOutputStream os = response.getOutputStream(); IOUtils.copy(is, os); os.flush(); } catch (IOException ex) { throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream"); } } Code Sample 2: private void updateIngredients(Recipe recipe, int id) throws Exception { PreparedStatement pst1 = null; PreparedStatement pst2 = null; try { conn = getConnection(); pst1 = conn.prepareStatement("DELETE FROM ingredients WHERE recipe_id = ?"); pst1.setInt(1, id); if (pst1.executeUpdate() >= 0) { pst2 = conn.prepareStatement("INSERT INTO ingredients (recipe_id, name, amount, measure_id, shop_flag) VALUES (?,?,?,?,?)"); IngredientContainer ings = recipe.getIngredients(); Ingredient ingBean = null; Iterator it; for (it = ings.getIngredients().iterator(); it.hasNext(); ) { ingBean = (Ingredient) it.next(); pst2.setInt(1, id); pst2.setString(2, ingBean.getName()); pst2.setDouble(3, ingBean.getAmount()); pst2.setInt(4, ingBean.getType()); pst2.setInt(5, ingBean.getShopFlag()); pst2.executeUpdate(); } } conn.commit(); } catch (Exception e) { conn.rollback(); MainFrame.appendStatusText("Can't add ingredient, the exception was " + e.getMessage()); } finally { try { if (pst1 != null) pst1.close(); pst1 = null; if (pst2 != null) pst2.close(); pst2 = null; } catch (Exception ex) { MainFrame.appendStatusText("Can't close database connection."); } } }
11
Code Sample 1: private static String hashToMD5(String sig) { try { MessageDigest lDigest = MessageDigest.getInstance("MD5"); lDigest.update(sig.getBytes()); BigInteger lHashInt = new BigInteger(1, lDigest.digest()); return String.format("%1$032X", lHashInt).toLowerCase(); } catch (NoSuchAlgorithmException lException) { throw new RuntimeException(lException); } } Code Sample 2: public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; }
00
Code Sample 1: private static void salvarArtista(Artista artista) throws Exception { Connection conn = null; PreparedStatement ps = null; try { conn = C3P0Pool.getConnection(); String sql = "insert into artista VALUES (?,?,?,?,?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, artista.getNumeroInscricao()); ps.setString(2, artista.getNome()); ps.setBoolean(3, artista.isSexo()); ps.setString(4, artista.getEmail()); ps.setString(5, artista.getObs()); ps.setString(6, artista.getTelefone()); ps.setNull(7, Types.INTEGER); ps.executeUpdate(); salvarEndereco(conn, ps, artista); conn.commit(); } catch (Exception e) { if (conn != null) conn.rollback(); throw e; } finally { close(conn, ps); } } Code Sample 2: public static String MD5(String s) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException ex) { return ""; } }
00
Code Sample 1: public Component loadComponent(URI uri, URI origuri) throws ComponentException { if (usePrivMan) PrivilegeManager.enablePrivilege("UniversalConnect"); ConzillaRDFModel model = factory.createModel(origuri, uri); RDFParser parser = new com.hp.hpl.jena.rdf.arp.StanfordImpl(); java.net.URL url = null; try { url = uri.getJavaURL(); } catch (java.net.MalformedURLException e) { throw new ComponentException("Invalid URL " + uri + " for component " + origuri + ":\n " + e.getMessage()); } try { InputSource source = new InputSource(url.openStream()); source.setSystemId(origuri.toString()); parser.parse(source, new ModelConsumer(model)); factory.getTotalModel().addModel(model); } catch (org.xml.sax.SAXException se) { se.getException().printStackTrace(); throw new ComponentException("Format error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage()); } catch (java.io.IOException se) { throw new ComponentException("IO error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage()); } catch (org.w3c.rdf.model.ModelException se) { throw new ComponentException("Model error loading URL " + url + " for component " + origuri + ":\n " + se.getMessage()); } return model; } Code Sample 2: public static void saveURL(URL url, Writer writer) throws IOException { BufferedInputStream in = new BufferedInputStream(url.openStream()); for (int c = in.read(); c != -1; c = in.read()) { writer.write(c); } }
11
Code Sample 1: private void publishMap(LWMap map) throws IOException { File savedMap = PublishUtil.saveMap(map); InputStream istream = new BufferedInputStream(new FileInputStream(savedMap)); OutputStream ostream = new BufferedOutputStream(new FileOutputStream(ActionUtil.selectFile("ConceptMap", "vue"))); int fileLength = (int) savedMap.length(); byte bytes[] = new byte[fileLength]; while (istream.read(bytes, 0, fileLength) != -1) ostream.write(bytes, 0, fileLength); istream.close(); ostream.close(); } Code Sample 2: public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); }
00
Code Sample 1: public static void buildPerMovieDiffBinary(String completePath, String slopeOneDataFolderName, String slopeOneDataFileName) { try { File inFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + slopeOneDataFileName); FileChannel inC = new FileInputStream(inFile).getChannel(); for (int i = 1; i <= 17770; i++) { File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + slopeOneDataFolderName + fSep + "Movie-" + i + "-SlopeOneData.txt"); FileChannel outC = new FileOutputStream(outFile).getChannel(); ByteBuffer buf = ByteBuffer.allocate(17770 * 10); for (int j = 1; j < i; j++) { ByteBuffer bbuf = ByteBuffer.allocate(12); inC.position((17769 * 17770 * 6) - ((17769 - (j - 1)) * (17770 - (j - 1)) * 6) + (i - j - 1) * 12); inC.read(bbuf); bbuf.flip(); buf.putShort(bbuf.getShort()); bbuf.getShort(); buf.putInt(bbuf.getInt()); buf.putFloat(-bbuf.getFloat()); } buf.putShort(new Integer(i).shortValue()); buf.putInt(0); buf.putFloat(0.0f); ByteBuffer remainingBuf = inC.map(FileChannel.MapMode.READ_ONLY, (17769 * 17770 * 6) - ((17769 - (i - 1)) * (17770 - (i - 1)) * 6), (17770 - i) * 12); while (remainingBuf.hasRemaining()) { remainingBuf.getShort(); buf.putShort(remainingBuf.getShort()); buf.putInt(remainingBuf.getInt()); buf.putFloat(remainingBuf.getFloat()); } buf.flip(); outC.write(buf); buf.clear(); outC.close(); } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static String calculateHash(String data, String algorithm) { if (data == null) { return null; } algorithm = (algorithm == null ? INTERNAL : algorithm.toUpperCase()); if (algorithm.equals(PLAIN)) { return data; } if (algorithm.startsWith("{RSA}")) { return encode(data, algorithm.substring(5), "RSA"); } try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(data.getBytes("UTF-8")); return getHashString(md.digest()); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { logger.error(nsae.getMessage()); return null; } }
11
Code Sample 1: public boolean copy(String file, String path) { try { File file_in = new File(file); String tmp1, tmp2; tmp1 = file; tmp2 = path; while (tmp2.contains("\\")) { tmp2 = tmp2.substring(tmp2.indexOf("\\") + 1); tmp1 = tmp1.substring(tmp1.indexOf("\\") + 1); } tmp1 = file.substring(0, file.length() - tmp1.length()) + tmp2 + tmp1.substring(tmp1.indexOf("\\")); File file_out = new File(tmp1); File parent = file_out.getParentFile(); parent.mkdirs(); FileInputStream in1 = new FileInputStream(file_in); FileOutputStream out1 = new FileOutputStream(file_out); byte[] bytes = new byte[1024]; int c; while ((c = in1.read(bytes)) != -1) out1.write(bytes, 0, c); in1.close(); out1.close(); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("Error!"); return false; } } Code Sample 2: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
11
Code Sample 1: public void sortPlayersTurn() { Token tempT = new Token(); Player tempP = new Player("test name", tempT); int tempN = 0; boolean exchangeMade = true; for (int i = 0; i < playerNum - 1 && exchangeMade; i++) { exchangeMade = false; for (int j = 0; j < playerNum - 1 - i; j++) { if (diceSum[j] < diceSum[j + 1]) { tempP = players[j]; tempN = diceSum[j]; players[j] = players[j + 1]; diceSum[j] = diceSum[j + 1]; players[j + 1] = tempP; diceSum[j + 1] = tempN; exchangeMade = true; } } } } Code Sample 2: public static void BubbleSortDouble1(double[] num) { boolean flag = true; // set flag to true to begin first pass double temp; // holding variable while (flag) { flag = false; // set flag to false awaiting a possible swap for (int j = 0; j < num.length - 1; j++) { if (num[j] > num[j + 1]) // change to > for ascending sort { temp = num[j]; // swap elements num[j] = num[j + 1]; num[j + 1] = temp; flag = true; // shows a swap occurred } } } }
11
Code Sample 1: public synchronized String encrypt(String plaintext) throws Exception { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new Exception(e.getMessage()); } try { md.update(plaintext.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new Exception(e.getMessage()); } byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static String getEncryptedPassword(String password) throws PasswordException { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); } catch (Exception e) { throw new PasswordException(e); } return convertToString(md.digest()); }
11
Code Sample 1: public void exportFile() { String expfolder = PropertyHandler.getInstance().getProperty(PropertyHandler.KINDLE_EXPORT_FOLDER_KEY); File out = new File(expfolder + File.separator + previewInfo.getTitle() + ".prc"); File f = new File(absPath); try { FileOutputStream fout = new FileOutputStream(out); FileInputStream fin = new FileInputStream(f); int read = 0; byte[] buffer = new byte[1024 * 1024]; while ((read = fin.read(buffer)) > 0) { fout.write(buffer, 0, read); } fin.close(); fout.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: protected void copy(URL url, File file) throws IOException { InputStream in = null; FileOutputStream out = null; try { in = url.openStream(); out = new FileOutputStream(file); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } }
00
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private static String readStreamToString(InputStream is, boolean passInVelocity, String tplName, Map<String, Object> templateVarsMap) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); if (passInVelocity) { return tpl.formatStr(sw.toString(), templateVarsMap, tplName); } return sw.toString(); }
11
Code Sample 1: private String hashPassword(String password) { if (password != null && password.trim().length() > 0) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.trim().getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } } return null; } Code Sample 2: protected String md5sum(String toCompute) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toCompute.getBytes()); java.math.BigInteger hash = new java.math.BigInteger(1, md.digest()); return hash.toString(16); }
11
Code Sample 1: public static void main(String[] args) throws Exception { DES des = new DES(); StreamBlockReader reader = new StreamBlockReader(new FileInputStream("D:\\test.txt")); StreamBlockWriter writer = new StreamBlockWriter(new FileOutputStream("D:\\test1.txt")); SingleKey key = new SingleKey(new Block(64), ""); key = new SingleKey(new Block("1111111100000000111111110000000011111111000000001111111100000000"), ""); Mode mode = new ECBDESMode(des); des.encrypt(reader, writer, key, mode); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static void copyFile(File inputFile, File outputFile) throws IOException { BufferedInputStream fr = new BufferedInputStream(new FileInputStream(inputFile)); BufferedOutputStream fw = new BufferedOutputStream(new FileOutputStream(outputFile)); byte[] buf = new byte[8192]; int n; while ((n = fr.read(buf)) >= 0) fw.write(buf, 0, n); fr.close(); fw.close(); } Code Sample 2: public static boolean copyFile(File outFile, File inFile) { InputStream inStream = null; OutputStream outStream = null; try { if (outFile.createNewFile()) { inStream = new FileInputStream(inFile); outStream = new FileOutputStream(outFile); byte[] buffer = new byte[1024]; int length; while ((length = inStream.read(buffer)) > 0) outStream.write(buffer, 0, length); inStream.close(); outStream.close(); } else return false; } catch (IOException iox) { iox.printStackTrace(); return false; } return true; }
00
Code Sample 1: public static InputStream getUrlInputStream(final java.net.URL url) throws java.io.IOException, java.lang.InstantiationException { final java.net.URLConnection conn = url.openConnection(); conn.connect(); final InputStream input = url.openStream(); if (input == null) { throw new java.lang.InstantiationException("Url " + url + " does not provide data."); } return input; } 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) { } }
00
Code Sample 1: protected String loadPage(String url_string) { try { URL url = new URL(url_string); HttpURLConnection connection = null; InputStream is = null; try { connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); if (response == HttpURLConnection.HTTP_ACCEPTED || response == HttpURLConnection.HTTP_OK) { is = connection.getInputStream(); String page = ""; while (page.length() < MAX_PAGE_SIZE) { byte[] buffer = new byte[2048]; int len = is.read(buffer); if (len < 0) { break; } page += new String(buffer, 0, len); } return (page); } else { informFailure("httpinvalidresponse", "" + response); return (null); } } finally { try { if (is != null) { is.close(); } if (connection != null) { connection.disconnect(); } } catch (Throwable e) { Debug.printStackTrace(e); } } } catch (Throwable e) { informFailure("httploadfail", e.toString()); return (null); } } Code Sample 2: @Test public void testExactCopySize() throws IOException { final int size = Byte.SIZE + RANDOMIZER.nextInt(TEST_DATA.length - Long.SIZE); final InputStream in = new ByteArrayInputStream(TEST_DATA); final ByteArrayOutputStream out = new ByteArrayOutputStream(size); final int cpySize = ExtraIOUtils.copy(in, out, size); assertEquals("Mismatched copy size", size, cpySize); final byte[] subArray = ArrayUtils.subarray(TEST_DATA, 0, size), outArray = out.toByteArray(); assertArrayEquals("Mismatched data", subArray, outArray); }
00
Code Sample 1: public static void main(String[] args) throws IOException { String zipPath = "C:\\test.zip"; CZipInputStream zip_in = null; try { byte[] c = new byte[1024]; int slen; zip_in = new CZipInputStream(new FileInputStream(zipPath), "utf-8"); do { ZipEntry file = zip_in.getNextEntry(); if (file == null) break; String fileName = file.getName(); System.out.println(fileName); String ext = fileName.substring(fileName.lastIndexOf(".")); long seed = new Date(System.currentTimeMillis()).getTime(); String newFileName = Long.toString(seed) + ext; FileOutputStream out = new FileOutputStream(newFileName); while ((slen = zip_in.read(c, 0, c.length)) != -1) out.write(c, 0, slen); out.close(); } while (true); } catch (ZipException zipe) { zipe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { zip_in.close(); } } Code Sample 2: public void test(TestHarness harness) { harness.checkPoint("TestOfMD4"); try { Security.addProvider(new JarsyncProvider()); algorithm = MessageDigest.getInstance("BrokenMD4", "JARSYNC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); throw new Error(x); } try { for (int i = 0; i < 64; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "755cd64425f260e356f5303ee82a2d5f"; harness.check(exp.equals(Util.toHexString(md)), "testSixtyFourA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { harness.verbose("NOTE: This test may take a while."); for (int i = 0; i < 536870913; i++) algorithm.update((byte) 'a'); byte[] md = algorithm.digest(); String exp = "b6cea9f528a85963f7529a9e3a2153db"; harness.check(exp.equals(Util.toHexString(md)), "test536870913A"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.provider"); } try { byte[] md = algorithm.digest("a".getBytes()); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testA"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testA"); } try { byte[] md = algorithm.digest("abc".getBytes()); String exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testABC"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testABC"); } try { byte[] md = algorithm.digest("message digest".getBytes()); String exp = "d9130a8164549fe818874806e1c7014b"; harness.check(exp.equals(Util.toHexString(md)), "testMessageDigest"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testMessageDigest"); } try { byte[] md = algorithm.digest("abcdefghijklmnopqrstuvwxyz".getBytes()); String exp = "d79e1c308aa5bbcdeea8ed63df412da9"; harness.check(exp.equals(Util.toHexString(md)), "testAlphabet"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAlphabet"); } try { byte[] md = algorithm.digest("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".getBytes()); String exp = "043f8582f241db351ce627e153e7f0e4"; harness.check(exp.equals(Util.toHexString(md)), "testAsciiSubset"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testAsciiSubset"); } try { byte[] md = algorithm.digest("12345678901234567890123456789012345678901234567890123456789012345678901234567890".getBytes()); String exp = "e33b4ddc9c38f2199c3e7b164fcc0536"; harness.check(exp.equals(Util.toHexString(md)), "testEightyNumerics"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testEightyNumerics"); } try { algorithm.update("a".getBytes(), 0, 1); clone = (MessageDigest) algorithm.clone(); byte[] md = algorithm.digest(); String exp = "bde52cb31de33e46245e05fbdbd6fb24"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #1"); clone.update("bc".getBytes(), 0, 2); md = clone.digest(); exp = "a448017aaf21d8525fc10ae87aa6729d"; harness.check(exp.equals(Util.toHexString(md)), "testCloning #2"); } catch (Exception x) { harness.debug(x); harness.fail("TestOfMD4.testCloning"); } }
00
Code Sample 1: public void registerSchema(String newSchemaName, String objectControlller, long boui, String expression, String schema) throws SQLException { Connection cndef = null; PreparedStatement pstm = null; try { cndef = this.getRepositoryConnection(p_ctx.getApplication(), "default", 2); String friendlyName = "Schema created by object [" + objectControlller + "] with boui [" + boui + "]"; pstm = cndef.prepareStatement("DELETE FROM NGTDIC WHERE TABLENAME=? and objecttype='S'"); pstm.setString(1, newSchemaName); pstm.executeUpdate(); pstm.close(); pstm = cndef.prepareStatement("INSERT INTO NGTDIC (\"SCHEMA\",OBJECTNAME,OBJECTTYPE,TABLENAME, " + "FRIENDLYNAME, EXPRESSION) VALUES (" + "?,?,?,?,?,?)"); pstm.setString(1, schema); pstm.setString(2, newSchemaName); pstm.setString(3, "S"); pstm.setString(4, newSchemaName); pstm.setString(5, friendlyName); pstm.setString(6, expression); pstm.executeUpdate(); pstm.close(); cndef.commit(); } catch (Exception e) { cndef.rollback(); e.printStackTrace(); throw new SQLException(e.getMessage()); } finally { if (pstm != null) { try { pstm.close(); } catch (Exception e) { } } } } Code Sample 2: String getOutputPage(String action, String XML, String xslFileName, InputStream pageS, HttpServletRequest request) throws NoSuchAlgorithmException, UnsupportedEncodingException, TransformerException { String sPage = null; Transformer transformer = null; String dig = null; CharArrayWriter page = new CharArrayWriter(); if (this.nCachedPages > 0) { java.security.MessageDigest mess = java.security.MessageDigest.getInstance("SHA1"); mess.update(XML.getBytes()); mess.update(Long.toString(new File(basePath + xslFileName).lastModified()).getBytes()); dig = new String(mess.digest()); synchronized (pages) { if (pages.containsKey(dig)) { sPage = pages.get(dig); } } } if (sPage == null && xslFileName.length() > 4) { try { long modifyTime = new File(basePath + xslFileName).lastModified(); String path = basePath.replaceAll("\\\\", "/") + xslFileName; path = "file:///" + path; boolean add2cache = false; if (this.nCachedTransformers > 0) { String cacheKey = action + xslFileName + modifyTime; if (this.transformers.containsKey(cacheKey)) { transformer = this.transformers.get(cacheKey); synchronized (transformer) { transformer.transform(new StreamSource(new ByteArrayInputStream(XML.getBytes("UTF-8"))), new StreamResult(page)); } } else { add2cache = true; } } if (transformer == null) { transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(path)); transformer.transform(new StreamSource(new ByteArrayInputStream(XML.getBytes("UTF-8"))), new StreamResult(page)); } sPage = page.toString(); sPage = sPage.replaceAll("&lt;", "<"); sPage = sPage.replaceAll("&gt;", ">"); sPage = replaceLinks(sPage, request); if (this.nCachedPages > 0) { synchronized (pages) { pages.put(dig, sPage); if (pages.size() > nCachedPages) { Iterator<String> i = pages.values().iterator(); i.next(); i.remove(); } } } if (add2cache) { synchronized (this.transformers) { this.transformers.put(action + xslFileName + modifyTime, transformer); if (this.transformers.size() > this.nCachedTransformers) { Iterator<Transformer> it = this.transformers.values().iterator(); it.next(); it.remove(); } } } } catch (TransformerException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, "---------------------------------------------"); Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); Logger.getLogger(getClass().getName()).log(Level.SEVERE, ("XSL file: " + xslFileName)); Logger.getLogger(getClass().getName()).log(Level.SEVERE, XML); Logger.getLogger(getClass().getName()).log(Level.SEVERE, "---------------------------------------------"); throw ex; } } return sPage; }
00
Code Sample 1: public static boolean doExecuteBatchSQL(List<String> sql) { session = currentSession(); Connection conn = session.connection(); PreparedStatement ps = null; try { conn.setAutoCommit(false); Iterator iter = sql.iterator(); while (iter.hasNext()) { String sqlstr = (String) iter.next(); log("[SmsManager] doing sql:" + sqlstr); ps = conn.prepareStatement(sqlstr); ps.executeUpdate(); } conn.commit(); conn.setAutoCommit(true); return true; } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } return false; } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } closeHibernateSession(); } } Code Sample 2: public static boolean encodeFileToFile(final String infile, final String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); final byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (final java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (final Exception exc) { } try { out.close(); } catch (final Exception exc) { } } return success; }
00
Code Sample 1: public String getRec(String attribute, String url) { String arr[] = new String[3]; String[] subarr = new String[6]; String mdPrefix = ""; String mdPrefixValue = ""; String iden = ""; String idenValue = ""; String s = ""; String arguments = attribute.substring(attribute.indexOf("?") + 1); System.out.println("attributes" + arguments); java.util.StringTokenizer st = new java.util.StringTokenizer(arguments, "&"); int i = 0; int j = 0; int count = 0; int argCount = 0; java.util.Vector v1 = new java.util.Vector(1, 1); java.util.Vector v901 = new java.util.Vector(1, 1); java.util.Vector v902 = new java.util.Vector(1, 1); java.util.Vector v903 = new java.util.Vector(1, 1); java.util.Vector v904 = new java.util.Vector(1, 1); java.util.Vector v905 = new java.util.Vector(1, 1); java.util.Vector v906 = new java.util.Vector(1, 1); java.util.Vector v907 = new java.util.Vector(1, 1); java.util.Vector v908 = new java.util.Vector(1, 1); java.util.Vector v3 = new java.util.Vector(1, 1); java.util.Vector vData = new java.util.Vector(1, 1); java.util.Vector vSet = new java.util.Vector(1, 1); java.util.Vector v856 = new java.util.Vector(1, 1); Resdate dt = new Resdate(); try { while (st.hasMoreElements()) { arr[i] = st.nextElement().toString(); java.util.StringTokenizer subSt = new java.util.StringTokenizer(arr[i], "="); while (subSt.hasMoreElements()) { subarr[j] = subSt.nextElement().toString(); System.out.println(" arga are... " + subarr[j]); j++; } i++; count++; } } catch (Exception e) { e.printStackTrace(); } Namespace oains = Namespace.getNamespace("http://www.openarchives.org/OAI/2.0/"); Element root = new Element("OAI-PMH", oains); Namespace xsi = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); Attribute schemaLocation = new Attribute("schemaLocation", "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd", xsi); root.setAttribute(schemaLocation); root.addNamespaceDeclaration(xsi); Document doc = new Document(root); Element responseDate = new Element("responseDate", oains); root.addContent(responseDate); responseDate.setText(dt.getDate()); Element request = new Element("request", oains); request.setAttribute("verb", "GetRecord"); int idenCount = 0, mdfCount = 0; for (int k = 2; k < j; k += 2) { System.out.println(" arg key " + subarr[k]); if (subarr[k].equals("metadataPrefix")) { mdPrefix = "metadataPrefix"; mdfCount++; mdPrefixValue = subarr[k + 1]; request.setAttribute(mdPrefix, mdPrefixValue); System.out.println(subarr[k] + "="); System.out.println(mdPrefixValue); argCount++; } else if (subarr[k].equals("identifier")) { iden = "identifier"; idenCount++; idenValue = subarr[k + 1]; request.setAttribute(iden, idenValue); System.out.println(subarr[k] + "="); System.out.println(idenValue); argCount++; } } request.setText(url); root.addContent(request); System.out.println("count" + argCount); if (mdfCount == 1 && idenCount == 1 && (mdPrefixValue.equals("marc21") || mdPrefixValue.equals("oai_dc") || mdPrefixValue.equals("mods"))) { try { v1 = ((ejb.bprocess.OAIPMH.ListGetRecordsHome) ejb.bprocess.util.HomeFactory.getInstance().getRemoteHome("ListGetRecords")).create().getRecord(idenValue, mdPrefixValue); } catch (Exception ex) { ex.printStackTrace(); } if (v1.size() == 0) { System.out.println("vector size is empty"); Errors e1 = new Errors(); Element errorXML = e1.describeError(3, attribute, url, "GetRecord"); root.addContent(errorXML); } else { Element GetRecord = new Element("GetRecord", oains); root.addContent(GetRecord); Element Record = new Element("record", oains); Element metadata = new Element("metadata", oains); Element head = new Element("header", oains); System.out.println("size i s " + v1.size()); for (int v = 0; v < v1.size(); v = v + 13) { vSet = (java.util.Vector) v1.elementAt(v + 1); Element ident = new Element("identifier", oains); ident.setText(idenValue); head.addContent(ident); Element dates = new Element("datestamp", oains); dates.setText(v1.elementAt(v).toString().substring(0, 10)); head.addContent(dates); for (int t = 0; t < vSet.size(); t++) { Element setSpec = new Element("setSpec", oains); System.out.println("set elem" + vSet.elementAt(t).toString()); setSpec.setText(vSet.elementAt(t).toString()); head.addContent(setSpec); } Element marcroot = new Element("record", "marc", "http://www.loc.gov/MARC21/slim"); Namespace xsimarc = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); marcroot.addNamespaceDeclaration(xsimarc); Attribute schemaLocationmarc = new Attribute("schemaLocation", "http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd", xsimarc); marcroot.setAttribute(schemaLocationmarc); marcroot.setAttribute("type", "Bibliographic"); v3 = (java.util.Vector) v1.elementAt(v + 10); java.util.Vector vL = (java.util.Vector) v3.elementAt(0); org.jdom.Element lead = new org.jdom.Element("leader", "marc", "http://www.loc.gov/MARC21/slim"); lead.setText(vL.elementAt(0).toString()); marcroot.addContent(lead); java.util.Vector vC = (java.util.Vector) v3.elementAt(1); for (int u = 0; u < vC.size(); u = u + 2) { org.jdom.Element ct = new org.jdom.Element("controlfield", "marc", "http://www.loc.gov/MARC21/slim"); ct.setAttribute("tag", vC.elementAt(u).toString()); ct.setText(vC.elementAt(u + 1).toString()); marcroot.addContent(ct); } v901 = (java.util.Vector) v1.elementAt(v + 2); for (int k = 0; k < v901.size(); k++) { org.jdom.Element datafield = new org.jdom.Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield.setAttribute("tag", "901"); datafield.setAttribute("ind1", "0"); datafield.setAttribute("ind2", "0"); java.util.Vector vecSub = new java.util.Vector(1, 1); vecSub = (java.util.Vector) v901.elementAt(k); System.out.println("in getrec sub "); System.out.println("sub 901 size" + vecSub.size()); for (int k1 = 0; k1 < vecSub.size(); k1 = k1 + 2) { org.jdom.Element subfield = new org.jdom.Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vecSub.elementAt(k1).toString()); subfield.setText(vecSub.elementAt(k1 + 1).toString()); datafield.addContent(subfield); } marcroot.addContent(datafield); } v902 = (java.util.Vector) v1.elementAt(v + 3); for (int l = 0; l < v902.size(); l++) { Element datafield1 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield1.setAttribute("tag", "902"); datafield1.setAttribute("ind1", "0"); datafield1.setAttribute("ind2", "0"); java.util.Vector vecSub1 = new java.util.Vector(1, 1); vecSub1 = (java.util.Vector) v902.elementAt(l); for (int b = 0; b < vecSub1.size(); b = b + 2) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vecSub1.elementAt(b).toString()); subfield.setText(vecSub1.elementAt(b + 1).toString()); datafield1.addContent(subfield); } marcroot.addContent(datafield1); } v903 = (java.util.Vector) v1.elementAt(v + 4); Element datafield1 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield1.setAttribute("tag", "903"); datafield1.setAttribute("ind1", "0"); datafield1.setAttribute("ind2", "0"); for (int l = 0; l < v903.size(); l++) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", "a"); subfield.setText(v903.elementAt(l).toString()); datafield1.addContent(subfield); } marcroot.addContent(datafield1); v904 = (java.util.Vector) v1.elementAt(v + 5); Element datafield21 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield21.setAttribute("tag", "904"); datafield21.setAttribute("ind1", "0"); datafield21.setAttribute("ind2", "0"); for (int l = 0; l < v904.size(); l++) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", "a"); subfield.setText(v904.elementAt(l).toString()); datafield21.addContent(subfield); } marcroot.addContent(datafield21); v905 = (java.util.Vector) v1.elementAt(v + 6); Element datafield31 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield31.setAttribute("tag", "905"); datafield31.setAttribute("ind1", "0"); datafield31.setAttribute("ind2", "0"); for (int l = 0; l < v905.size(); l++) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", "a"); subfield.setText(v905.elementAt(l).toString()); datafield31.addContent(subfield); } marcroot.addContent(datafield31); v906 = (java.util.Vector) v1.elementAt(v + 7); Element datafield4 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield4.setAttribute("tag", "906"); datafield4.setAttribute("ind1", "0"); datafield4.setAttribute("ind2", "0"); for (int l = 0; l < v906.size(); l++) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", "a"); subfield.setText(v906.elementAt(l).toString()); datafield4.addContent(subfield); } marcroot.addContent(datafield4); v907 = (java.util.Vector) v1.elementAt(v + 8); for (int l = 0; l < v907.size(); l++) { Element datafield5 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield5.setAttribute("tag", "907"); datafield5.setAttribute("ind1", "0"); datafield5.setAttribute("ind2", "0"); java.util.Vector vecSub1 = new java.util.Vector(1, 1); vecSub1 = (java.util.Vector) v907.elementAt(l); for (int b = 0; b < vecSub1.size(); b = b + 2) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vecSub1.elementAt(b).toString()); subfield.setText(vecSub1.elementAt(b + 1).toString()); datafield5.addContent(subfield); } marcroot.addContent(datafield5); } v908 = (java.util.Vector) v1.elementAt(v + 9); for (int l = 0; l < v908.size(); l++) { Element datafield6 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield6.setAttribute("tag", "908"); datafield6.setAttribute("ind1", "0"); datafield6.setAttribute("ind2", "0"); java.util.Vector vecSub1 = new java.util.Vector(1, 1); vecSub1 = (java.util.Vector) v908.elementAt(l); for (int b = 0; b < vecSub1.size(); b = b + 2) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vecSub1.elementAt(b).toString()); subfield.setText(vecSub1.elementAt(b + 1).toString()); datafield6.addContent(subfield); } marcroot.addContent(datafield6); } vData = (java.util.Vector) v1.elementAt(v + 11); for (int m = 0; m < vData.size(); m = m + 2) { Element datafield2 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield2.setAttribute("tag", vData.elementAt(m).toString()); datafield2.setAttribute("ind1", "0"); datafield2.setAttribute("ind2", "0"); java.util.Vector vSub = new java.util.Vector(1, 1); vSub = (java.util.Vector) vData.elementAt(m + 1); for (int n = 0; n < vSub.size(); n = n + 2) { Element subfield = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield.setAttribute("code", vSub.elementAt(n).toString()); subfield.setText(vSub.elementAt(n + 1).toString()); datafield2.addContent(subfield); } marcroot.addContent(datafield2); } v856 = (java.util.Vector) v1.elementAt(v + 12); for (int l = 0; l < v856.size(); l = l + 2) { Element datafield3 = new Element("datafield", "marc", "http://www.loc.gov/MARC21/slim"); datafield3.setAttribute("tag", "856"); datafield3.setAttribute("ind1", "0"); datafield3.setAttribute("ind2", "0"); Element subfield1 = new Element("subfield", "marc", "http://www.loc.gov/MARC21/slim"); subfield1.setAttribute("code", v856.elementAt(l).toString()); subfield1.setText(v856.elementAt(l + 1).toString()); datafield3.addContent(subfield1); marcroot.addContent(datafield3); } if (mdPrefixValue.equals("oai_dc")) { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(ejb.bprocess.util.NewGenLibRoot.getRoot() + java.io.File.separator + "StyleSheets" + java.io.File.separator + "MARC21slim2OAIDC.xsl")); Document docmarc = new Document(marcroot); JDOMSource in = new JDOMSource(docmarc); JDOMResult out = new JDOMResult(); transformer.transform(in, out); Document doc2 = out.getDocument(); org.jdom.output.XMLOutputter out1 = new org.jdom.output.XMLOutputter(); out1.setTextTrim(true); out1.setIndent(" "); out1.setNewlines(true); String s1 = out1.outputString(doc2); System.out.println("dublin core is" + s1); Element dcroot1 = doc2.getRootElement(); Namespace xsi1 = Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); Namespace oainsdc = Namespace.getNamespace("http://www.openarchives.org/OAI/2.0/oai_dc/"); Element dcroot = new Element("dc", "oai_dc", "http://www.openarchives.org/OAI/2.0/oai_dc/"); Namespace dcns = Namespace.getNamespace("dc", "http://purl.org/dc/elements/1.1/"); dcroot.addNamespaceDeclaration(dcns); dcroot.addNamespaceDeclaration(xsi1); Attribute schemaLocationdc = new Attribute("schemaLocation", "http://www.openarchives.org/OAI/2.0/oai_dc/ http://www.openarchives.org/OAI/2.0/oai_dc.xsd", xsi1); dcroot.setAttribute(schemaLocationdc); java.util.List dcList = doc2.getRootElement().getChildren(); for (int g = 0; g < dcList.size(); g++) { Element dcElem1 = (org.jdom.Element) dcList.get(g); Element dcElem = new Element(dcElem1.getName(), "dc", "http://purl.org/dc/elements/1.1/"); dcElem.setText(dcElem1.getText()); dcroot.addContent(dcElem); } metadata.addContent(dcroot); } catch (TransformerException e) { e.printStackTrace(); } } else if (mdPrefixValue.equals("mods")) { try { java.util.Properties systemSettings = System.getProperties(); java.util.prefs.Preferences prefs = java.util.prefs.Preferences.systemRoot(); if (prefs.getBoolean("useproxy", false)) { systemSettings.put("proxySet", "true"); systemSettings.put("proxyHost", prefs.get("proxyservername", "")); systemSettings.put("proxyPort", prefs.get("proxyport", "")); systemSettings.put("http.proxyHost", prefs.get("proxyservername", "")); systemSettings.put("http.proxyPort", prefs.get("proxyport", "")); } String urltext = ""; Transformer transformer = null; urltext = "http://www.loc.gov/standards/mods/v3/MARC21slim2MODS3.xsl"; java.net.URL url1 = new java.net.URL(urltext); java.net.URLConnection urlconn = url1.openConnection(); urlconn.setDoInput(true); transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(urlconn.getInputStream())); Document docmarc = new Document(marcroot); JDOMSource in = new JDOMSource(docmarc); JDOMResult out = new JDOMResult(); transformer.transform(in, out); Document doc2 = out.getDocument(); org.jdom.output.XMLOutputter out1 = new org.jdom.output.XMLOutputter(); out1.setTextTrim(true); out1.setIndent(" "); out1.setNewlines(true); String s1 = out1.outputString(doc2); Namespace xsi1 = Namespace.getNamespace("xlink", "http://www.w3.org/1999/xlink"); Namespace oainsdc = Namespace.getNamespace("http://www.openarchives.org/OAI/2.0/oai_dc/"); Element mroot = new Element("mods", "http://www.loc.gov/mods/v3"); Namespace dcns = Namespace.getNamespace("http://www.loc.gov/mods/v3"); mroot.addNamespaceDeclaration(xsi1); Attribute schemaLocationdc = new Attribute("schemaLocation", "http://www.loc.gov/mods/v3 http://www.loc.gov/standards/mods/v3/mods-3-0.xsd", xsi1); mroot.setAttribute(schemaLocationdc); java.util.List dcList = doc2.getRootElement().getChildren(); for (int g = 0; g < dcList.size(); g++) { Element mElem1 = (org.jdom.Element) dcList.get(g); Element mElem = new Element(mElem1.getName(), "http://www.loc.gov/mods/v3"); if (mElem1.hasChildren()) { java.util.List mList1 = mElem1.getChildren(); for (int f = 0; f < mList1.size(); f++) { Element mElem2 = (org.jdom.Element) mList1.get(f); Element mElem3 = new Element(mElem2.getName(), "http://www.loc.gov/mods/v3"); if (mElem2.hasChildren()) { java.util.List mList2 = mElem2.getChildren(); for (int h = 0; h < mList2.size(); h++) { Element mElem4 = (org.jdom.Element) mList1.get(h); Element mElem5 = new Element(mElem4.getName(), "http://www.loc.gov/mods/v3"); mElem5.setText(mElem4.getText()); mElem3.addContent(mElem5); } } if (mElem2.hasChildren() == false) { mElem3.setText(mElem2.getText()); } mElem.addContent(mElem3); } } if (mElem1.hasChildren() == false) { mElem.setText(mElem1.getText()); } mroot.addContent(mElem); } metadata.addContent(mroot); } catch (Exception e) { e.printStackTrace(); } } if (mdPrefixValue.equals("marc21")) { metadata.addContent(marcroot); } else if (mdPrefixValue.equals("oai_dc")) { } } Record.addContent(head); Record.addContent(metadata); GetRecord.addContent(Record); } } else if (argCount <= 2) { if (idenCount < 1 && mdfCount < 1) { Errors e1 = new Errors(); Element errorXML = e1.describeError(2, "missing arguments: identifier,metadataprefix", url, "GetRecord"); root.addContent(errorXML); } else if (idenCount < 1) { Errors e1 = new Errors(); Element errorXML = e1.describeError(2, "missing argument: identifier", url, "GetRecord"); root.addContent(errorXML); } else if (mdfCount < 1) { Errors e1 = new Errors(); Element errorXML = e1.describeError(2, "missing argument: metadataprefix", url, "GetRecord"); root.addContent(errorXML); } else if (argCount > 2) { Errors e1 = new Errors(); Element errorXML = e1.describeError(2, "more number of arguments", url, "GetRecord"); root.addContent(errorXML); } else { System.out.println("no format"); Errors e1 = new Errors(); Element errorXML = e1.describeError(6, "", url, "GetRecord"); root.addContent(errorXML); } } XMLOutputter out = new XMLOutputter(); out.setIndent(" "); out.setNewlines(true); s = out.outputString(doc); return s; } Code Sample 2: public AudioFileFormat getAudioFileFormat(URL url) throws UnsupportedAudioFileException, IOException { if (TDebug.TraceAudioFileReader) { TDebug.out("TAudioFileReader.getAudioFileFormat(URL): begin"); } long lFileLengthInBytes = AudioSystem.NOT_SPECIFIED; InputStream inputStream = url.openStream(); AudioFileFormat audioFileFormat = null; try { audioFileFormat = getAudioFileFormat(inputStream, lFileLengthInBytes); } finally { inputStream.close(); } if (TDebug.TraceAudioFileReader) { TDebug.out("TAudioFileReader.getAudioFileFormat(URL): end"); } return audioFileFormat; }
00
Code Sample 1: public static String loadPage(URL url) throws IOException { Reader in = null; URLConnection uc; HttpURLConnection huc = null; try { uc = url.openConnection(); if (uc instanceof HttpURLConnection) { huc = (HttpURLConnection) uc; huc.setInstanceFollowRedirects(false); huc.connect(); in = new InputStreamReader(huc.getInputStream()); StringBuilder sb = new StringBuilder(); int c; while ((c = in.read()) != -1) sb.append((char) c); return sb.toString(); } else return null; } finally { try { if (in != null) in.close(); if (huc != null) huc.disconnect(); } catch (IOException ex) { ex.printStackTrace(); } } } Code Sample 2: private void getXMLData() { String result = null; URL url = null; URLConnection conn = null; BufferedReader rd = null; StringBuffer sb = new StringBuffer(); String line; try { url = new URL(this.url); conn = url.openConnection(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = rd.readLine()) != null) { sb.append(line + "\n"); } rd.close(); result = sb.toString(); } catch (MalformedURLException e) { log.error("URL was malformed: {}", url, e); } catch (IOException e) { log.error("IOException thrown: {}", url, e); } this.xmlString = result; }
00
Code Sample 1: private String searchMetabolite(String name) { { BufferedReader in = null; try { String urlName = name; URL url = new URL(urlName); in = new BufferedReader(new InputStreamReader(url.openStream())); String inputLine; Boolean isMetabolite = false; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("Metabolite</h1>")) { isMetabolite = true; } if (inputLine.contains("<td><a href=\"/Metabolites/") && isMetabolite) { String metName = inputLine.substring(inputLine.indexOf("/Metabolites/") + 13, inputLine.indexOf("aspx\" target") + 4); return "http://gmd.mpimp-golm.mpg.de/Metabolites/" + metName; } } in.close(); return name; } catch (IOException ex) { Logger.getLogger(GetGolmIDsTask.class.getName()).log(Level.SEVERE, null, ex); return null; } } } Code Sample 2: public void fillTableValues() { java.util.ArrayList cpool = newgen.presentation.NewGenMain.getAppletInstance().getCataloguingPool(); String xmlreq = AdministrationXMLGenerator.getInstance().getPoolChronologicalSubDivision("4", cpool); System.out.println(xmlreq); try { java.net.URL url = new java.net.URL(ResourceBundle.getBundle("Administration").getString("ServerURL") + ResourceBundle.getBundle("Administration").getString("ServletSubPath") + "SubDivisionServlet"); 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(); java.util.List onelist = rootelement.getChildren(); for (int i = 0; i < onelist.size(); i++) { Element rec = (Element) onelist.get(i); Object[] r = new Object[7]; String[] chronolib = new String[2]; chronolib[0] = rec.getChild("ChronologicalSubDivisionId").getText(); chronolib[1] = rec.getChild("LibraryId").getText(); this.chronoid_libid.add(chronolib); r[0] = rec.getChild("ChronologicalSubDivision").getText(); this.dtmSearch.addRow(r); } } catch (Exception e) { System.out.println(e); } }
11
Code Sample 1: @Override @Transactional public FileData store(FileData data, InputStream stream) { try { FileData file = save(data); file.setPath(file.getGroup() + File.separator + file.getId()); file = save(file); File folder = new File(PATH, file.getGroup()); if (!folder.exists()) folder.mkdirs(); File filename = new File(folder, file.getId() + ""); IOUtils.copyLarge(stream, new FileOutputStream(filename)); return file; } catch (IOException e) { throw new ServiceException("storage", e); } } Code Sample 2: private static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
00
Code Sample 1: public static String BaiKe(String unknown) { String encodeurl = ""; long sTime = System.currentTimeMillis(); long eTime; try { String regEx = "\\#(.+)\\#"; String searchText = ""; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(unknown); if (m.find()) { searchText = m.group(1); } System.out.println("searchText : " + searchText); encodeurl = URLEncoder.encode(searchText, "UTF-8"); String url = "http://www.hudong.com/wiki/" + encodeurl; HttpURLConnection conn = (HttpURLConnection) (new URL(url)).openConnection(); conn.setConnectTimeout(10000); Parser parser = new Parser(conn); parser.setEncoding(parser.getEncoding()); NodeFilter filtera = new TagNameFilter("DIV"); NodeList nodes = parser.extractAllNodesThatMatch(filtera); String textInPage = ""; if (nodes != null) { for (int i = 0; i < nodes.size(); i++) { Node textnode = (Node) nodes.elementAt(i); if ("div class=\"summary\"".equals(textnode.getText())) { String temp = textnode.toPlainTextString(); textInPage += temp + "\n"; } } } String s = Replace(textInPage, searchText); eTime = System.currentTimeMillis(); String time = "搜索[" + searchText + "]用时:" + (eTime - sTime) / 1000.0 + "s"; System.out.println(s); return time + "\r\n" + s; } catch (Exception e) { e.printStackTrace(); return "大姨妈来了"; } } Code Sample 2: public static boolean copyFile(File dest, File source) { FileInputStream fis = null; FileOutputStream fos = null; boolean rv = false; byte[] buf = new byte[1000000]; int bytesRead = 0; if (!dest.getParentFile().exists()) dest.getParentFile().mkdirs(); try { fis = new FileInputStream(source); fos = new FileOutputStream(dest); while ((bytesRead = fis.read(buf)) > 0) fos.write(buf, 0, bytesRead); fis.close(); fis = null; fos.close(); fos = null; rv = true; } catch (Throwable t) { throw new ApplicationException("copy error (" + source.getAbsolutePath() + " => " + dest.getAbsolutePath(), t); } finally { if (fis != null) { try { fis.close(); } catch (Exception e) { } fis = null; } if (fos != null) { try { fos.close(); } catch (Exception e) { } fos = null; } } return rv; }
11
Code Sample 1: protected void setUp() throws Exception { this.testOutputDirectory = new File(getClass().getResource("/").getPath()); this.pluginFile = new File(this.testOutputDirectory, "/plugin.zip"); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pluginFile)); zos.putNextEntry(new ZipEntry("WEB-INF/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/")); zos.putNextEntry(new ZipEntry("WEB-INF/classes/system.properties")); System.getProperties().store(zos, null); zos.closeEntry(); zos.putNextEntry(new ZipEntry("WEB-INF/lib/")); zos.putNextEntry(new ZipEntry("WEB-INF/lib/plugin.jar")); File jarFile = new File(this.testOutputDirectory.getPath() + "/plugin.jar"); JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); jos.putNextEntry(new ZipEntry("vqwiki/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/")); jos.putNextEntry(new ZipEntry("vqwiki/plugins/system.properties")); System.getProperties().store(jos, null); jos.closeEntry(); jos.close(); IOUtils.copy(new FileInputStream(jarFile), zos); zos.closeEntry(); zos.close(); jarFile.delete(); pcl = new PluginClassLoader(new File(testOutputDirectory, "/work")); pcl.addPlugin(pluginFile); } Code Sample 2: public static int copyFile(File src, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(src).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) in.close(); if (out != null) out.close(); } return 1; }
11
Code Sample 1: public ActualTask(TEditor editor, TIGDataBase dataBase, String directoryPath) { File myDirectory = new File(directoryPath); String[] list = myDirectory.list(); int i; for (i = 0; ((i < list.length) && !stop); i++) { current = i; if ((list[i].compareTo("Images") != 0) && ((list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".jpg") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".bmp") == 0) || (list[i].substring(list[i].lastIndexOf('.'), list[i].length()).toLowerCase().compareTo(".png") == 0))) { String name = list[i]; String pathSrc = directoryPath.concat(list[i]); name = name.replace(' ', '_').replace(',', '-').replace('á', 'a').replace('é', 'e').replace('í', 'i').replace('ó', 'o').replace('ú', 'u').replace('Á', 'A').replace('É', 'E').replace('Í', 'I').replace('Ó', 'O').replace('Ú', 'U'); String pathDst = directoryPath.concat(name); Vector aux = new Vector(); aux = dataBase.imageSearch(name.substring(0, name.lastIndexOf('.'))); if (aux.size() != 0) pathDst = pathDst.substring(0, pathDst.lastIndexOf('.')) + '_' + aux.size() + ".png"; File src = new File(pathSrc); File absPath = new File(""); String nameSrc = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase() + src.separator + pathDst.substring(pathDst.lastIndexOf(src.separator) + 1, pathDst.length()); String newDirectory = '.' + src.separator + "Images" + src.separator + name.substring(0, 1).toUpperCase(); String imagePathThumb = (nameSrc.substring(0, nameSrc.lastIndexOf("."))).concat("_th.jpg"); ImageIcon image = null; if (src != null) { if (TFileUtils.isJAIRequired(src)) { RenderedOp src_aux = JAI.create("fileload", src.getAbsolutePath()); BufferedImage bufferedImage = src_aux.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(src.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { System.out.print("Error al insertar imagen: "); System.out.println(pathDst); } else { int option = 0; imageFile = new File(directoryPath + "Images"); if (!imageFile.exists()) { TIGNewImageDataDialog dialog = new TIGNewImageDataDialog(editor, dataBase, image, nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length()), list[i].substring(0, list[i].lastIndexOf('.')), myTask); option = dialog.getOption(); if (option != 0) { File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } } if (imageFile.exists()) { dataBase.insertImageDB(list[i].substring(0, list[i].lastIndexOf('.')), nameSrc.substring(nameSrc.lastIndexOf(File.separator) + 1, nameSrc.length())); File newDirectoryFolder = new File(newDirectory); newDirectoryFolder.mkdirs(); try { FileChannel srcChannel = new FileInputStream(pathSrc).getChannel(); FileChannel dstChannel = new FileOutputStream(nameSrc).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } } try { int thumbWidth = PREVIEW_WIDTH; int thumbHeight = PREVIEW_HEIGHT; double thumbRatio = (double) thumbWidth / (double) thumbHeight; int imageWidth = image.getIconWidth(); int imageHeight = image.getIconHeight(); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { thumbHeight = (int) (thumbWidth / imageRatio); } else { thumbWidth = (int) (thumbHeight * imageRatio); } BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graphics2D = thumbImage.createGraphics(); graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); graphics2D.drawImage(image.getImage(), 0, 0, thumbWidth, thumbHeight, null); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(imagePathThumb)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); int quality = 100; quality = Math.max(0, Math.min(quality, 100)); param.setQuality((float) quality / 100.0f, false); encoder.setJPEGEncodeParam(param); encoder.encode(thumbImage); out.close(); } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } } } } if (imageFile.exists() && !stop) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(imageFile); Element dataBaseElement = doc.getDocumentElement(); if (dataBaseElement.getTagName().equals("dataBase")) { NodeList imageNodeList = dataBaseElement.getElementsByTagName("image"); for (int j = 0; j < imageNodeList.getLength(); j++) { current++; Node imageNode = imageNodeList.item(j); NodeList lista = imageNode.getChildNodes(); Node nameNode = imageNode.getChildNodes().item(0); String imageName = nameNode.getChildNodes().item(0).getNodeValue(); int imageKey = dataBase.imageKeySearchName(imageName.substring(0, imageName.lastIndexOf('.'))); if (imageKey != -1) { for (int k = 1; k < imageNode.getChildNodes().getLength(); k++) { Node keyWordNode = imageNode.getChildNodes().item(k); String keyWord = keyWordNode.getChildNodes().item(0).getNodeValue(); int conceptKey = dataBase.conceptKeySearch(keyWord); if (conceptKey == -1) { dataBase.insertConceptDB(keyWord); conceptKey = dataBase.conceptKeySearch(keyWord); } dataBase.insertAsociatedDB(conceptKey, imageKey); } } } } } catch (Exception ex) { System.out.println(ex.getMessage()); System.out.println(ex.toString()); } } current = lengthOfTask; } Code Sample 2: public String storeUploadedZip(byte[] zip, String name) { List filesToStore = new ArrayList(); int i = 0; ZipInputStream zipIs = new ZipInputStream(new ByteArrayInputStream(zip)); ZipEntry zipEntry = zipIs.getNextEntry(); while (zipEntry != null) { if (zipEntry.isDirectory() == false) { i++; ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(zipIs, baos); baos.close(); } zipIs.closeEntry(); zipEntry = zipIs.getNextEntry(); } }
11
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("image/png"); OutputStream outStream; outStream = resp.getOutputStream(); InputStream is; String name = req.getParameter("name"); if (name == null) { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } else { ImageRecord imageRecord = imageBean.getFile(name); if (imageRecord != null) { is = new BufferedInputStream(new FileInputStream(imageRecord.getThumbnailFile())); } else { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } } IOUtils.copy(is, outStream); outStream.close(); outStream.flush(); } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static final void main(String[] args) throws FileNotFoundException, IOException { ArrayList<String[]> result = new ArrayList<String[]>(); IStream is = new StreamImpl(); IOUtils.copy(new FileInputStream("H:\\7-项目预算表.xlsx"), is.getOutputStream()); int count = loadExcel(result, is, 0, 0, -1, 16, 1); System.out.println(count); for (String[] rs : result) { for (String r : rs) { System.out.print(r + "\t"); } System.out.println(); } } Code Sample 2: private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); }
00
Code Sample 1: public List tree(String cat, int branch) { Pattern p = Pattern.compile("<a href=\"javascript:checkBranch\\(([0-9]+), 'true'\\)\">([^<]*)</a>"); Matcher m; List res = new ArrayList(); URL url; HttpURLConnection conn; System.out.println(); try { url = new URL("http://cri-srv-ade.insa-toulouse.fr:8080/ade/standard/gui/tree.jsp?category=trainee&expand=false&forceLoad=false&reload=false&scroll=0"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Cookie", sessionId); BufferedReader i = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = i.readLine()) != null) { m = p.matcher(line); if (m.find()) { trainee.add(new Node(Integer.parseInt(m.group(1)), m.group(2))); System.out.println(m.group(1) + " - " + m.group(2)); } } } catch (Exception e2) { e2.printStackTrace(); } return res; } Code Sample 2: public Object resolveEntity(String publicID, String systemID, String baseURI, String namespace) throws XMLStreamException { URL url = configuration.get(publicID); try { if (url != null) return url.openStream(); } catch (IOException ex) { throw new XMLStreamException(String.format("Unable to open stream for resource %s: %s", url, InternalUtils.toMessage(ex)), ex); } return null; }
00
Code Sample 1: public void createResource(String resourceUri, boolean publish, User user) throws IOException { PermissionAPI perAPI = APILocator.getPermissionAPI(); Logger.debug(this.getClass(), "createResource"); resourceUri = stripMapping(resourceUri); String hostName = getHostname(resourceUri); String path = getPath(resourceUri); String folderName = getFolderName(path); String fileName = getFileName(path); fileName = deleteSpecialCharacter(fileName); if (fileName.startsWith(".")) { return; } Host host = HostFactory.getHostByHostName(hostName); Folder folder = FolderFactory.getFolderByPath(folderName, host); boolean hasPermission = perAPI.doesUserHavePermission(folder, PERMISSION_WRITE, user, false); if (hasPermission) { if (!checkFolderFilter(folder, fileName)) { throw new IOException("The file doesn't comply the folder's filter"); } if (host.getInode() != 0 && folder.getInode() != 0) { File file = new File(); file.setTitle(fileName); file.setFileName(fileName); file.setShowOnMenu(false); file.setLive(publish); file.setWorking(true); file.setDeleted(false); file.setLocked(false); file.setModDate(new Date()); String mimeType = FileFactory.getMimeType(fileName); file.setMimeType(mimeType); String author = user.getFullName(); file.setAuthor(author); file.setModUser(author); file.setSortOrder(0); file.setShowOnMenu(false); try { Identifier identifier = null; if (!isResource(resourceUri)) { WebAssetFactory.createAsset(file, user.getUserId(), folder, publish); identifier = IdentifierCache.getIdentifierFromIdentifierCache(file); } else { File actualFile = FileFactory.getFileByURI(path, host, false); identifier = IdentifierCache.getIdentifierFromIdentifierCache(actualFile); WebAssetFactory.createAsset(file, user.getUserId(), folder, identifier, false, false); WebAssetFactory.publishAsset(file); String assetsPath = FileFactory.getRealAssetsRootPath(); new java.io.File(assetsPath).mkdir(); java.io.File workingIOFile = FileFactory.getAssetIOFile(file); DotResourceCache vc = CacheLocator.getVeloctyResourceCache(); vc.remove(ResourceManager.RESOURCE_TEMPLATE + workingIOFile.getPath()); if (file != null && file.getInode() > 0) { byte[] currentData = new byte[0]; FileInputStream is = new FileInputStream(workingIOFile); int size = is.available(); currentData = new byte[size]; is.read(currentData); java.io.File newVersionFile = FileFactory.getAssetIOFile(file); vc.remove(ResourceManager.RESOURCE_TEMPLATE + newVersionFile.getPath()); FileChannel channelTo = new FileOutputStream(newVersionFile).getChannel(); ByteBuffer currentDataBuffer = ByteBuffer.allocate(currentData.length); currentDataBuffer.put(currentData); currentDataBuffer.position(0); channelTo.write(currentDataBuffer); channelTo.force(false); channelTo.close(); } java.util.List<Tree> parentTrees = TreeFactory.getTreesByChild(file); for (Tree tree : parentTrees) { Tree newTree = TreeFactory.getTree(tree.getParent(), file.getInode()); if (newTree.getChild() == 0) { newTree.setParent(tree.getParent()); newTree.setChild(file.getInode()); newTree.setRelationType(tree.getRelationType()); newTree.setTreeOrder(0); TreeFactory.saveTree(newTree); } } } List<Permission> permissions = perAPI.getPermissions(folder); for (Permission permission : permissions) { Permission filePermission = new Permission(); filePermission.setPermission(permission.getPermission()); filePermission.setRoleId(permission.getRoleId()); filePermission.setInode(identifier.getInode()); perAPI.save(filePermission); } } catch (Exception ex) { Logger.debug(this, ex.toString()); } } } else { throw new IOException("You don't have access to add that folder/host"); } } Code Sample 2: public static String makeMD5(String pin) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pin.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { hexString.append(Integer.toHexString(0xFF & hash[i])); } return hexString.toString(); } catch (Exception e) { return null; } }
11
Code Sample 1: public static void writeFullImageToStream(Image scaledImage, String javaFormat, OutputStream os) throws IOException { BufferedImage bufImage = new BufferedImage(scaledImage.getWidth(null), scaledImage.getHeight(null), BufferedImage.TYPE_BYTE_BINARY); Graphics gr = bufImage.getGraphics(); gr.drawImage(scaledImage, 0, 0, null); gr.dispose(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(bufImage, javaFormat, bos); IOUtils.copyStreams(new ByteArrayInputStream(bos.toByteArray()), os); } Code Sample 2: private static String fetchImageViaHttp(URL imgUrl) throws IOException { String sURL = imgUrl.toString(); String imgFile = imgUrl.getPath(); HttpURLConnection cnx = (HttpURLConnection) imgUrl.openConnection(); String uri = null; try { cnx.setAllowUserInteraction(false); cnx.setDoOutput(true); cnx.addRequestProperty("Cache-Control", "no-cache"); RequestContext ctx = RequestContext.get(); if (ctx != null) cnx.addRequestProperty("User-Agent", ctx.header("user-agent")); else cnx.addRequestProperty("User-Agent", user_agent); cnx.addRequestProperty("Referer", sURL.substring(0, sURL.indexOf('/', sURL.indexOf('.')) + 1)); cnx.connect(); if (cnx.getResponseCode() != HttpURLConnection.HTTP_OK) return null; InputStream imgData = cnx.getInputStream(); String ext = FilenameUtils.getExtension(imgFile).toLowerCase(); if (!Multimedia.isImageFile("aa." + ext)) ext = "jpg"; uri = FMT_FN.format(new Date()) + RandomStringUtils.randomAlphanumeric(4) + '.' + ext; File fileDest = new File(img_path + uri); if (!fileDest.getParentFile().exists()) fileDest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(fileDest); try { IOUtils.copy(imgData, fos); } finally { IOUtils.closeQuietly(imgData); IOUtils.closeQuietly(fos); } } finally { cnx.disconnect(); } return RequestContext.get().contextPath() + "/uploads/img/" + uri; }
11
Code Sample 1: public final void testT4CClientWriter() throws Exception { InputStream is = ClassLoader.getSystemResourceAsStream(this.testFileName); T4CClientReader reader = new T4CClientReader(is, rc); File tmpFile = File.createTempFile("barde", ".log", this.tmpDir); System.out.println("tmp=" + tmpFile.getAbsolutePath()); T4CClientWriter writer = new T4CClientWriter(new FileOutputStream(tmpFile), rc); for (Message m = reader.read(); m != null; m = reader.read()) writer.write(m); writer.close(); InputStream fa = ClassLoader.getSystemResourceAsStream(this.testFileName); FileInputStream fb = new FileInputStream(tmpFile); for (int ba = fa.read(); ba != -1; ba = fa.read()) assertEquals(ba, fb.read()); } Code Sample 2: protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } }
00
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 InputSource resolveEntity(String pPublicId, String pSystemId) throws SAXException, IOException { try { URL url = new URL(pSystemId); String fileName = (String) urlMap.get(url); if (fileName != null) { FileInputStream istream = new FileInputStream(new File(schemaDir, fileName)); InputSource isource = new InputSource(istream); isource.setSystemId(url.toString()); return isource; } String file = url.getFile(); if (file == null) { file = ""; } else { int offset = file.lastIndexOf('/'); if (offset >= 0) { file = file.substring(offset + 1); } } if ("".equals(file)) { file = "schema.xsd"; } int offset = file.lastIndexOf('.'); String prefix; String suffix; String numAsStr = ""; if (offset > 0 && offset < file.length()) { prefix = file.substring(0, offset); suffix = file.substring(offset); } else { prefix = file; suffix = ".xsd"; } File f; for (int num = 1; ; ++num) { f = new File(schemaDir, prefix + numAsStr + suffix); if (f.exists()) { numAsStr = "_" + num; } else { break; } } InputStream istream = url.openStream(); schemaDir.mkdirs(); FileOutputStream fos = new FileOutputStream(f); try { byte[] buffer = new byte[1024]; for (; ; ) { int res = istream.read(buffer); if (res == -1) { break; } else if (res > 0) { fos.write(buffer, 0, res); } } istream.close(); fos.close(); fos = null; } finally { if (fos != null) { try { f.delete(); } catch (Throwable ignore) { } } } urlMap.put(url, f.getName()); InputSource isource = new InputSource(new FileInputStream(f)); isource.setSystemId(url.toString()); return isource; } catch (Exception e) { JaxMeServlet.this.log("Failed to resolve URL " + pSystemId, e); } return null; }
00
Code Sample 1: public List<Mosque> getAllMosquaisFromDataBase() { List<Mosque> mosquais = new ArrayList<Mosque>(); InputStream is = null; String result = ""; ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); if (MyMapActivity.DEVELOPER_MODE) { nameValuePairs.add(new BasicNameValuePair(Param.LATITUDE, MyMapActivity.mLatitude + "")); nameValuePairs.add(new BasicNameValuePair(Param.LONGITUDE, MyMapActivity.mLongitude + "")); } else { nameValuePairs.add(new BasicNameValuePair(Param.LATITUDE, MyMapActivity.myLocation.getLatitude() + "")); nameValuePairs.add(new BasicNameValuePair(Param.LONGITUDE, MyMapActivity.myLocation.getLongitude() + "")); } nameValuePairs.add(new BasicNameValuePair(Param.RAYON, DataBaseQuery.rayon * Param.KM_MARGE + "")); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(Param.URI_SELECT_ALL_DATA_BASE); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONArray jArray = new JSONArray(result); for (int i = 0; i < jArray.length(); i++) { JSONObject json_data = jArray.getJSONObject(i); Mosque mosquai = new Mosque(json_data.getInt(Param.ID), json_data.getString(Param.NOM), json_data.getDouble(Param.LATITUDE), json_data.getDouble(Param.LONGITUDE), json_data.getString(Param.INFO), json_data.getInt(Param.HAVE_PICTURE) == 1 ? true : false, json_data.getString(Param.PICTURE)); mosquais.add(mosquai); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return mosquais; } Code Sample 2: public static void extractZipPackage(String fileName, String destinationFolder) throws Exception { if (NullStatus.isNull(destinationFolder)) { destinationFolder = ""; } new File(destinationFolder).mkdirs(); File inputFile = new File(fileName); ZipFile zipFile = new ZipFile(inputFile); Enumeration<? extends ZipEntry> oEnum = zipFile.entries(); while (oEnum.hasMoreElements()) { ZipEntry zipEntry = oEnum.nextElement(); File file = new File(destinationFolder + "/" + zipEntry.getName()); if (zipEntry.isDirectory()) { file.mkdirs(); } else { String destinationFolderName = destinationFolder + "/" + zipEntry.getName(); destinationFolderName = destinationFolderName.substring(0, destinationFolderName.lastIndexOf("/")); new File(destinationFolderName).mkdirs(); FileOutputStream fos = new FileOutputStream(file); IOUtils.copy(zipFile.getInputStream(zipEntry), fos); fos.close(); } } }
00
Code Sample 1: private void createNodes() { try { URL url = this.getClass().getResource("NodesFile.txt"); InputStreamReader inReader = new InputStreamReader(url.openStream()); BufferedReader inNodes = new BufferedReader(inReader); String s; while ((s = inNodes.readLine()) != null) { String label = inNodes.readLine(); String fullText = inNodes.readLine(); String type = inNodes.readLine(); Node n = new Node(s, type); n.label = label; n.fullText = fullText; node.add(n); } inNodes.close(); url = this.getClass().getResource("EdgesFile.txt"); inReader = new InputStreamReader(url.openStream()); BufferedReader inEdges = new BufferedReader(inReader); while ((s = inEdges.readLine()) != null) edge.add(new Edge(s, inEdges.readLine(), inEdges.readLine(), inEdges.readLine())); inEdges.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static String encryptPassword(String password) throws PasswordException { String hash = null; if (password != null && !password.equals("")) { try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(password.getBytes("UTF-8")); byte raw[] = md.digest(); hash = String.valueOf(Base64Coder.encode(raw)); } catch (NoSuchAlgorithmException nsae) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } catch (UnsupportedEncodingException uee) { throw new PasswordException(PasswordException.SYSTEM_ERROR); } } return hash; }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { FileChannel from = new FileInputStream(src).getChannel(); FileChannel to = new FileOutputStream(dst).getChannel(); from.transferTo(0, src.length(), to); from.close(); to.close(); } Code Sample 2: @Override public Collection<IAuthor> doImport() throws Exception { progress.initialize(2, "Ściągam autorów amerykańskich"); String url = "http://pl.wikipedia.org/wiki/Kategoria:Ameryka%C5%84scy_autorzy_fantastyki"; UrlResource resource = new UrlResource(url); InputStream urlInputStream = resource.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(urlInputStream, writer); progress.advance("Parsuję autorów amerykańskich"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String httpDoc = writer.toString(); httpDoc = httpDoc.replaceFirst("(?s)<!DOCTYPE.+?>\\n", ""); httpDoc = httpDoc.replaceAll("(?s)<script.+?</script>", ""); httpDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" + httpDoc; ByteArrayInputStream byteInputStream = new ByteArrayInputStream(httpDoc.getBytes("UTF-8")); Document doc = builder.parse(byteInputStream); ArrayList<String> authorNames = new ArrayList<String>(); ArrayList<IAuthor> authors = new ArrayList<IAuthor>(); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList list = (NodeList) xpath.evaluate("//ul/li/div/div/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } list = (NodeList) xpath.evaluate("//td/ul/li/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } for (String name : authorNames) { int idx = name.lastIndexOf(' '); String fname = name.substring(0, idx).trim(); String lname = name.substring(idx + 1).trim(); authors.add(new Author(fname, lname)); } progress.advance("Wykonano"); return authors; }
00
Code Sample 1: public String parse(String queryText) throws ParseException { try { StringBuilder sb = new StringBuilder(); queryText = Val.chkStr(queryText); if (queryText.length() > 0) { URL url = new URL(getUrl(queryText)); InputStream in = url.openStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } } return sb.toString(); } catch (IOException ex) { throw new ParseException("Ontology parser is unable to parse term: \"" + queryText + "\" due to internal error: " + ex.getMessage()); } } 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 File copyFileAs(String path, String newName) { File src = new File(path); File dest = new File(newName); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; } Code Sample 2: 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 = { { 4., 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"); }
00
Code Sample 1: @Override protected PermissionCollection getPermissions(CodeSource _codeSource) { PermissionCollection perms = super.getPermissions(_codeSource); URL url = _codeSource.getLocation(); Permission perm = null; URLConnection urlConnection = null; try { urlConnection = url.openConnection(); urlConnection.connect(); perm = urlConnection.getPermission(); } catch (IOException excp) { perm = null; urlConnection = null; } if (perm == null) { perm = new ModulePermission(url.getHost(), "read"); } if (perm != null) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { final Permission fp = perm; AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() throws SecurityException { sm.checkPermission(fp); return null; } }, this.controlContext); } perms.add(perm); } return perms; } Code Sample 2: public static String getMD5Str(String str) { MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(str.getBytes("UTF-8")); } catch (NoSuchAlgorithmException e) { System.out.println("NoSuchAlgorithmException caught!"); System.exit(-1); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] byteArray = messageDigest.digest(); StringBuffer md5StrBuff = new StringBuffer(); for (int i = 0; i < byteArray.length; i++) { if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i])); else md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i])); } return md5StrBuff.toString(); }
00
Code Sample 1: @Override public void parse() throws DocumentException, IOException { URL url = new URL(getDataUrl()); URLConnection con = url.openConnection(); BufferedReader bStream = new BufferedReader(new InputStreamReader(con.getInputStream())); String s = bStream.readLine(); bStream.readLine(); while ((s = bStream.readLine()) != null) { String[] tokens = s.split("\\|"); ResultUnit unit = new ResultUnit(tokens[3], Float.valueOf(tokens[4]), Integer.valueOf(tokens[2])); set.add(unit); } } Code Sample 2: public static void concatFiles(List<File> sourceFiles, File destFile) throws IOException { FileOutputStream outFile = new FileOutputStream(destFile); FileChannel outChannel = outFile.getChannel(); for (File f : sourceFiles) { FileInputStream fis = new FileInputStream(f); FileChannel channel = fis.getChannel(); channel.transferTo(0, channel.size(), outChannel); channel.close(); fis.close(); } outChannel.close(); }
11
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { assertTrue(resourceName.startsWith("/")); final URL resource = this.getClass().getResource(resourceName); assertNotNull("Expected '" + resourceName + "' not found.", resource); assertTrue(targetDirectory.isAbsolute()); FileUtils.deleteDirectory(targetDirectory); assertTrue(targetDirectory.mkdirs()); ZipInputStream in = null; boolean suppressExceptionOnClose = true; try { in = new ZipInputStream(resource.openStream()); ZipEntry e; while ((e = in.getNextEntry()) != null) { if (e.isDirectory()) { continue; } final File dest = new File(targetDirectory, e.getName()); assertTrue(dest.isAbsolute()); OutputStream out = null; try { out = FileUtils.openOutputStream(dest); IOUtils.copy(in, out); suppressExceptionOnClose = false; } finally { try { if (out != null) { out.close(); } suppressExceptionOnClose = true; } catch (final IOException ex) { if (!suppressExceptionOnClose) { throw ex; } } } in.closeEntry(); } suppressExceptionOnClose = false; } finally { try { if (in != null) { in.close(); } } catch (final IOException e) { if (!suppressExceptionOnClose) { throw e; } } } }
00
Code Sample 1: public static int[] bubbleSortOtimizado(int... a) { boolean swapped; int n = a.length - 2; do { swapped = false; for (int i = 0; i <= n; i++) { if (a[i] > a[i + 1]) { int tmp = a[i]; a[i] = a[i + 1]; a[i + 1] = tmp; swapped = true; } } n = n - 1; } while (swapped); return a; } Code Sample 2: private void importUrl(String str) throws Exception { URL url = new URL(str); InputStream xmlStream = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); MessageHolder messages = MessageHolder.getInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(xmlStream); Element rootElement = document.getDocumentElement(); EntrySetParser entrySetParser = new EntrySetParser(); EntrySetTag entrySet = entrySetParser.process(rootElement); UpdateProteinsI proteinFactory = new UpdateProteins(); BioSourceFactory bioSourceFactory = new BioSourceFactory(); ControlledVocabularyRepository.check(); EntrySetChecker.check(entrySet, proteinFactory, bioSourceFactory); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printCheckerReport(System.err); } else { EntrySetPersister.persist(entrySet); if (messages.checkerMessageExists()) { MessageHolder.getInstance().printPersisterReport(System.err); } else { System.out.println("The data have been successfully saved in your Intact node."); } } }
11
Code Sample 1: private void copyFile(File s, File d) throws IOException { d.getParentFile().mkdirs(); FileChannel inChannel = new FileInputStream(s).getChannel(); FileChannel outChannel = new FileOutputStream(d).getChannel(); int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } inChannel.close(); outChannel.close(); d.setLastModified(s.lastModified()); } Code Sample 2: public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
11
Code Sample 1: public static void main(String[] args) throws Throwable { Options options = new Options(); options.addOption(new CommandLineOptionBuilder("cas", "cas file").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("o", "output directory").longName("outputDir").isRequired(true).build()); options.addOption(new CommandLineOptionBuilder("tempDir", "temp directory").build()); options.addOption(new CommandLineOptionBuilder("prefix", "file prefix for all generated files ( default " + DEFAULT_PREFIX + " )").build()); options.addOption(new CommandLineOptionBuilder("trim", "trim file in sfffile's tab delimmed trim format").build()); options.addOption(new CommandLineOptionBuilder("trimMap", "trim map file containing tab delimited trimmed fastX file to untrimmed counterpart").build()); options.addOption(new CommandLineOptionBuilder("chromat_dir", "directory of chromatograms to be converted into phd " + "(it is assumed the read data for these chromatograms are in a fasta file which the .cas file knows about").build()); options.addOption(new CommandLineOptionBuilder("s", "cache size ( default " + DEFAULT_CACHE_SIZE + " )").longName("cache_size").build()); options.addOption(new CommandLineOptionBuilder("useIllumina", "any FASTQ files in this assembly are encoded in Illumina 1.3+ format (default is Sanger)").isFlag(true).build()); options.addOption(new CommandLineOptionBuilder("useClosureTrimming", "apply additional contig trimming based on JCVI Closure rules").isFlag(true).build()); CommandLine commandLine; try { commandLine = CommandLineUtils.parseCommandLine(options, args); int cacheSize = commandLine.hasOption("s") ? Integer.parseInt(commandLine.getOptionValue("s")) : DEFAULT_CACHE_SIZE; File casFile = new File(commandLine.getOptionValue("cas")); File casWorkingDirectory = casFile.getParentFile(); ReadWriteDirectoryFileServer outputDir = DirectoryFileServer.createReadWriteDirectoryFileServer(commandLine.getOptionValue("o")); String prefix = commandLine.hasOption("prefix") ? commandLine.getOptionValue("prefix") : DEFAULT_PREFIX; TrimDataStore trimDatastore; if (commandLine.hasOption("trim")) { List<TrimDataStore> dataStores = new ArrayList<TrimDataStore>(); final String trimFiles = commandLine.getOptionValue("trim"); for (String trimFile : trimFiles.split(",")) { System.out.println("adding trim file " + trimFile); dataStores.add(new DefaultTrimFileDataStore(new File(trimFile))); } trimDatastore = MultipleDataStoreWrapper.createMultipleDataStoreWrapper(TrimDataStore.class, dataStores); } else { trimDatastore = TrimDataStoreUtil.EMPTY_DATASTORE; } CasTrimMap trimToUntrimmedMap; if (commandLine.hasOption("trimMap")) { trimToUntrimmedMap = new DefaultTrimFileCasTrimMap(new File(commandLine.getOptionValue("trimMap"))); } else { trimToUntrimmedMap = new UnTrimmedExtensionTrimMap(); } boolean useClosureTrimming = commandLine.hasOption("useClosureTrimming"); TraceDataStore<FileSangerTrace> sangerTraceDataStore = null; Map<String, File> sangerFileMap = null; ReadOnlyDirectoryFileServer sourceChromatogramFileServer = null; if (commandLine.hasOption("chromat_dir")) { sourceChromatogramFileServer = DirectoryFileServer.createReadOnlyDirectoryFileServer(new File(commandLine.getOptionValue("chromat_dir"))); sangerTraceDataStore = new SingleSangerTraceDirectoryFileDataStore(sourceChromatogramFileServer, ".scf"); sangerFileMap = new HashMap<String, File>(); Iterator<String> iter = sangerTraceDataStore.getIds(); while (iter.hasNext()) { String id = iter.next(); sangerFileMap.put(id, sangerTraceDataStore.get(id).getFile()); } } PrintWriter logOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".log")), true); PrintWriter consensusOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".consensus.fasta")), true); PrintWriter traceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".traceFiles.txt")), true); PrintWriter referenceFilesOut = new PrintWriter(new FileOutputStream(outputDir.createNewFile(prefix + ".referenceFiles.txt")), true); long startTime = System.currentTimeMillis(); logOut.println(System.getProperty("user.dir")); final ReadWriteDirectoryFileServer tempDir; if (!commandLine.hasOption("tempDir")) { tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(DEFAULT_TEMP_DIR); } else { File t = new File(commandLine.getOptionValue("tempDir")); IOUtil.mkdirs(t); tempDir = DirectoryFileServer.createTemporaryDirectoryFileServer(t); } try { if (!outputDir.contains("chromat_dir")) { outputDir.createNewDir("chromat_dir"); } if (sourceChromatogramFileServer != null) { for (File f : sourceChromatogramFileServer) { String name = f.getName(); OutputStream out = new FileOutputStream(outputDir.createNewFile("chromat_dir/" + name)); final FileInputStream fileInputStream = new FileInputStream(f); try { IOUtils.copy(fileInputStream, out); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(fileInputStream); } } } FastQQualityCodec qualityCodec = commandLine.hasOption("useIllumina") ? FastQQualityCodec.ILLUMINA : FastQQualityCodec.SANGER; CasDataStoreFactory casDataStoreFactory = new MultiCasDataStoreFactory(new H2SffCasDataStoreFactory(casWorkingDirectory, tempDir, EmptyDataStoreFilter.INSTANCE), new H2FastQCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, qualityCodec, tempDir.getRootDir()), new FastaCasDataStoreFactory(casWorkingDirectory, trimToUntrimmedMap, cacheSize)); final SliceMapFactory sliceMapFactory = new LargeNoQualitySliceMapFactory(); CasAssembly casAssembly = new DefaultCasAssembly.Builder(casFile, casDataStoreFactory, trimDatastore, trimToUntrimmedMap, casWorkingDirectory).build(); System.out.println("finished making casAssemblies"); for (File traceFile : casAssembly.getNuceotideFiles()) { traceFilesOut.println(traceFile.getAbsolutePath()); final String name = traceFile.getName(); String extension = FilenameUtils.getExtension(name); if (name.contains("fastq")) { if (!outputDir.contains("solexa_dir")) { outputDir.createNewDir("solexa_dir"); } if (outputDir.contains("solexa_dir/" + name)) { IOUtil.delete(outputDir.getFile("solexa_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "solexa_dir/" + name); } else if ("sff".equals(extension)) { if (!outputDir.contains("sff_dir")) { outputDir.createNewDir("sff_dir"); } if (outputDir.contains("sff_dir/" + name)) { IOUtil.delete(outputDir.getFile("sff_dir/" + name)); } outputDir.createNewSymLink(traceFile.getAbsolutePath(), "sff_dir/" + name); } } for (File traceFile : casAssembly.getReferenceFiles()) { referenceFilesOut.println(traceFile.getAbsolutePath()); } DataStore<CasContig> contigDatastore = casAssembly.getContigDataStore(); Map<String, AceContig> aceContigs = new HashMap<String, AceContig>(); CasIdLookup readIdLookup = sangerFileMap == null ? casAssembly.getReadIdLookup() : new DifferentFileCasIdLookupAdapter(casAssembly.getReadIdLookup(), sangerFileMap); Date phdDate = new Date(startTime); NextGenClosureAceContigTrimmer closureContigTrimmer = null; if (useClosureTrimming) { closureContigTrimmer = new NextGenClosureAceContigTrimmer(2, 5, 10); } for (CasContig casContig : contigDatastore) { final AceContigAdapter adpatedCasContig = new AceContigAdapter(casContig, phdDate, readIdLookup); CoverageMap<CoverageRegion<AcePlacedRead>> coverageMap = DefaultCoverageMap.buildCoverageMap(adpatedCasContig); for (AceContig aceContig : ConsedUtil.split0xContig(adpatedCasContig, coverageMap)) { if (useClosureTrimming) { AceContig trimmedAceContig = closureContigTrimmer.trimContig(aceContig); if (trimmedAceContig == null) { System.out.printf("%s was completely trimmed... skipping%n", aceContig.getId()); continue; } aceContig = trimmedAceContig; } aceContigs.put(aceContig.getId(), aceContig); consensusOut.print(new DefaultNucleotideEncodedSequenceFastaRecord(aceContig.getId(), NucleotideGlyph.convertToString(NucleotideGlyph.convertToUngapped(aceContig.getConsensus().decode())))); } } System.out.printf("finished adapting %d casAssemblies into %d ace contigs%n", contigDatastore.size(), aceContigs.size()); QualityDataStore qualityDataStore = sangerTraceDataStore == null ? casAssembly.getQualityDataStore() : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(QualityDataStore.class, TraceQualityDataStoreAdapter.adapt(sangerTraceDataStore), casAssembly.getQualityDataStore()); final DateTime phdDateTime = new DateTime(phdDate); final PhdDataStore casPhdDataStore = CachedDataStore.createCachedDataStore(PhdDataStore.class, new ArtificalPhdDataStore(casAssembly.getNucleotideDataStore(), qualityDataStore, phdDateTime), cacheSize); final PhdDataStore phdDataStore = sangerTraceDataStore == null ? casPhdDataStore : MultipleDataStoreWrapper.createMultipleDataStoreWrapper(PhdDataStore.class, new PhdSangerTraceDataStoreAdapter<FileSangerTrace>(sangerTraceDataStore, phdDateTime), casPhdDataStore); WholeAssemblyAceTag pathToPhd = new DefaultWholeAssemblyAceTag("phdball", "cas2consed", new Date(DateTimeUtils.currentTimeMillis()), "../phd_dir/" + prefix + ".phd.ball"); AceAssembly aceAssembly = new DefaultAceAssembly<AceContig>(new SimpleDataStore<AceContig>(aceContigs), phdDataStore, Collections.<File>emptyList(), new DefaultAceTagMap(Collections.<ConsensusAceTag>emptyList(), Collections.<ReadAceTag>emptyList(), Arrays.asList(pathToPhd))); System.out.println("writing consed package..."); ConsedWriter.writeConsedPackage(aceAssembly, sliceMapFactory, outputDir.getRootDir(), prefix, false); } catch (Throwable t) { t.printStackTrace(logOut); throw t; } finally { long endTime = System.currentTimeMillis(); logOut.printf("took %s%n", new Period(endTime - startTime)); logOut.flush(); logOut.close(); outputDir.close(); consensusOut.close(); traceFilesOut.close(); referenceFilesOut.close(); trimDatastore.close(); } } catch (ParseException e) { printHelp(options); System.exit(1); } } Code Sample 2: protected static void copyFile(File from, File to) throws IOException { if (!from.isFile() || !to.isFile()) { throw new IOException("Both parameters must be files. from is " + from.isFile() + ", to is " + to.isFile()); } FileChannel in = (new FileInputStream(from)).getChannel(); FileChannel out = (new FileOutputStream(to)).getChannel(); in.transferTo(0, from.length(), out); in.close(); out.close(); }
00
Code Sample 1: public TestReport runImpl() throws Exception { DocumentFactory df = new SAXDocumentFactory(GenericDOMImplementation.getDOMImplementation(), parserClassName); File f = (new File(testFileName)); URL url = f.toURL(); Document doc = df.createDocument(null, rootTag, url.toString(), url.openStream()); File ser1 = File.createTempFile("doc1", "ser"); File ser2 = File.createTempFile("doc2", "ser"); try { ObjectOutputStream oos; oos = new ObjectOutputStream(new FileOutputStream(ser1)); oos.writeObject(doc); oos.close(); ObjectInputStream ois; ois = new ObjectInputStream(new FileInputStream(ser1)); doc = (Document) ois.readObject(); ois.close(); oos = new ObjectOutputStream(new FileOutputStream(ser2)); oos.writeObject(doc); oos.close(); } catch (IOException e) { DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode("io.error"); report.addDescriptionEntry("message", e.getClass().getName() + ": " + e.getMessage()); report.addDescriptionEntry("file.name", testFileName); report.setPassed(false); return report; } InputStream is1 = new FileInputStream(ser1); InputStream is2 = new FileInputStream(ser2); for (; ; ) { int i1 = is1.read(); int i2 = is2.read(); if (i1 == -1 && i2 == -1) { return reportSuccess(); } if (i1 != i2) { DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode("difference.found"); report.addDescriptionEntry("file.name", testFileName); report.setPassed(false); return report; } } } Code Sample 2: public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
11
Code Sample 1: public static int zipFile(File file_input, File dir_output) { File zip_output = new File(dir_output, file_input.getName() + ".zip"); ZipOutputStream zip_out_stream; try { FileOutputStream out = new FileOutputStream(zip_output); zip_out_stream = new ZipOutputStream(new BufferedOutputStream(out)); } catch (IOException e) { return STATUS_OUT_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { ZipEntry zip_entry = new ZipEntry(file_input.getName()); zip_out_stream.putNextEntry(zip_entry); FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE); while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) zip_out_stream.write(input_buffer, 0, len); in.close(); } catch (IOException e) { return STATUS_ZIP_FAIL; } try { zip_out_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
11
Code Sample 1: public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } } Code Sample 2: public void execute() throws MojoExecutionException, MojoFailureException { try { this.getLog().info("copy source web.xml - " + this.getWebXml() + " to build dir (source web.xml required if mergewebxml execution is enabled)"); File destination = new File(this.getBuildDir(), "web.xml"); if (!destination.exists()) { destination.getParentFile().mkdirs(); destination.createNewFile(); } FileIOUtils.copyFile(this.getWebXml(), destination); for (int i = 0; i < this.getCompileTarget().length; i++) { File moduleFile = null; for (Iterator it = this.getProject().getCompileSourceRoots().iterator(); it.hasNext() && moduleFile == null; ) { File check = new File(it.next().toString() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } for (Iterator it = this.getProject().getResources().iterator(); it.hasNext(); ) { Resource r = (Resource) it.next(); File check = new File(r.getDirectory() + "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"); getLog().debug("Looking for file: " + check.getAbsolutePath()); if (check.exists()) { moduleFile = check; } } ClassLoader loader = this.fixThreadClasspath(); if (moduleFile == null) { try { String classpath = "/" + this.getCompileTarget()[i].replace('.', '/') + ".gwt.xml"; InputStream is = loader.getResourceAsStream(classpath); System.out.println("Looking for classpath: " + classpath + "(" + (is != null) + ")"); if (is != null) { File temp = new File(this.getBuildDir(), this.getCompileTarget()[i].concat(".gwt.xml")); FileOutputStream fos = new FileOutputStream(temp); FileIOUtils.copyStream(is, fos); moduleFile = temp; } } catch (IOException e) { this.getLog().info(e); } } GwtWebInfProcessor processor = null; try { if (moduleFile != null) { getLog().info("Module file: " + moduleFile.getAbsolutePath()); processor = new GwtWebInfProcessor(this.getCompileTarget()[i], moduleFile, destination.getAbsolutePath(), destination.getAbsolutePath(), this.isWebXmlServletPathAsIs()); processor.process(); } else { throw new MojoExecutionException("module file null"); } } catch (ExitException e) { this.getLog().info(e.getMessage()); } } } catch (Exception e) { throw new MojoExecutionException("Unable to merge web.xml", e); } }
00
Code Sample 1: private void unpackBundle() throws IOException { File useJarPath = null; if (DownloadManager.isWindowsVista()) { useJarPath = lowJarPath; File jarDir = useJarPath.getParentFile(); if (jarDir != null) { jarDir.mkdirs(); } } else { useJarPath = jarPath; } DownloadManager.log("Unpacking " + this + " to " + useJarPath); InputStream rawStream = new FileInputStream(localPath); JarInputStream in = new JarInputStream(rawStream) { public void close() throws IOException { } }; try { File jarTmp = null; JarEntry entry; while ((entry = in.getNextJarEntry()) != null) { String entryName = entry.getName(); if (entryName.equals("classes.pack")) { File packTmp = new File(useJarPath + ".pack"); packTmp.getParentFile().mkdirs(); DownloadManager.log("Writing temporary .pack file " + packTmp); OutputStream tmpOut = new FileOutputStream(packTmp); try { DownloadManager.send(in, tmpOut); } finally { tmpOut.close(); } jarTmp = new File(useJarPath + ".tmp"); DownloadManager.log("Writing temporary .jar file " + jarTmp); unpack(packTmp, jarTmp); packTmp.delete(); } else if (!entryName.startsWith("META-INF")) { File dest; if (DownloadManager.isWindowsVista()) { dest = new File(lowJavaPath, entryName.replace('/', File.separatorChar)); } else { dest = new File(DownloadManager.JAVA_HOME, entryName.replace('/', File.separatorChar)); } if (entryName.equals(BUNDLE_JAR_ENTRY_NAME)) dest = useJarPath; File destTmp = new File(dest + ".tmp"); boolean exists = dest.exists(); if (!exists) { DownloadManager.log(dest + ".mkdirs()"); dest.getParentFile().mkdirs(); } try { DownloadManager.log("Using temporary file " + destTmp); FileOutputStream out = new FileOutputStream(destTmp); try { byte[] buffer = new byte[2048]; int c; while ((c = in.read(buffer)) > 0) out.write(buffer, 0, c); } finally { out.close(); } if (exists) dest.delete(); DownloadManager.log("Renaming from " + destTmp + " to " + dest); if (!destTmp.renameTo(dest)) { throw new IOException("unable to rename " + destTmp + " to " + dest); } } catch (IOException e) { if (!exists) throw e; } } } if (jarTmp != null) { if (useJarPath.exists()) jarTmp.delete(); else if (!jarTmp.renameTo(useJarPath)) { throw new IOException("unable to rename " + jarTmp + " to " + useJarPath); } } if (DownloadManager.isWindowsVista()) { DownloadManager.log("Using broker to move " + name); if (!DownloadManager.moveDirWithBroker(DownloadManager.getKernelJREDir() + name)) { throw new IOException("unable to create " + name); } DownloadManager.log("Broker finished " + name); } DownloadManager.log("Finished unpacking " + this); } finally { rawStream.close(); } if (deleteOnInstall) { localPath.delete(); } } Code Sample 2: public Login authenticateClient() { Object o; String user, password; Vector<Login> clientLogins = ClientLoginsTableModel.getClientLogins(); Login login = null; try { socket.setSoTimeout(25000); objectOut.writeObject("JFRITZ SERVER 1.1"); objectOut.flush(); o = objectIn.readObject(); if (o instanceof String) { user = (String) o; objectOut.flush(); for (Login l : clientLogins) { if (l.getUser().equals(user)) { login = l; break; } } if (login != null) { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(login.getPassword().getBytes()); DESKeySpec desKeySpec = new DESKeySpec(md.digest()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); desCipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] dataKeySeed = new byte[32]; Random random = new Random(); random.nextBytes(dataKeySeed); md.reset(); md.update(dataKeySeed); dataKeySeed = md.digest(); SealedObject dataKeySeedSealed; dataKeySeedSealed = new SealedObject(dataKeySeed, desCipher); objectOut.writeObject(dataKeySeedSealed); objectOut.flush(); desKeySpec = new DESKeySpec(dataKeySeed); secretKey = keyFactory.generateSecret(desKeySpec); inCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); outCipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); inCipher.init(Cipher.DECRYPT_MODE, secretKey); outCipher.init(Cipher.ENCRYPT_MODE, secretKey); SealedObject sealedObject = (SealedObject) objectIn.readObject(); o = sealedObject.getObject(inCipher); if (o instanceof String) { String response = (String) o; if (response.equals("OK")) { SealedObject ok_sealed = new SealedObject("OK", outCipher); objectOut.writeObject(ok_sealed); return login; } else { Debug.netMsg("Client sent false response to challenge!"); } } else { Debug.netMsg("Client sent false object as response to challenge!"); } } else { Debug.netMsg("client sent unkown username: " + user); } } } catch (IllegalBlockSizeException e) { Debug.netMsg("Wrong blocksize for sealed object!"); Debug.error(e.toString()); e.printStackTrace(); } catch (ClassNotFoundException e) { Debug.netMsg("received unrecognized object from client!"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { Debug.netMsg("MD5 Algorithm not present in this JVM!"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeySpecException e) { Debug.netMsg("Error generating cipher, problems with key spec?"); Debug.error(e.toString()); e.printStackTrace(); } catch (InvalidKeyException e) { Debug.netMsg("Error genertating cipher, problems with key?"); Debug.error(e.toString()); e.printStackTrace(); } catch (NoSuchPaddingException e) { Debug.netMsg("Error generating cipher, problems with padding?"); Debug.error(e.toString()); e.printStackTrace(); } catch (IOException e) { Debug.netMsg("Error authenticating client!"); Debug.error(e.toString()); e.printStackTrace(); } catch (BadPaddingException e) { Debug.netMsg("Bad padding exception!"); Debug.error(e.toString()); e.printStackTrace(); } return null; }
00
Code Sample 1: public void movePrior(String[] showOrder, String[] orgID, String targetShowOrder, String targetOrgID) throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; int moveCount = showOrder.length; DBOperation dbo = factory.createDBOperation(POOL_NAME); String strQuery = "select show_order from " + Common.ORGANIZE_TABLE + " where show_order=" + showOrder[moveCount - 1] + " and organize_id= '" + orgID[moveCount - 1] + "'"; try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strQuery); result = ps.executeQuery(); int maxOrderNo = 0; if (result.next()) { maxOrderNo = result.getInt(1); } String[] sqls = new String[moveCount + 1]; sqls[0] = "update " + Common.ORGANIZE_TABLE + " set show_order=" + maxOrderNo + " where show_order=" + targetShowOrder + " and organize_id= '" + targetOrgID + "'"; for (int i = 0; i < showOrder.length; i++) { sqls[i + 1] = "update " + Common.ORGANIZE_TABLE + " set show_order=show_order-1" + " where show_order=" + showOrder[i] + " and organize_id= '" + orgID[i] + "'"; } for (int j = 0; j < sqls.length; j++) { ps = con.prepareStatement(sqls[j]); int resultCount = ps.executeUpdate(); if (resultCount != 1) { throw new CesSystemException("Organize.movePrior(): ERROR Inserting data " + "in T_SYS_ORGANIZE update !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { if (con != null) { con.rollback(); } throw new CesSystemException("Organize.movePrior(): SQLException while mov organize order " + " :\n\t" + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } Code Sample 2: public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } }
00
Code Sample 1: protected synchronized String encryptThis(String seed, String text) throws EncryptionException { String encryptedValue = null; String textToEncrypt = text; if (seed != null) { textToEncrypt = seed.toLowerCase() + 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: @Override public void run() { String lastVersion = null; try { URL projectSite = new URL("http://code.google.com/p/g15lastfm/"); URLConnection urlC = projectSite.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlC.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { if (inputLine.contains("<strong>Current version:")) { lastVersion = inputLine; break; } } in.close(); if (lastVersion != null && lastVersion.length() > 0) { lastVersion = lastVersion.substring(lastVersion.indexOf("Current version:") + 16); lastVersion = lastVersion.substring(0, lastVersion.indexOf("</strong>")).trim(); LOGGER.debug("last Version=" + lastVersion); } if (!lastVersion.equals(G15LastfmPlayer.getVersion())) LOGGER.debug("Not necessary to update"); else { LOGGER.debug("New update found!"); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (JOptionPane.showConfirmDialog(null, "New version of G15Lastfm is available to download!", "New Update for G15Lastfm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { LOGGER.debug("User choose to update, opening browser."); Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI("http://code.google.com/p/g15lastfm/")); } catch (IOException e) { LOGGER.debug(e); } catch (URISyntaxException e) { LOGGER.debug(e); } } else { LOGGER.debug("User choose to not update."); } } }); } } catch (Exception e) { LOGGER.debug(e); } }
11
Code Sample 1: private static String genRandomGUID(boolean secure) { String valueBeforeMD5 = ""; String valueAfterMD5 = ""; MessageDigest md5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); return valueBeforeMD5; } long time = System.currentTimeMillis(); long rand = 0; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte[] array = md5.digest(); String strTemp = ""; for (int i = 0; i < array.length; i++) { strTemp = (Integer.toHexString(array[i] & 0XFF)); if (strTemp.length() == 1) { valueAfterMD5 = valueAfterMD5 + "0" + strTemp; } else { valueAfterMD5 = valueAfterMD5 + strTemp; } } return valueAfterMD5.toUpperCase(); } Code Sample 2: public String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("SHA-1"); byte[] sha1hash = new byte[40]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); sha1hash = md.digest(); return convertToHex(sha1hash); }
00
Code Sample 1: @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final Map<String, String> fileAttr = new HashMap<String, String>(); boolean download = false; String dw = req.getParameter("d"); if (StringUtils.isNotEmpty(dw) && StringUtils.equals(dw, "true")) { download = true; } final ByteArrayOutputStream imageOutputStream = new ByteArrayOutputStream(DEFAULT_CONTENT_LENGTH_SIZE); InputStream imageInputStream = null; try { imageInputStream = getImageAsStream(req, fileAttr); IOUtils.copy(imageInputStream, imageOutputStream); resp.setHeader("Cache-Control", "no-store"); resp.setHeader("Pragma", "no-cache"); resp.setDateHeader("Expires", 0); resp.setContentType(fileAttr.get("mimetype")); if (download) { resp.setHeader("Content-Disposition", "attachment; filename=\"" + fileAttr.get("filename") + "\""); } final ServletOutputStream responseOutputStream = resp.getOutputStream(); responseOutputStream.write(imageOutputStream.toByteArray()); responseOutputStream.flush(); responseOutputStream.close(); } catch (Exception e) { e.printStackTrace(); resp.setContentType("text/html"); resp.getWriter().println("<h1>Sorry... cannot find document</h1>"); } finally { IOUtils.closeQuietly(imageInputStream); IOUtils.closeQuietly(imageOutputStream); } } Code Sample 2: public void testAuthentication() throws Exception { String host = "localhost"; int port = DEFAULT_PORT; URL url = new URL("http://" + host + ":" + port + "/"); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); in.close(); waitToStop(); server.setAttribute(name, new Attribute("AuthenticationMethod", "basic")); server.invoke(name, "addAuthorization", new Object[] { "mx4j", "mx4j" }, new String[] { "java.lang.String", "java.lang.String" }); server.invoke(name, "start", null, null); url = new URL("http://" + host + ":" + port + "/"); connection = url.openConnection(); try { in = connection.getInputStream(); } catch (Exception e) { } finally { in.close(); } assertEquals(((HttpURLConnection) connection).getResponseCode(), 401); url = new URL("http://" + host + ":" + port + "/"); connection = url.openConnection(); connection.setRequestProperty("Authorization", "basic bXg0ajpteDRq"); in = connection.getInputStream(); in.close(); waitToStop(); server.setAttribute(name, new Attribute("AuthenticationMethod", "none")); }
00
Code Sample 1: private static void writeUrl(String filePath, String data, String charCoding, boolean urlIsFile) throws IOException { int chunkLength; OutputStream os = null; try { if (!urlIsFile) { URL urlObj = new URL(filePath); URLConnection uc = urlObj.openConnection(); os = uc.getOutputStream(); if (charCoding == null) { String type = uc.getContentType(); if (type != null) { charCoding = getCharCodingFromType(type); } } } else { File f = new File(filePath); os = new FileOutputStream(f); } Writer w; if (charCoding == null) { w = new OutputStreamWriter(os); } else { w = new OutputStreamWriter(os, charCoding); } w.write(data); w.flush(); } finally { if (os != null) os.close(); } } Code Sample 2: public static File copyFileAs(String path, String newName) { File src = new File(path); File dest = new File(newName); try { if (!dest.exists()) { dest.createNewFile(); } FileChannel source = new FileInputStream(src).getChannel(); FileChannel destination = new FileOutputStream(dest).getChannel(); destination.transferFrom(source, 0, source.size()); source.close(); destination.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return dest; }
11
Code Sample 1: 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()); } Code Sample 2: public static void copyFile(final String inFile, final String outFile) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(inFile).getChannel(); out = new FileOutputStream(outFile).getChannel(); in.transferTo(0, in.size(), out); } catch (final Exception e) { } finally { if (in != null) { try { in.close(); } catch (final Exception e) { } } if (out != null) { try { out.close(); } catch (final Exception e) { } } } }
00
Code Sample 1: public ActionForward dbExecute(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest, HttpServletResponse pResponse) throws DatabaseException { Integer key; SubmitUserForm form = (SubmitUserForm) pForm; if (pRequest.getParameter("key") == null) { key = form.getPrimaryKey(); } else { key = Integer.parseInt(pRequest.getParameter("key")); } User currentUser = (User) (pRequest.getSession().getAttribute("login")); if ((currentUser == null) || (!currentUser.getAdminRights() && (currentUser.getPrimaryKey() != key))) { return (pMapping.findForward("denied")); } if (currentUser.getAdminRights()) { pRequest.setAttribute("isAdmin", new Boolean(true)); } if (currentUser.getPDFRights()) { pRequest.setAttribute("pdfRights", Boolean.TRUE); } User user = database.acquireUserByPrimaryKey(key); if (user.isSuperAdmin() && !currentUser.isSuperAdmin()) { return (pMapping.findForward("denied")); } pRequest.setAttribute("user", user); pRequest.setAttribute("taxonomy", database.acquireTaxonomy()); if (form.getAction().equals("none")) { form.setPrimaryKey(user.getPrimaryKey()); } if (form.getAction().equals("edit")) { FormError formError = form.validateFields(); if (formError != null) { if (formError.getFormFieldErrors().get("firstName") != null) { pRequest.setAttribute("FirstNameBad", new Boolean(true)); } if (formError.getFormFieldErrors().get("lastName") != null) { pRequest.setAttribute("LastNameBad", new Boolean(true)); } if (formError.getFormFieldErrors().get("emailAddress") != null) { pRequest.setAttribute("EmailAddressBad", new Boolean(true)); } if (formError.getFormFieldErrors().get("mismatchPassword") != null) { pRequest.setAttribute("mismatchPassword", new Boolean(true)); } if (formError.getFormFieldErrors().get("shortPassword") != null) { pRequest.setAttribute("shortPassword", new Boolean(true)); } return (pMapping.findForward("invalid")); } user.setFirstName(form.getFirstName()); user.setLastName(form.getLastName()); user.setEmailAddress(form.getEmailAddress()); if (!form.getFirstPassword().equals("")) { MessageDigest md; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { throw new DatabaseException("Could not hash password for storage: no such algorithm"); } try { md.update(form.getFirstPassword().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new DatabaseException("Could not hash password for storage: no such encoding"); } user.setPassword((new BASE64Encoder()).encode(md.digest())); } user.setTitle(form.getTitle()); user.setDegree(form.getDegree()); user.setAddress(form.getAddress()); user.setNationality(form.getNationality()); user.setLanguages(form.getLanguages()); user.setHomepage(form.getHomepage()); user.setInstitution(form.getInstitution()); if (pRequest.getParameter("hideEmail") != null) { if (pRequest.getParameter("hideEmail").equals("on")) { user.setHideEmail(true); } } else { user.setHideEmail(false); } User storedUser = database.acquireUserByPrimaryKey(user.getPrimaryKey()); if (currentUser.isSuperAdmin()) { if (pRequest.getParameter("admin") != null) { user.setAdminRights(true); } else { if (!storedUser.isSuperAdmin()) { user.setAdminRights(false); } } } else { user.setAdminRights(storedUser.getAdminRights()); } if (currentUser.isAdmin()) if (pRequest.getParameter("PDFRights") != null) user.setPDFRights(true); else user.setPDFRights(false); if (currentUser.isAdmin()) { if (!storedUser.isAdmin() || !storedUser.isSuperAdmin()) { if (pRequest.getParameter("active") != null) { user.setActive(true); } else { user.setActive(false); } } else { user.setActive(storedUser.getActive()); } } if (currentUser.isAdmin() || currentUser.isSuperAdmin()) { String[] categories = pRequest.getParameterValues("categories"); user.setModeratorRights(new Categories()); if (categories != null) { try { for (int i = 0; i < categories.length; i++) { Integer catkey = Integer.parseInt(categories[i]); Category cat = database.acquireCategoryByPrimaryKey(catkey); user.getModeratorRights().add(cat); } } catch (NumberFormatException nfe) { throw new DatabaseException("Invalid category key."); } } } if (!currentUser.isAdmin() && !currentUser.isSuperAdmin()) { user.setAdminRights(false); user.setSuperAdminRights(false); } database.updateUser(user); if (currentUser.getPrimaryKey() == user.getPrimaryKey()) { pRequest.getSession().setAttribute("login", user); } pRequest.setAttribute("helpKey", key); if (currentUser.isAdmin() || currentUser.isSuperAdmin()) { return (pMapping.findForward("adminfinished")); } return (pMapping.findForward("finished")); } return (pMapping.findForward("success")); } Code Sample 2: private static MappedObject sendHttpRequestToUrl(URL url, String method) throws Exception { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.connect(); InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder buffer = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { buffer.append(line); } System.out.println("Read: " + buffer.toString()); connection.disconnect(); JAXBContext context = JAXBContext.newInstance(MappedObject.class); Unmarshaller unmarshaller = context.createUnmarshaller(); MappedObject mapped = (MappedObject) unmarshaller.unmarshal(new StringReader(buffer.toString())); return mapped; } catch (IOException e) { e.printStackTrace(); } throw new Exception("Could not establish connection to " + url.toExternalForm()); }
00
Code Sample 1: public void run() { Thread.currentThread().setName("zhongwen.com watcher"); String url = getURL(); try { while (m_shouldBeRunning) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream(), "ISO8859_1")); String line; Vector chatLines = new Vector(); boolean startGrabbing = false; while ((line = reader.readLine()) != null) { if (line.indexOf("</style>") >= 0) { startGrabbing = true; } else if (startGrabbing) { if (line.equals(m_mostRecentKnownLine)) { break; } chatLines.addElement(line); } } reader.close(); for (int i = chatLines.size() - 1; i >= 0; --i) { String chatLine = (String) chatLines.elementAt(i); m_mostRecentKnownLine = chatLine; if (chatLine.indexOf(":") >= 0) { String from = chatLine.substring(0, chatLine.indexOf(":")); String message = stripTags(chatLine.substring(chatLine.indexOf(":"))); m_source.pushMessage(new ZhongWenMessage(m_source, from, message)); } else { m_source.pushMessage(new ZhongWenMessage(m_source, null, stripTags(chatLine))); } } Thread.sleep(SLEEP_TIME); } catch (InterruptedIOException e) { } catch (InterruptedException e) { } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { m_source.disconnect(); throw e; } catch (Error e) { m_source.disconnect(); throw e; } } Code Sample 2: private String hashPassword(String password) { if (password != null && password.trim().length() > 0) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.trim().getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); return hash.toString(16); } catch (NoSuchAlgorithmException nsae) { } } return null; }
00
Code Sample 1: private void add(Hashtable applicantInfo) throws Exception { String mode = "".equals(getParam("applicant_id_gen").trim()) ? "update" : "insert"; String applicant_id = getParam("applicant_id"); String password = getParam("password"); if ("".equals(applicant_id)) applicant_id = getParam("applicant_id_gen"); if ("".equals(getParam("applicant_name"))) throw new Exception("Can not have empty fields!"); applicantInfo.put("id", applicant_id); applicantInfo.put("password", password); applicantInfo.put("name", getParam("applicant_name")); applicantInfo.put("address1", getParam("address1")); applicantInfo.put("address2", getParam("address2")); applicantInfo.put("address3", getParam("address3")); applicantInfo.put("city", getParam("city")); applicantInfo.put("state", getParam("state")); applicantInfo.put("poscode", getParam("poscode")); applicantInfo.put("country_code", getParam("country_list")); applicantInfo.put("email", getParam("email")); applicantInfo.put("phone", getParam("phone")); String birth_year = getParam("birth_year"); String birth_month = getParam("birth_month"); String birth_day = getParam("birth_day"); applicantInfo.put("birth_year", birth_year); applicantInfo.put("birth_month", birth_month); applicantInfo.put("birth_day", birth_day); applicantInfo.put("gender", getParam("gender")); String birth_date = birth_year + "-" + fmt(birth_month) + "-" + fmt(birth_day); applicantInfo.put("birth_date", birth_date); Db db = null; String sql = ""; Connection conn = null; try { db = new Db(); conn = db.getConnection(); conn.setAutoCommit(false); Statement stmt = db.getStatement(); SQLRenderer r = new SQLRenderer(); boolean found = false; { r.add("applicant_id"); r.add("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLSelect("adm_applicant"); ResultSet rs = stmt.executeQuery(sql); if (rs.next()) found = true; else found = false; } if (found && !"update".equals(mode)) throw new Exception("Applicant Id was invalid!"); { r.clear(); r.add("password", (String) applicantInfo.get("password")); r.add("applicant_name", (String) applicantInfo.get("name")); r.add("address1", (String) applicantInfo.get("address1")); r.add("address2", (String) applicantInfo.get("address2")); r.add("address3", (String) applicantInfo.get("address3")); r.add("city", (String) applicantInfo.get("city")); r.add("state", (String) applicantInfo.get("state")); r.add("poscode", (String) applicantInfo.get("poscode")); r.add("country_code", (String) applicantInfo.get("country_code")); r.add("phone", (String) applicantInfo.get("phone")); r.add("birth_date", (String) applicantInfo.get("birth_date")); r.add("gender", (String) applicantInfo.get("gender")); } if (!found) { r.add("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLInsert("adm_applicant"); stmt.executeUpdate(sql); } else { r.update("applicant_id", (String) applicantInfo.get("id")); sql = r.getSQLUpdate("adm_applicant"); stmt.executeUpdate(sql); } conn.commit(); } catch (DbException dbex) { throw dbex; } catch (SQLException sqlex) { try { conn.rollback(); } catch (SQLException rollex) { } throw sqlex; } finally { if (db != null) db.close(); } } Code Sample 2: private static void copyFile(String from, String to) throws IOException { FileReader in = new FileReader(from); FileWriter out = new FileWriter(to); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
11
Code Sample 1: public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } } Code Sample 2: public void handleEvent(Event event) { if (fileDialog == null) { fileDialog = new FileDialog(getShell(), SWT.OPEN); fileDialog.setText("Open device profile file..."); fileDialog.setFilterNames(new String[] { "Device profile (*.jar)" }); fileDialog.setFilterExtensions(new String[] { "*.jar" }); } fileDialog.open(); if (fileDialog.getFileName() != null) { File file; String manifestDeviceName = null; URL[] urls = new URL[1]; ArrayList descriptorEntries = new ArrayList(); try { file = new File(fileDialog.getFilterPath(), fileDialog.getFileName()); JarFile jar = new JarFile(file); Manifest manifest = jar.getManifest(); if (manifest != null) { Attributes attrs = manifest.getMainAttributes(); manifestDeviceName = attrs.getValue("Device-Name"); } for (Enumeration en = jar.entries(); en.hasMoreElements(); ) { String entry = ((JarEntry) en.nextElement()).getName(); if ((entry.toLowerCase().endsWith(".xml") || entry.toLowerCase().endsWith("device.txt")) && !entry.toLowerCase().startsWith("meta-inf")) { descriptorEntries.add(entry); } } jar.close(); urls[0] = file.toURL(); } catch (IOException ex) { Message.error("Error reading file: " + fileDialog.getFileName() + ", " + Message.getCauseMessage(ex), ex); return; } if (descriptorEntries.size() == 0) { Message.error("Cannot find any device profile in file: " + fileDialog.getFileName()); return; } if (descriptorEntries.size() > 1) { manifestDeviceName = null; } ClassLoader classLoader = Common.createExtensionsClassLoader(urls); HashMap devices = new HashMap(); for (Iterator it = descriptorEntries.iterator(); it.hasNext(); ) { JarEntry entry = (JarEntry) it.next(); try { devices.put(entry.getName(), DeviceImpl.create(emulatorContext, classLoader, entry.getName(), SwtDevice.class)); } catch (IOException ex) { Message.error("Error parsing device profile, " + Message.getCauseMessage(ex), ex); return; } } for (int i = 0; i < deviceModel.size(); i++) { DeviceEntry entry = (DeviceEntry) deviceModel.elementAt(i); if (devices.containsKey(entry.getDescriptorLocation())) { devices.remove(entry.getDescriptorLocation()); } } if (devices.size() == 0) { Message.info("Device profile already added"); return; } try { File deviceFile = new File(Config.getConfigPath(), file.getName()); if (deviceFile.exists()) { deviceFile = File.createTempFile("device", ".jar", Config.getConfigPath()); } IOUtils.copyFile(file, deviceFile); DeviceEntry entry = null; for (Iterator it = devices.keySet().iterator(); it.hasNext(); ) { String descriptorLocation = (String) it.next(); Device device = (Device) devices.get(descriptorLocation); if (manifestDeviceName != null) { entry = new DeviceEntry(manifestDeviceName, deviceFile.getName(), descriptorLocation, false); } else { entry = new DeviceEntry(device.getName(), deviceFile.getName(), descriptorLocation, false); } deviceModel.addElement(entry); for (int i = 0; i < deviceModel.size(); i++) { if (deviceModel.elementAt(i) == entry) { lsDevices.add(entry.getName()); lsDevices.select(i); } } Config.addDeviceEntry(entry); } lsDevicesListener.widgetSelected(null); } catch (IOException ex) { Message.error("Error adding device profile, " + Message.getCauseMessage(ex), ex); return; } } }
11
Code Sample 1: @Override protected void processImport() throws SudokuInvalidFormatException { importFolder(mUri.getLastPathSegment()); try { URL url = new URL(mUri.toString()); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = null; try { br = new BufferedReader(isr); String s; while ((s = br.readLine()) != null) { if (!s.equals("")) { importGame(s); } } } finally { if (br != null) br.close(); } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } Code Sample 2: public Constructor run() throws Exception { String path = "META-INF/services/" + BeanletApplicationContext.class.getName(); ClassLoader loader = Thread.currentThread().getContextClassLoader(); final Enumeration<URL> urls; if (loader == null) { urls = BeanletApplicationContext.class.getClassLoader().getResources(path); } else { urls = loader.getResources(path); } while (urls.hasMoreElements()) { URL url = urls.nextElement(); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); try { String className = null; while ((className = reader.readLine()) != null) { final String name = className.trim(); if (!name.startsWith("#") && !name.startsWith(";") && !name.startsWith("//")) { final Class<?> cls; if (loader == null) { cls = Class.forName(name); } else { cls = Class.forName(name, true, loader); } int m = cls.getModifiers(); if (BeanletApplicationContext.class.isAssignableFrom(cls) && !Modifier.isAbstract(m) && !Modifier.isInterface(m)) { Constructor constructor = cls.getDeclaredConstructor(); if (!Modifier.isPublic(constructor.getModifiers())) { constructor.setAccessible(true); } return constructor; } else { throw new ClassCastException(cls.getName()); } } } } finally { reader.close(); } } throw new BeanletApplicationException("No " + "BeanletApplicationContext implementation " + "found."); }
11
Code Sample 1: public static void copyFile(File in, File out) throws FileNotFoundException, IOException { FileChannel sourceChannel = null; FileChannel destinationChannel = null; try { sourceChannel = new FileInputStream(in).getChannel(); destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { try { sourceChannel.close(); } catch (Exception ex) { } try { destinationChannel.close(); } catch (Exception ex) { } } } Code Sample 2: @Test public void testWriteAndReadFirstLevel() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile directory1 = new RFile("directory1"); RFile file = new RFile(directory1, "testreadwrite1st.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
00
Code Sample 1: @Override protected void copy(InputStream inputs, OutputStream outputs) throws IOException { if (outputs == null) { throw new NullPointerException(); } if (inputs == null) { throw new NullPointerException(); } ZipOutputStream zipoutputs = null; try { zipoutputs = new ZipOutputStream(outputs); zipoutputs.putNextEntry(new ZipEntry("default")); IOUtils.copy(inputs, zipoutputs); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (zipoutputs != null) { zipoutputs.close(); } if (inputs != null) { inputs.close(); } } } Code Sample 2: public static void upper() throws Exception { File input = new File("dateiname"); PostMethod post = new PostMethod("url"); post.setRequestBody(new FileInputStream(input)); if (input.length() < Integer.MAX_VALUE) post.setRequestContentLength((int) input.length()); else post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED); post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859�1"); HttpClient httpclient = new HttpClient(); httpclient.executeMethod(post); post.releaseConnection(); URL url = new URL("https://www.amazon.de/"); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { System.out.println(line); } rd.close(); }
00
Code Sample 1: private static void stampaFoglioRisposte(HttpSession httpSess, Appelli appello, Elaborati el, StringBuffer retVal, boolean primaVolta, String url, boolean anonimo) { InputStream is = null; String html = null; final int MAX_RIGHE_PER_PAGINA = 25; long totaleDomande = EsamiDAO.trovaQuanteDomandeElaborato(el.getID()); long numPagine = 0, totalePagine = (long) Math.ceil(totaleDomande / 50.0); String urlBarcode = null; while (numPagine < totalePagine) { try { urlBarcode = URLEncoder.encode(HtmlCodeForPrint.creaBarcode("" + appello.getID() + "-" + el.getID() + "-" + (numPagine + 1), url), "UTF-8"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex); } String jsp = url + "jsp/StampaRisposte.jsp?base=" + (numPagine * MAX_RIGHE_PER_PAGINA) + "&urlbarcode=" + urlBarcode; try { URL urlJSP = new URL(jsp); is = urlJSP.openStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int letto = is.read(); while (letto != -1) { baos.write(letto); letto = is.read(); } html = baos.toString(); } catch (IOException ex) { Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } finally { try { is.close(); } catch (IOException ex) { Logger.getLogger(GestioneStampaAppello.class.getName()).log(Level.SEVERE, null, ex); } numPagine++; } } retVal.append(html); } Code Sample 2: private void writeToUrl(byte[] data, String url) throws IOException, MalformedURLException { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); OutputStream out = connection.getOutputStream(); out.write(data); out.flush(); out.close(); }
00
Code Sample 1: private void translate(String sender, String message) { StringTokenizer st = new StringTokenizer(message, " "); message = message.replaceFirst(st.nextToken(), ""); String typeCode = st.nextToken(); message = message.replaceFirst(typeCode, ""); try { String data = URLEncoder.encode(message, "UTF-8"); URL url = new URL("http://babelfish.altavista.com/babelfish/tr?doit=done&urltext=" + data + "&lp=" + typeCode); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.contains("input type=hidden name=\"q\"")) { String[] tokens = line.split("\""); sendMessage(sender, tokens[3]); } } wr.close(); rd.close(); } catch (Exception e) { } } Code Sample 2: public LineIterator iterator() { LineIterator ret; final String charsetname; final Charset charset; final CharsetDecoder charsetDecoder; synchronized (this) { charsetname = this.charsetname; charset = this.charset; charsetDecoder = this.charsetDecoder; } try { if (charsetDecoder != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charsetDecoder); else if (charset != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, charset); else if (charsetname != null) ret = new LineIterator(this, url.openStream(), returnNullUponEof, Charset.forName(charsetname)); else ret = new LineIterator(this, url.openStream(), returnNullUponEof, (Charset) null); synchronized (openedIterators) { openedIterators.add(ret); } return ret; } catch (IOException e) { throw new IllegalStateException(e); } }
11
Code Sample 1: public void zipDocsetFiles(SaxHandler theXmlHandler, int theEventId, Attributes theAtts) throws BpsProcessException { ZipOutputStream myZipOut = null; BufferedInputStream myDocumentInputStream = null; String myFinalFile = null; String myTargetPath = null; String myTargetFileName = null; String myInputFileName = null; byte[] myBytesBuffer = null; int myLength = 0; try { myZipOut = new ZipOutputStream(new FileOutputStream(myFinalFile)); myZipOut.putNextEntry(new ZipEntry(myTargetPath + myTargetFileName)); myDocumentInputStream = new BufferedInputStream(new FileInputStream(myInputFileName)); while ((myLength = myDocumentInputStream.read(myBytesBuffer, 0, 4096)) != -1) myZipOut.write(myBytesBuffer, 0, myLength); myZipOut.closeEntry(); myZipOut.close(); } catch (FileNotFoundException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "FileNotFoundException while building zip dest file")); } catch (IOException e) { throw (new BpsProcessException(BpsProcessException.ERR_OPEN_FILE, "IOException while building zip dest file")); } } Code Sample 2: public void save(File f, AudioFileFormat.Type t) throws IOException { if (t.getExtension().equals("raw")) { IOUtils.copy(makeInputStream(), new FileOutputStream(f)); } else { AudioSystem.write(makeStream(), t, f); } }
00
Code Sample 1: public static byte[] SHA1(String... strings) { try { MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.reset(); for (String string : strings) { digest.update(string.getBytes("UTF-8")); } return digest.digest(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.toString(), e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.toString(), e); } } Code Sample 2: private WikiSiteContentInfo createInfoIndexSite(Long domainId) { final UserInfo user = getSecurityService().getCurrentUser(); final Locale locale = new Locale(user.getLocale()); final String country = locale.getLanguage(); InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index_" + country + ".xhtml"); if (inStream == null) { inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("wiki_index.xhtml"); } if (inStream == null) { inStream = new ByteArrayInputStream(DEFAULT_WIKI_INDEX_SITE_TEXT.getBytes()); } if (inStream != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copyLarge(inStream, out); return createIndexVersion(domainId, out.toString(), user); } catch (IOException exception) { LOGGER.error("Error creating info page.", exception); } finally { try { inStream.close(); out.close(); } catch (IOException exception) { LOGGER.error("Error reading wiki_index.xhtml", exception); } } } return null; }
11
Code Sample 1: public void configureKerberos(boolean overwriteExistingSetup) throws Exception { OutputStream keyTabOut = null; InputStream keyTabIn = null; OutputStream krb5ConfOut = null; try { keyTabIn = loadKeyTabResource(keyTabResource); File file = new File(keyTabRepository + keyTabResource); if (!file.exists() || overwriteExistingSetup) { keyTabOut = new FileOutputStream(file, false); if (logger.isDebugEnabled()) logger.debug("Installing keytab file to : " + file.getAbsolutePath()); IOUtils.copy(keyTabIn, keyTabOut); } File krb5ConfFile = new File(System.getProperty("java.security.krb5.conf", defaultKrb5Config)); if (logger.isDebugEnabled()) logger.debug("Using Kerberos config file : " + krb5ConfFile.getAbsolutePath()); if (!krb5ConfFile.exists()) throw new Exception("Kerberos config file not found : " + krb5ConfFile.getAbsolutePath()); FileInputStream fis = new FileInputStream(krb5ConfFile); Wini krb5Conf = new Wini(KerberosConfigUtil.toIni(fis)); Ini.Section krb5Realms = krb5Conf.get("realms"); String windowsDomainSetup = krb5Realms.get(kerberosRealm); if (kerberosRealm == null || overwriteExistingSetup) { windowsDomainSetup = "{ kdc = " + keyDistributionCenter + ":88 admin_server = " + keyDistributionCenter + ":749 default_domain = " + kerberosRealm.toLowerCase() + " }"; krb5Realms.put(kerberosRealm, windowsDomainSetup); } Ini.Section krb5DomainRealms = krb5Conf.get("domain_realm"); String domainRealmSetup = krb5DomainRealms.get(kerberosRealm.toLowerCase()); if (domainRealmSetup == null || overwriteExistingSetup) { krb5DomainRealms.put(kerberosRealm.toLowerCase(), kerberosRealm); krb5DomainRealms.put("." + kerberosRealm.toLowerCase(), kerberosRealm); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); krb5Conf.store(baos); InputStream bios = new ByteArrayInputStream(baos.toByteArray()); bios = KerberosConfigUtil.toKrb5(bios); krb5ConfOut = new FileOutputStream(krb5ConfFile, false); IOUtils.copy(bios, krb5ConfOut); } catch (Exception e) { logger.error("Error while configuring Kerberos :" + e.getMessage(), e); throw e; } finally { IOUtils.closeQuietly(keyTabOut); IOUtils.closeQuietly(keyTabIn); IOUtils.closeQuietly(krb5ConfOut); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
00
Code Sample 1: public 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) { } } } } Code Sample 2: protected URLConnection openConnection(URL url) throws IOException { if (bundleEntry != null) return (new BundleURLConnection(url, bundleEntry)); String bidString = url.getHost(); if (bidString == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_ID, url.toExternalForm())); } AbstractBundle bundle = null; long bundleID; try { bundleID = Long.parseLong(bidString); } catch (NumberFormatException nfe) { throw new MalformedURLException(NLS.bind(AdaptorMsg.URL_INVALID_BUNDLE_ID, bidString)); } bundle = (AbstractBundle) context.getBundle(bundleID); if (!url.getAuthority().equals(SECURITY_AUTHORIZED)) { checkAdminPermission(bundle); } if (bundle == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_FOUND, url.toExternalForm())); } return (new BundleURLConnection(url, findBundleEntry(url, bundle))); }
11
Code Sample 1: public static int copy(File src, int amount, File dst) { final int BUFFER_SIZE = 1024; int amountToRead = amount; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src)); out = new BufferedOutputStream(new FileOutputStream(dst)); byte[] buf = new byte[BUFFER_SIZE]; while (amountToRead > 0) { int read = in.read(buf, 0, Math.min(BUFFER_SIZE, amountToRead)); if (read == -1) break; amountToRead -= read; out.write(buf, 0, read); } } catch (IOException e) { } finally { if (in != null) try { in.close(); } catch (IOException e) { } if (out != null) { try { out.flush(); } catch (IOException e) { } try { out.close(); } catch (IOException e) { } } } return amount - amountToRead; } Code Sample 2: private byte[] digestFile(File file, MessageDigest digest) throws IOException { DigestInputStream in = new DigestInputStream(new FileInputStream(file), digest); IOUtils.copy(in, new NullOutputStream()); in.close(); return in.getMessageDigest().digest(); }
00
Code Sample 1: public boolean open() { try { URL url = new URL(resource); conn = url.openConnection(); in = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (MalformedURLException e) { System.out.println("Uable to connect URL:" + resource); return false; } catch (IOException e) { System.out.println("IOExeption when connecting to URL" + resource); return false; } return true; } Code Sample 2: public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); }
00
Code Sample 1: public <T extends FetionResponse> T executeAction(FetionAction<T> fetionAction) throws IOException { URL url = new URL(fetionAction.getProtocol().name().toLowerCase() + "://" + fetionUrl + fetionAction.getRequestData()); URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); byte[] buffer = new byte[10240]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); int read = 0; while ((read = in.read(buffer)) > 0) { bout.write(buffer, 0, read); } return fetionAction.processResponse(parseRawResponse(bout.toByteArray())); } Code Sample 2: private JButton getButtonImagen() { if (buttonImagen == null) { buttonImagen = new JButton(); buttonImagen.setText(Messages.getString("gui.AdministracionResorces.6")); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetree.png"))); buttonImagen.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonImagen; }
00
Code Sample 1: public List<String> addLine(String username, String URL, int page) { List<String> rss = new ArrayList<String>(); try { URL url = new URL(URL + page); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; System.out.println(reader.readLine()); while ((line = reader.readLine()) != null) { String string = "<text>"; String string1 = "</text>"; if (line.contains(string) && !line.contains("@") && !line.contains("http")) { String tweet = line.replace(string, "").replace(string1, "").replace("'", "").trim(); final Tweets tweets = new Tweets(username, tweet, page, false); int save = tweets.save(); tweets.setId((long) save); Thread thread = new Thread(new Runnable() { @Override public void run() { Main.addRow(tweets); } }); thread.start(); System.out.println(tweet); } } reader.close(); } catch (MalformedURLException e) { Log.put(e.toString()); System.out.println(e.toString()); } catch (IOException e) { Log.put(e.toString()); System.out.println(e.toString()); } catch (Exception e) { Log.put(e.toString()); System.out.println(e.toString()); } return rss; } Code Sample 2: public static String hash(String toEncripty) { if (toEncripty != null) { try { synchronized (toEncripty) { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toEncripty.getBytes()); byte[] hash = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) hexString.append("0" + Integer.toHexString((0xFF & hash[i]))); else hexString.append(Integer.toHexString(0xFF & hash[i])); } toEncripty = hexString.toString(); } } catch (Exception e) { e.getMessage(); } } return toEncripty; }
11
Code Sample 1: public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) return; FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: @Override public void run() { try { File dest = new File(location); if ((dest.getParent() != null && !dest.getParentFile().isDirectory() && !dest.getParentFile().mkdirs())) { throw new IOException("Impossible de créer un dossier (" + dest.getParent() + ")."); } else if (dest.exists() && !dest.delete()) { throw new IOException("Impossible de supprimer un ancien fichier (" + dest + ")."); } else if (!dest.createNewFile()) { throw new IOException("Impossible de créer un fichier (" + dest + ")."); } FileChannel in = new FileInputStream(file).getChannel(); FileChannel out = new FileOutputStream(dest).getChannel(); try { in.transferTo(0, in.size(), out); } finally { in.close(); out.close(); } } catch (Exception e) { Main.fenetre().erreur(Fenetre.ERREUR_FATALE_UPDATE, e); } finally { file.delete(); } }
00
Code Sample 1: private void writeResponse(final Collection<? extends Resource> resources, final HttpServletResponse response) throws IOException { for (final Resource resource : resources) { InputStream in = null; try { in = resource.getInputStream(); final OutputStream out = response.getOutputStream(); final long bytesCopied = IOUtils.copyLarge(in, out); if (bytesCopied < 0L) throw new StreamCorruptedException("Bad number of copied bytes (" + bytesCopied + ") for resource=" + resource.getFilename()); if (logger.isDebugEnabled()) logger.debug("writeResponse(" + resource.getFile() + ") copied " + bytesCopied + " bytes"); } finally { if (in != null) in.close(); } } } Code Sample 2: private void insertService(String table, int type) { Connection con = null; log.info(""); log.info("正在生成" + table + "的服务。。。。。。。"); try { con = DODataSource.getDefaultCon(); con.setAutoCommit(false); Statement stmt = con.createStatement(); Statement stmt2 = con.createStatement(); String serviceUid = UUIDHex.getInstance().generate(); DOBO bo = DOBO.getDOBOByName(StringUtil.getDotName(table)); List props = new ArrayList(); StringBuffer mainSql = null; String name = ""; String l10n = ""; String prefix = StringUtil.getDotName(table); Boolean isNew = null; switch(type) { case 1: name = prefix + ".insert"; l10n = name; props = bo.retrieveProperties(); mainSql = getInsertSql(props, table); isNew = Boolean.TRUE; break; case 2: name = prefix + ".update"; l10n = name; props = bo.retrieveProperties(); mainSql = this.getModiSql(props, table); isNew = Boolean.FALSE; break; case 3: DOBOProperty property = DOBOProperty.getDOBOPropertyByName(bo.getName(), "objuid"); System.out.println("BOBOBO::::::" + bo); System.out.println("Property::::::" + property); if (property == null) { return; } name = prefix + ".delete"; l10n = name; props.add(property); mainSql = new StringBuffer("delete from ").append(table).append(" where objuid = ?"); break; case 4: property = DOBOProperty.getDOBOPropertyByName(bo.getName(), "objuid"); if (property == null) { return; } name = prefix + ".browse"; l10n = name; props.add(property); mainSql = new StringBuffer("select * from ").append(table).append(" where objuid = ?"); break; case 5: name = prefix + ".list"; l10n = name; mainSql = new StringBuffer("select * from ").append(table); } this.setParaLinkBatch(props, stmt2, serviceUid, isNew); StringBuffer aSql = new StringBuffer("insert into DO_Service(objuid,l10n,name,bouid,mainSql) values(").append("'").append(serviceUid).append("','").append(l10n).append("','").append(name).append("','").append(this.getDOBOUid(table)).append("','").append(mainSql).append("')"); log.info("Servcice's Sql:" + aSql.toString()); stmt.executeUpdate(aSql.toString()); stmt2.executeBatch(); con.commit(); } catch (SQLException ex) { try { con.rollback(); } catch (SQLException ex2) { ex2.printStackTrace(); } ex.printStackTrace(); } finally { try { if (!con.isClosed()) { con.close(); } } catch (SQLException ex1) { ex1.printStackTrace(); } } }
11
Code Sample 1: public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); } Code Sample 2: private String getManifestVersion() { URL url = AceTree.class.getResource("/org/rhwlab/help/messages/manifest.html"); InputStream istream = null; String s = ""; try { istream = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(istream)); while (br.ready()) { s = br.readLine(); if (s.indexOf("Manifest-Version:") == 0) { s = s.substring(17); break; } System.out.println("read: " + s); } br.close(); } catch (Exception e) { e.printStackTrace(); } return "Version: " + s + C.NL; }
11
Code Sample 1: private void copyFileToDir(MyFile file, MyFile to, wlPanel panel) throws IOException { Utilities.print("started copying " + file.getAbsolutePath() + "\n"); FileOutputStream fos = new FileOutputStream(new File(to.getAbsolutePath())); FileChannel foc = fos.getChannel(); FileInputStream fis = new FileInputStream(new File(file.getAbsolutePath())); FileChannel fic = fis.getChannel(); Date d1 = new Date(); long amount = foc.transferFrom(fic, rest, fic.size() - rest); fic.close(); foc.force(false); foc.close(); Date d2 = new Date(); long time = d2.getTime() - d1.getTime(); double secs = time / 1000.0; double rate = amount / secs; frame.getStatusArea().append(secs + "s " + "amount: " + Utilities.humanReadable(amount) + " rate: " + Utilities.humanReadable(rate) + "/s\n", "black"); panel.updateView(); } Code Sample 2: @Test public void testTrainingQuickprop() throws IOException { File temp = File.createTempFile("fannj_", ".tmp"); temp.deleteOnExit(); IOUtils.copy(this.getClass().getResourceAsStream("xor.data"), new FileOutputStream(temp)); List<Layer> layers = new ArrayList<Layer>(); layers.add(Layer.create(2)); layers.add(Layer.create(3, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); layers.add(Layer.create(1, ActivationFunction.FANN_SIGMOID_SYMMETRIC)); Fann fann = new Fann(layers); Trainer trainer = new Trainer(fann); trainer.setTrainingAlgorithm(TrainingAlgorithm.FANN_TRAIN_QUICKPROP); float desiredError = .001f; float mse = trainer.train(temp.getPath(), 500000, 1000, desiredError); assertTrue("" + mse, mse <= desiredError); }
00
Code Sample 1: public void setUp() { try { String excelFile = "result" + java.io.File.separator + "input" + java.io.File.separator + "conextech.xls"; java.io.File f1 = new java.io.File(excelFile); URL url = new URL("file:test/result/input/checksun.xls"); InputStream is = url.openStream(); workbook = Workbook.getWorkbook(is); } catch (MalformedURLException urlEx) { urlEx.printStackTrace(); fail(); } catch (IOException ioEx) { ioEx.printStackTrace(); fail(); } catch (BiffException biffEx) { biffEx.printStackTrace(); fail(); } } Code Sample 2: protected void copyFile(File from, File to) throws IOException { to.getParentFile().mkdirs(); InputStream in = new FileInputStream(from); try { OutputStream out = new FileOutputStream(to); try { byte[] buf = new byte[1024]; int readLength; while ((readLength = in.read(buf)) > 0) { out.write(buf, 0, readLength); } } finally { out.close(); } } finally { in.close(); } }
00
Code Sample 1: public void loadProperties() throws IOException { File file = new File(filename); URL url = file.toURI().toURL(); Properties temp = new Properties(); temp.load(url.openStream()); Point2d start = new Point2d(); Point2d end = new Point2d(); if (temp.getProperty("StartX") != null) try { start.x = Double.valueOf(temp.getProperty("StartX")); } catch (Exception e) { System.out.println("Error loading StartX - leaving as default: " + e); } if (temp.getProperty("StartY") != null) try { start.y = Double.valueOf(temp.getProperty("StartY")); } catch (Exception e) { System.out.println("Error loading StartY - leaving as default: " + e); } if (temp.getProperty("EndX") != null) try { end.x = Double.valueOf(temp.getProperty("EndX")); } catch (Exception e) { System.out.println("Error loading EndX - leaving as default: " + e); } if (temp.getProperty("EndY") != null) try { end.y = Double.valueOf(temp.getProperty("EndY")); } catch (Exception e) { System.out.println("Error loading EndY - leaving as default: " + e); } initialline = new LineSegment2D(start, end); if (temp.getProperty("ReferenceImage") != null) try { referenceimage = Integer.valueOf(temp.getProperty("ReferenceImage")); } catch (Exception e) { System.out.println("Error loading ReferenceImage - leaving as default: " + e); } } Code Sample 2: public RSClassLoader(Map<String, byte[]> classes, URL source) { try { CodeSource codeSource = new CodeSource(source, (CodeSigner[]) null); domain = new ProtectionDomain(codeSource, getPermissions()); this.classes = classes; String s = getClass().getResource("RSClassLoader.class").toString(); s = s.replace("bot/RSClassLoader.class", "client/RandomAccessFile.class"); URL url = new URL(s); InputStream is = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(5000); is = new BufferedInputStream(url.openStream()); byte[] buff = new byte[1024]; int len = -1; while ((len = is.read(buff)) != -1) bos.write(buff, 0, len); byte[] data = bos.toByteArray(); this.classes.put("org.rsbot.client.RandomAccessFile", data); } catch (IOException e) { e.printStackTrace(); } finally { if (is != null) is.close(); } } catch (final Exception ignored) { } }
11
Code Sample 1: public NamedList<Object> request(final SolrRequest request, ResponseParser processor) throws SolrServerException, IOException { HttpMethod method = null; InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = "/select"; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = _parser; } ModifiableSolrParams wparams = new ModifiableSolrParams(); wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); if (params == null) { params = wparams; } else { params = new DefaultSolrParams(wparams, params); } if (_invariantParams != null) { params = new DefaultSolrParams(_invariantParams, params); } int tries = _maxRetries + 1; try { while (tries-- > 0) { try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = _baseURL + path; boolean isMultipart = (streams != null && streams.size() > 1); if (streams == null || isMultipart) { PostMethod post = new PostMethod(url); post.getParams().setContentCharset("UTF-8"); if (!this.useMultiPartPost && !isMultipart) { post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<Part> parts = new LinkedList<Part>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (this.useMultiPartPost || isMultipart) { parts.add(new StringPart(p, v, "UTF-8")); } else { post.addParameter(p, v); } } } } if (isMultipart) { int i = 0; for (ContentStream content : streams) { final ContentStream c = content; String charSet = null; String transferEncoding = null; parts.add(new PartBase(c.getName(), c.getContentType(), charSet, transferEncoding) { @Override protected long lengthOfData() throws IOException { return c.getSize(); } @Override protected void sendData(OutputStream out) throws IOException { Reader reader = c.getReader(); try { IOUtils.copy(reader, out); } finally { reader.close(); } } }); } } if (parts.size() > 0) { post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), post.getParams())); } method = post; } else { String pstr = ClientUtils.toQueryString(params, false); PostMethod post = new PostMethod(url + pstr); final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setRequestEntity(new RequestEntity() { public long getContentLength() { return -1; } public String getContentType() { return contentStream[0].getContentType(); } public boolean isRepeatable() { return false; } public void writeRequest(OutputStream outputStream) throws IOException { ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream); } }); } else { is = contentStream[0].getStream(); post.setRequestEntity(new InputStreamRequestEntity(is, contentStream[0].getContentType())); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method.releaseConnection(); method = null; if (is != null) { is.close(); } if ((tries < 1)) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } method.setFollowRedirects(_followRedirects); method.addRequestHeader("User-Agent", AGENT); if (_allowCompression) { method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate")); } try { int statusCode = _httpClient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { StringBuilder msg = new StringBuilder(); msg.append(method.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append(method.getStatusText()); msg.append("\n\n"); msg.append("request: " + method.getURI()); throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8")); } String charset = "UTF-8"; if (method instanceof HttpMethodBase) { charset = ((HttpMethodBase) method).getResponseCharSet(); } InputStream respBody = method.getResponseBodyAsStream(); if (_allowCompression) { Header contentEncodingHeader = method.getResponseHeader("Content-Encoding"); if (contentEncodingHeader != null) { String contentEncoding = contentEncodingHeader.getValue(); if (contentEncoding.contains("gzip")) { respBody = new GZIPInputStream(respBody); } else if (contentEncoding.contains("deflate")) { respBody = new InflaterInputStream(respBody); } } else { Header contentTypeHeader = method.getResponseHeader("Content-Type"); if (contentTypeHeader != null) { String contentType = contentTypeHeader.getValue(); if (contentType != null) { if (contentType.startsWith("application/x-gzip-compressed")) { respBody = new GZIPInputStream(respBody); } else if (contentType.startsWith("application/x-deflate")) { respBody = new InflaterInputStream(respBody); } } } } } return processor.processResponse(respBody, charset); } catch (HttpException e) { throw new SolrServerException(e); } catch (IOException e) { throw new SolrServerException(e); } finally { method.releaseConnection(); if (is != null) { is.close(); } } } Code Sample 2: public synchronized void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { CacheEntry entry = null; Tenant tenant = null; if (!tenantInfo.getTenants().isEmpty()) { tenant = tenantInfo.getMatchingTenant(request); if (tenant == null) { tenant = tenantInfo.getTenants().get(0); } entry = tenantToCacheEntry.get(tenant.getName()); } else { entry = cacheEntry; } if (entry == null) { File tempDir = (File) servletContext.getAttribute("javax.servlet.context.tempdir"); tempDir = new File(tempDir, "pustefix-sitemap-cache"); if (!tempDir.exists()) { tempDir.mkdirs(); } entry = new CacheEntry(); entry.file = new File(tempDir, "sitemap" + (tenant == null ? "" : "-" + tenant.getName()) + ".xml"); try { String host = AbstractPustefixRequestHandler.getServerName(request); Document doc = getSearchEngineSitemap(tenant, host); Transformer trf = TransformerFactory.newInstance().newTransformer(); trf.setOutputProperty(OutputKeys.INDENT, "yes"); FileOutputStream out = new FileOutputStream(entry.file); MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException x) { throw new RuntimeException("Can't create message digest", x); } DigestOutputStream digestOutput = new DigestOutputStream(out, digest); trf.transform(new DOMSource(doc), new StreamResult(digestOutput)); digestOutput.close(); byte[] digestBytes = digest.digest(); entry.etag = MD5Utils.byteToHex(digestBytes); } catch (Exception x) { throw new ServletException("Error creating sitemap", x); } } String reqETag = request.getHeader("If-None-Match"); if (reqETag != null) { if (entry.etag.equals(reqETag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } long reqMod = request.getDateHeader("If-Modified-Since"); if (reqMod != -1) { if (entry.file.lastModified() < reqMod + 1000) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.flushBuffer(); return; } } response.setContentType("application/xml"); response.setContentLength((int) entry.file.length()); response.setDateHeader("Last-Modified", entry.file.lastModified()); response.setHeader("ETag", entry.etag); OutputStream out = new BufferedOutputStream(response.getOutputStream()); InputStream in = new FileInputStream(entry.file); int bytes_read; byte[] buffer = new byte[8]; while ((bytes_read = in.read(buffer)) != -1) { out.write(buffer, 0, bytes_read); } out.flush(); in.close(); out.close(); }
00
Code Sample 1: public static String doGetWithBasicAuthentication(URL url, String username, String password, int timeout, Map<String, String> headers) throws Throwable { HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); if (username != null || password != null) { byte[] encodedPassword = (username + ":" + password).getBytes(); BASE64Encoder encoder = new BASE64Encoder(); con.setRequestProperty("Authorization", "Basic " + encoder.encode(encodedPassword)); } if (headers != null) { for (Map.Entry<String, String> header : headers.entrySet()) { con.setRequestProperty(header.getKey(), header.getValue()); } } con.setConnectTimeout(timeout); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuffer response = new StringBuffer(); while ((line = rd.readLine()) != null) { response.append(line); response.append('\n'); } rd.close(); is.close(); con.disconnect(); return response.toString(); } Code Sample 2: private HttpURLConnection sendData(URL url, String user, String password) throws IOException, IllegalArgumentException { String tmpAuthUserName = ""; if (user != null) { tmpAuthUserName = user; } final String anAuthUserName = tmpAuthUserName; String tmpAuthPasswd = ""; if (password != null) { tmpAuthPasswd = password; } final String anAuthPasswd = tmpAuthPasswd; Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(anAuthUserName, anAuthPasswd.toCharArray()); } }); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(1000); conn.connect(); return conn; }
00
Code Sample 1: public void buildCache() { CacheManager.resetCache(); XMLCacheBuilder cacheBuilder = CompositePageUtil.getCacheBuilder(); if (cacheBuilder == null) return; String pathStr = cacheBuilder.getPath(); if (pathStr == null) return; String[] paths = pathStr.split("\n"); for (int i = 0; i < paths.length; i++) { try { String path = paths[i]; URL url = new URL(path); HttpURLConnection huc = (HttpURLConnection) url.openConnection(); huc.setDoInput(true); huc.setDoOutput(true); huc.setUseCaches(false); huc.setRequestProperty("Content-Type", "text/html"); DataOutputStream dos = new DataOutputStream(huc.getOutputStream()); dos.flush(); dos.close(); huc.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: private static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } } Code Sample 2: public static String sendScripts(Session session) { Channel channel = null; String tempDirectory = ""; Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "Start sendScripts."); try { { channel = session.openChannel("exec"); final String command = "mktemp -d /tmp/scipionXXXXXXXX"; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); tempDirectory = result[1]; tempDirectory = tempDirectory.replaceAll("\n", ""); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + tempDirectory); IOUtils.closeQuietly(in); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream rsyncHelperContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_HELPER_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(rsyncHelperContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_HELPER_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } { InputStream askPassContentInput = Thread.currentThread().getContextClassLoader().getResourceAsStream("scripts/" + RSYNC_ASKPASS_SCRIPT); channel = session.openChannel("exec"); final String command = "cat > " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); OutputStream out = channel.getOutputStream(); channel.connect(); IOUtils.copy(askPassContentInput, out); IOUtils.closeQuietly(out); channel.disconnect(); } { channel = session.openChannel("exec"); final String command = "chmod 700 " + tempDirectory + "/" + RSYNC_ASKPASS_SCRIPT; ((ChannelExec) channel).setCommand(command); InputStream in = channel.getInputStream(); channel.connect(); String[] result = inputStreamToString(in, channel); Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "status:" + result[0] + "-command:" + command + "-result:" + result[1]); IOUtils.closeQuietly(in); channel.disconnect(); } } catch (IOException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } catch (JSchException ex) { Logger.getLogger(RsyncHelper.class.getName()).log(Level.SEVERE, null, ex); } Logger.getLogger(RsyncHelper.class.getName()).log(Level.INFO, "End sendScripts."); return tempDirectory; }
00
Code Sample 1: private byte[] getImage(String urlpath) throws Exception { URL url = new URL(urlpath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(6 * 1000); if (conn.getResponseCode() == 200) { InputStream inputStream = conn.getInputStream(); return readStream(inputStream); } return null; } Code Sample 2: public static String md5(String input) { String res = ""; try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(input.getBytes()); byte[] md5 = algorithm.digest(); String tmp = ""; for (int i = 0; i < md5.length; i++) { tmp = (Integer.toHexString(0xFF & md5[i])); if (tmp.length() == 1) res += "0" + tmp; else res += tmp; } } catch (NoSuchAlgorithmException ex) { } return res; }
00
Code Sample 1: public Item findById(String itemId) throws UnsupportedEncodingException, IOException { String sessionId = (String) RuntimeAccess.getInstance().getSession().getAttribute("SESSION_ID"); DefaultHttpClient httpclient = new DefaultHttpClient(); FindItemByIdRequest request = new FindItemByIdRequest(); request.setItemID(itemId); request.setSessionId(sessionId); XStream writer = new XStream(); writer.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); writer.alias("FindItemByIdRequest", FindItemByIdRequest.class); XStream reader = new XStream(); reader.setMode(XStream.XPATH_ABSOLUTE_REFERENCES); reader.alias("FindItemByIdResponse", FindItemByIdResponse.class); String strRequest = URLEncoder.encode(reader.toXML(request), "UTF-8"); HttpGet httpget = new HttpGet(MewitProperties.getMewitUrl() + "/resources/findItemById?REQUEST=" + strRequest); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { String result = URLDecoder.decode(EntityUtils.toString(entity), "UTF-8"); FindItemByIdResponse fibiResponse = (FindItemByIdResponse) reader.fromXML(result); return fibiResponse.getItem(); } return null; } Code Sample 2: @SuppressWarnings("deprecation") public static final ReturnCode runCommand(IOBundle io, String[] args) { if ((args.length < 3) || (args.length > 4)) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 3) && (!args[1].equals("show"))) return ReturnCode.makeReturnCode(ReturnCode.RET_INVALID_NUM_ARGS, "Invalid number of arguments: " + args.length); if ((args.length == 4) && (!(args[2].equals("training") || args[2].equals("log") || args[2].equals("configuration")))) return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Access denied to directory: " + args[2]); if (args[1].equals("open")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); io.println(fileName); io.println(file.length() + " bytes"); while (dis.available() != 0) { io.println(dis.readLine()); } fis.close(); bis.close(); dis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_NOT_FOUND, "File " + fileName + " doesn't exist"); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error reading File " + fileName); } } else if (args[1].equals("save")) { final String fileName = args[2] + "/" + args[3]; String line; try { BufferedWriter out = new BufferedWriter(new FileWriter(fileName)); line = io.readLine(); int count = Integer.parseInt(line.trim()); while (count > 0) { out.write(io.read()); count = count - 1; } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Error writing File " + fileName); } } else if (args[1].equals("delete")) { final String fileName = args[2] + "/" + args[3]; final File file = new File(fileName); if (!file.exists()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such file or directory: " + fileName); if (!file.canWrite()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "File is write-protected: " + fileName); if (file.isDirectory()) { String[] files = file.list(); if (files.length > 0) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Directory is not empty: " + fileName); } if (!file.delete()) return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "Deletion failed: " + fileName); } else if (args[1].equals("show")) { File directory = new File(args[2]); String[] files; if ((!directory.isDirectory()) || (!directory.exists())) { return ReturnCode.makeReturnCode(ReturnCode.RET_IO_ERROR, "No such directory: " + directory); } int count = 0; files = directory.list(); io.println("Files in directory \"" + directory + "\":"); for (int i = 0; i < files.length; i++) { directory = new File(files[i]); if (!directory.isDirectory()) { count++; io.println(" " + files[i]); } } io.println("Total " + count + " files"); } else return ReturnCode.makeReturnCode(ReturnCode.RET_BAD_REQUEST, "Unrecognized command"); return ReturnCode.makeReturnCode(ReturnCode.RET_OK); }
11
Code Sample 1: private static void copyFile(File sourceFile, File targetFile) throws FileSaveException { try { FileInputStream inputStream = new FileInputStream(sourceFile); FileOutputStream outputStream = new FileOutputStream(targetFile); FileChannel readableChannel = inputStream.getChannel(); FileChannel writableChannel = outputStream.getChannel(); writableChannel.truncate(0); writableChannel.transferFrom(readableChannel, 0, readableChannel.size()); inputStream.close(); outputStream.close(); } catch (IOException ioException) { String exceptionMessage = "An error occurred when copying from the file \"" + sourceFile.getAbsolutePath() + "\" to the file \"" + targetFile.getAbsolutePath() + "\"."; throw new FileSaveException(exceptionMessage, ioException); } } Code Sample 2: private static void exportConfigResource(ClassLoader classLoader, String resourceName, String targetFileName) throws Exception { InputStream is = classLoader.getResourceAsStream(resourceName); FileOutputStream fos = new FileOutputStream(targetFileName, false); IOUtils.copy(is, fos); fos.close(); is.close(); }
11
Code Sample 1: public static void kopirujSoubor(File vstup, File vystup) throws IOException { FileChannel sourceChannel = new FileInputStream(vstup).getChannel(); FileChannel destinationChannel = new FileOutputStream(vystup).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: public BufferedWriter createWriter(File outfile, String encoding) throws UnsupportedEncodingException, IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(outfile)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot; ZipInputStream zis = new ZipInputStream(new FileInputStream(infile)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); return new BufferedWriter(new OutputStreamWriter(zos, "UTF-8")); }
00
Code Sample 1: private void copy(URL url, IFile file, IProgressMonitor monitor) throws CoreException, IOException { InputStream input = null; try { input = url.openStream(); if (file.exists()) { file.setContents(input, IResource.FORCE, monitor); } else { file.create(input, IResource.FORCE, monitor); } } finally { if (input != null) { try { input.close(); } catch (IOException ignore) { } } } } Code Sample 2: public String buscaCDA() { Properties prop = new CargaProperties().Carga(); URL url; BufferedReader in; String inputLine; String miLinea = null; try { url = new URL(prop.getProperty("CDA")); in = new BufferedReader(new InputStreamReader(url.openStream())); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("cda-TRUNK-")) { miLinea = inputLine; miLinea = miLinea.substring(miLinea.indexOf("lastSuccessfulBuild/artifact/dist/cda-TRUNK")); miLinea = miLinea.substring(0, miLinea.indexOf("\">")); miLinea = url + miLinea; } } } catch (Throwable t) { } log.debug("Detetectado last build CDA: " + miLinea); return miLinea; }
11
Code Sample 1: public static void main(String[] args) { try { String completePath = null; String predictionFileName = null; if (args.length == 2) { completePath = args[0]; predictionFileName = args[1]; } else { System.out.println("Please provide complete path to training_set parent folder as an argument. EXITING"); System.exit(0); } File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); MoviesAndRatingsPerCustomer = InitializeMovieRatingsForCustomerHashMap(completePath, CustomerLimitsTHash); System.out.println("Populated MoviesAndRatingsPerCustomer hashmap"); File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionFileName); FileChannel out = new FileOutputStream(outfile, true).getChannel(); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "formattedProbeData.txt"); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); int custAndRatingSize = 0; TIntByteHashMap custsandratings = new TIntByteHashMap(); int ignoreProcessedRows = 0; int movieViewershipSize = 0; while (probemappedfile.hasRemaining()) { short testmovie = probemappedfile.getShort(); int testCustomer = probemappedfile.getInt(); if ((CustomersAndRatingsPerMovie != null) && (CustomersAndRatingsPerMovie.containsKey(testmovie))) { } else { CustomersAndRatingsPerMovie = InitializeCustomerRatingsForMovieHashMap(completePath, testmovie); custsandratings = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(testmovie); custAndRatingSize = custsandratings.size(); } TShortByteHashMap testCustMovieAndRatingsMap = (TShortByteHashMap) MoviesAndRatingsPerCustomer.get(testCustomer); short[] testCustMovies = testCustMovieAndRatingsMap.keys(); float finalPrediction = 0; finalPrediction = predictRating(testCustomer, testmovie, custsandratings, custAndRatingSize, testCustMovies, testCustMovieAndRatingsMap); System.out.println("prediction for movie: " + testmovie + " for customer " + testCustomer + " is " + finalPrediction); ByteBuffer buf = ByteBuffer.allocate(11); buf.putShort(testmovie); buf.putInt(testCustomer); buf.putFloat(finalPrediction); buf.flip(); out.write(buf); buf = null; testCustMovieAndRatingsMap = null; testCustMovies = null; } } catch (Exception e) { e.printStackTrace(); } } Code Sample 2: public static void copy(File source, File sink) throws IOException { if (source == null) throw new NullPointerException("Source file must not be null"); if (sink == null) throw new NullPointerException("Target file must not be null"); if (!source.exists()) throw new IOException("Source file " + source.getPath() + " does not exist"); if (!source.isFile()) throw new IOException("Source file " + source.getPath() + " is not a regular file"); if (!source.canRead()) throw new IOException("Source file " + source.getPath() + " can not be read (missing acces right)"); if (!sink.exists()) throw new IOException("Target file " + sink.getPath() + " does not exist"); if (!sink.isFile()) throw new IOException("Target file " + sink.getPath() + " is not a regular file"); if (!sink.canWrite()) throw new IOException("Target file " + sink.getPath() + " is write protected"); InputStream input = null; OutputStream output = null; try { input = new FileInputStream(source); output = new FileOutputStream(sink); byte[] buffer = new byte[1024]; while (input.available() > 0) { int bread = input.read(buffer); if (bread > 0) output.write(buffer, 0, bread); } } finally { if (input != null) try { input.close(); } catch (IOException x) { } if (output != null) try { output.close(); } catch (IOException x) { } } }
00
Code Sample 1: public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; } Code Sample 2: public int print(String type, String url, String attrs) throws PrinterException { try { return print(type, (new URL(url)).openStream(), attrs); } catch (Exception e) { e.printStackTrace(); throw new PrinterException(e); } }
00
Code Sample 1: public void loadLicenceText() { try { URL url = this.getClass().getResource("/licences/" + this.files[this.licence_text_id]); InputStreamReader ins = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(ins); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } this.licence_text = sb.toString(); } catch (Exception ex) { System.out.println("LicenceInfo::error reading. Ex: " + ex); ex.printStackTrace(); } } Code Sample 2: private static Properties load(URL url) { Properties props = new Properties(); try { InputStream is = null; try { is = url.openStream(); props.load(is); } finally { is.close(); } } catch (IOException e) { } return props; }
00
Code Sample 1: public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } } Code Sample 2: public boolean save(Object obj) { boolean bool = false; this.result = null; if (obj == null) return bool; Connection conn = null; try { conn = ConnectUtil.getConnect(); conn.setAutoCommit(false); String sql = SqlUtil.getInsertSql(this.getCls()); PreparedStatement ps = conn.prepareStatement(sql); setPsParams(ps, obj); ps.executeUpdate(); ps.close(); conn.commit(); bool = true; } catch (Exception e) { try { conn.rollback(); } catch (SQLException e1) { } this.result = e.getMessage(); } finally { this.closeConnectWithTransaction(conn); } return bool; }
11
Code Sample 1: public void copieFichier(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } Code Sample 2: public static void copy(FileInputStream source, FileOutputStream target) throws IOException { FileChannel sourceChannel = source.getChannel(); FileChannel targetChannel = target.getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), targetChannel); sourceChannel.close(); targetChannel.close(); }
00
Code Sample 1: boolean getHTML(URL url) { html = ""; int r; BufferedInputStream in = null; BufferedInputStream imgIn = null; boolean retry; Vector imageRd = new Vector(0); do { retry = false; try { in = new BufferedInputStream(url.openStream(), 4096); } catch (IOException ioe) { rbe.stats.error("Unable to open URL.", url.toExternalForm()); ioe.printStackTrace(); retry = true; continue; } try { while ((r = in.read(buffer, 0, buffer.length)) != -1) { if (r > 0) { html = html + new String(buffer, 0, r); } } } catch (IOException ioe) { rbe.stats.error("Unable to read HTML from URL.", url.toExternalForm()); retry = true; continue; } if (retry) { try { if (waitKey) { rbe.getKey(); } else { sleep(1000L); } } catch (InterruptedException inte) { System.out.println("In getHTML, caught interrupted exception!"); return true; } } } while (retry); try { in.close(); } catch (IOException ioe) { rbe.stats.error("Unable to close URL.", url.toExternalForm()); } if (DEBUG > 0) { } if (DEBUG > 10) { System.out.println(html); } int cur = 0; if (!RBE.getImage) return true; findImg(html, url, imgPat, srcPat, quotePat, imageRd); findImg(html, url, inputPat, srcPat, quotePat, imageRd); if (DEBUG > 2) { System.out.println("Found " + imageRd.size() + " images."); } while (imageRd.size() > 0) { int max = imageRd.size(); int min = Math.max(max - rbe.maxImageRd, 0); int i; try { for (i = min; i < max; i++) { ImageReader rd = (ImageReader) imageRd.elementAt(i); if (!rd.readImage()) { if (DEBUG > 2) { System.out.println("Read " + rd.tot + " bytes from " + rd.imgURLStr); } imageRd.removeElementAt(i); i--; max--; } } } catch (InterruptedException inte) { System.out.println("In getHTML, caught interrupted exception!"); return true; } } return true; } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public String[][] getProjectTreeData() { String[][] treeData = null; String filename = dms_home + FS + "temp" + FS + username + "projects.xml"; String urlString = dms_url + "/servlet/com.ufnasoft.dms.server.ServerGetProjects"; try { String urldata = urlString + "?username=" + URLEncoder.encode(username, "UTF-8") + "&key=" + URLEncoder.encode(key, "UTF-8") + "&filename=" + URLEncoder.encode(username, "UTF-8") + "projects.xml"; System.out.println(urldata); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(false); DocumentBuilder parser = factory.newDocumentBuilder(); URL u = new URL(urldata); DataInputStream is = new DataInputStream(u.openStream()); FileOutputStream os = new FileOutputStream(filename); int iBufSize = is.available(); byte inBuf[] = new byte[20000 * 1024]; int iNumRead; while ((iNumRead = is.read(inBuf, 0, iBufSize)) > 0) os.write(inBuf, 0, iNumRead); os.close(); is.close(); File f = new File(filename); InputStream inputstream = new FileInputStream(f); Document document = parser.parse(inputstream); NodeList nodelist = document.getElementsByTagName("j"); int num = nodelist.getLength(); treeData = new String[num][5]; for (int i = 0; i < num; i++) { treeData[i][0] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "i")); treeData[i][1] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "pi")); treeData[i][2] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "p")); treeData[i][3] = ""; treeData[i][4] = new String(DOMUtil.getSimpleElementText((Element) nodelist.item(i), "f")); } } catch (MalformedURLException ex) { System.out.println(ex); } catch (ParserConfigurationException ex) { System.out.println(ex); } catch (NullPointerException e) { } catch (Exception ex) { System.out.println(ex); } return treeData; } 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(); }