label
class label
2 classes
source_code
stringlengths
398
72.9k
00
Code Sample 1: public static Hashtable getNamingHashtable() { Hashtable namingHash = new Hashtable(); URL url = AceTree.class.getResource("/org/rhwlab/snight/namesHash.txt"); InputStream istream = null; try { istream = url.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(istream)); String s; while (br.ready()) { s = br.readLine(); if (s.length() == 0) continue; String[] sa = s.split(","); namingHash.put(sa[0], sa[1]); } br.close(); } catch (Exception e) { e.printStackTrace(); } return namingHash; } Code Sample 2: public XMLResourceBundle() throws MissingResourceException { String systemId = getShortName() + ".xml"; URL url; if ((url = getClass().getResource(systemId)) != null) { InputStream is = null; try { is = url.openStream(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); XMLReader xmlReader = factory.newSAXParser().getXMLReader(); xmlReader.setContentHandler(new MessageContentHandler()); xmlReader.parse(new InputSource(is)); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } catch (SAXException se) { System.err.println(se.getMessage()); se.printStackTrace(); } catch (ParserConfigurationException pce) { System.err.println(pce.getMessage()); pce.printStackTrace(); } finally { try { if (is != null) is.close(); } catch (IOException ioe) { System.err.println(ioe.getMessage()); ioe.printStackTrace(); } } } else { throw new MissingResourceException("Resource file '" + systemId + "' could not be found.", systemId, null); } }
00
Code Sample 1: public ActionForward saveImageMap(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { log.debug("MapAction saveImageMap()"); String imageURL = RequestUtil.getRequest(request, "imgUrl"); DataInputStream di = null; FileOutputStream fo = null; byte[] b = new byte[1]; URL url = new URL(imageURL); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename=" + "map.png"); OutputStream outstream = response.getOutputStream(); byte abyte0[] = new byte[4096]; try { BufferedInputStream instream = new BufferedInputStream(urlConnection.getInputStream()); int i; while ((i = instream.read(abyte0, 0, 4096)) != -1) outstream.write(abyte0, 0, i); instream.close(); } catch (Exception e) { e.printStackTrace(); } return null; } Code Sample 2: private String sha1(String s) { String encrypt = s; try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.update(s.getBytes()); byte[] digest = sha.digest(); final StringBuffer buffer = new StringBuffer(); for (int i = 0; i < digest.length; ++i) { final byte b = digest[i]; final int value = (b & 0x7F) + (b < 0 ? 128 : 0); buffer.append(value < 16 ? "0" : ""); buffer.append(Integer.toHexString(value)); } encrypt = buffer.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return encrypt; }
00
Code Sample 1: public static Bitmap loadBitmap(String token, String id, final String type) { String imageUrl = XMLfunctions.URL; imageUrl = imageUrl.replace("{0}", token); imageUrl = imageUrl.replace("{1}", id); InputStream imageStream = null; try { HttpGet httpRequest = new HttpGet(new URL(imageUrl).toURI()); HttpResponse response = (HttpResponse) new DefaultHttpClient().execute(httpRequest); httpRequest = null; BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); response = null; imageStream = bufHttpEntity.getContent(); bufHttpEntity = null; if (imageStream != null) { final BitmapFactory.Options options = new BitmapFactory.Options(); if (type.equals("image")) { options.inSampleSize = 2; } return BitmapFactory.decodeStream(imageStream, null, options); } else { } } catch (IOException e) { } catch (URISyntaxException e) { } finally { if (imageStream != null) closeStream(imageStream); } return null; } 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 { int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
00
Code Sample 1: private static byte[] finalizeStringHash(String loginHash) throws NoSuchAlgorithmException { MessageDigest md5Hasher; md5Hasher = MessageDigest.getInstance("MD5"); md5Hasher.update(loginHash.getBytes()); md5Hasher.update(LOGIN_FINAL_SALT); return md5Hasher.digest(); } Code Sample 2: private static void identify(ContentNetwork cn, String str) { try { URL url = new URL(str); HttpURLConnection con = (HttpURLConnection) url.openConnection(); UrlUtils.setBrowserHeaders(con, null); String key = "cn." + cn.getID() + ".identify.cookie"; String cookie = COConfigurationManager.getStringParameter(key, null); if (cookie != null) { con.setRequestProperty("Cookie", cookie + ";"); } con.setRequestProperty("Connection", "close"); con.getResponseCode(); cookie = con.getHeaderField("Set-Cookie"); if (cookie != null) { String[] bits = cookie.split(";"); if (bits.length > 0 && bits[0].length() > 0) { COConfigurationManager.setParameter(key, bits[0]); } } } catch (Throwable e) { } }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = 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 = 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(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public static String hashJopl(String password, String algorithm, String prefixKey, boolean useDefaultEncoding) { try { MessageDigest digest = MessageDigest.getInstance(algorithm); if (useDefaultEncoding) { digest.update(password.getBytes()); } else { for (char c : password.toCharArray()) { digest.update((byte) (c >> 8)); digest.update((byte) c); } } byte[] digestedPassword = digest.digest(); BASE64Encoder encoder = new BASE64Encoder(); String encodedDigestedStr = encoder.encode(digestedPassword); return prefixKey + encodedDigestedStr; } catch (NoSuchAlgorithmException ne) { return password; } }
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 DialogSongList(JFrame frame) { super(frame, "Menu_SongList", "songList"); setMinimumSize(new Dimension(400, 200)); JPanel panel, spanel; Container contentPane; (contentPane = getContentPane()).add(songSelector = new SongSelector(configKey, null, true)); songSelector.setSelectionAction(new Runnable() { public void run() { final Item<URL, MidiFileInfo> item = songSelector.getSelectedInfo(); if (item != null) { try { selection = new File(item.getKey().toURI()); author.setEnabled(true); title.setEnabled(true); difficulty.setEnabled(true); save.setEnabled(true); final MidiFileInfo info = item.getValue(); author.setText(info.getAuthor()); title.setText(info.getTitle()); Util.selectKey(difficulty, info.getDifficulty()); return; } catch (Exception e) { } } selection = null; author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); } }); contentPane.add(panel = new JPanel(), BorderLayout.SOUTH); panel.setLayout(new BorderLayout()); JScrollPane scrollPane; panel.add(scrollPane = new JScrollPane(spanel = new JPanel()), BorderLayout.NORTH); scrollPane.setPreferredSize(new Dimension(0, 60)); Util.addLabeledComponent(spanel, "Lbl_Author", author = new JTextField(10)); Util.addLabeledComponent(spanel, "Lbl_Title", title = new JTextField(14)); Util.addLabeledComponent(spanel, "Lbl_Difficulty", difficulty = new JComboBox()); difficulty.addItem(new Item<Byte, String>((byte) -1, "")); for (Map.Entry<Byte, String> entry : SongSelector.DIFFICULTIES.entrySet()) { final String value = entry.getValue(); difficulty.addItem(new Item<Byte, String>(entry.getKey(), Util.getMsg(value, value), value)); } spanel.add(save = new JButton()); Util.updateButtonText(save, "Save"); save.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File selected = MidiSong.setMidiFileInfo(selection, author.getText(), title.getText(), getAsByte(difficulty)); SongSelector.refresh(); try { songSelector.setSelected(selected == null ? null : selected.toURI().toURL()); } catch (MalformedURLException ex) { } } }); author.setEnabled(false); title.setEnabled(false); difficulty.setEnabled(false); save.setEnabled(false); JButton button; panel.add(spanel = new JPanel(), BorderLayout.WEST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Import"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final File inputFile = KeyboardHero.midiFile(); try { if (inputFile == null) return; final File dir = (new File(Util.DATA_FOLDER + MidiSong.MIDI_FILES_DIR)); if (dir.exists()) { if (!dir.isDirectory()) { Util.error(Util.getMsg("Err_MidiFilesDirNotDirectory"), dir.getParent()); return; } } else if (!dir.mkdirs()) { Util.error(Util.getMsg("Err_CouldntMkDir"), dir.getParent()); return; } File outputFile = new File(dir.getPath() + File.separator + inputFile.getName()); if (!outputFile.exists() || KeyboardHero.confirm("Que_FileExistsOverwrite")) { final FileChannel inChannel = new FileInputStream(inputFile).getChannel(); inChannel.transferTo(0, inChannel.size(), new FileOutputStream(outputFile).getChannel()); } } catch (Exception ex) { Util.getMsg(Util.getMsg("Err_CouldntImportSong"), ex.toString()); } SongSelector.refresh(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Delete"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (KeyboardHero.confirm(Util.getMsg("Que_SureToDelete"))) { try { new File(songSelector.getSelectedFile().toURI()).delete(); } catch (Exception ex) { Util.error(Util.getMsg("Err_CouldntDeleteFile"), ex.toString()); } SongSelector.refresh(); } } }); panel.add(spanel = new JPanel(), BorderLayout.CENTER); spanel.setLayout(new FlowLayout()); spanel.add(button = new JButton()); Util.updateButtonText(button, "Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { close(); } }); spanel.add(button = new JButton()); Util.updateButtonText(button, "Play"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Game.newGame(songSelector.getSelectedFile()); close(); } }); panel.add(spanel = new JPanel(), BorderLayout.EAST); spanel.add(button = new JButton()); Util.updateButtonText(button, "Refresh"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { SongSelector.refresh(); } }); getRootPane().setDefaultButton(button); instance = this; }
00
Code Sample 1: public static void copyURLToFile(URL source, File destination) throws IOException { InputStream input = source.openStream(); try { FileOutputStream output = openOutputStream(destination); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(output); } } finally { IOUtils.closeQuietly(input); } } Code Sample 2: @Override protected Integer doInBackground() throws Exception { int numOfRows = 0; combinationMap = new HashMap<AnsweredQuestion, Integer>(); combinationMapReverse = new HashMap<Integer, AnsweredQuestion>(); LinkedHashSet<AnsweredQuestion> answeredQuestionSet = new LinkedHashSet<AnsweredQuestion>(); LinkedHashSet<Integer> studentSet = new LinkedHashSet<Integer>(); final String delimiter = ";"; final String typeToProcess = "F"; String line; String[] chunks = new String[9]; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); numOfRows++; if (chunks[2].equals(typeToProcess)) { answeredQuestionSet.add(new AnsweredQuestion(chunks[4], chunks[5])); studentSet.add(new Integer(chunks[0])); } } in.close(); int i = 0; Integer I; for (AnsweredQuestion pair : answeredQuestionSet) { I = new Integer(i++); combinationMap.put(pair, I); combinationMapReverse.put(I, pair); } matrix = new SparseObjectMatrix2D(answeredQuestionSet.size(), studentSet.size()); int lastStudentNumber = -1; AnsweredQuestion pair; in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-2")); in.readLine(); while ((line = in.readLine()) != null) { chunks = line.split(delimiter); pair = null; if (chunks[2].equals(typeToProcess)) { if (Integer.parseInt(chunks[0]) != lastStudentNumber) { lastStudentNumber++; } pair = new AnsweredQuestion(chunks[4], chunks[5]); if (combinationMap.containsKey(pair)) { matrix.setQuick(combinationMap.get(pair), lastStudentNumber, Boolean.TRUE); } } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } supportVector = new int[combinationMap.size()]; ObjectMatrix1D row = null; for (int i = 0; i < combinationMap.size(); i++) { row = matrix.viewRow(i); int sum = 0; for (int k = 0; k < row.size(); k++) { if (row.getQuick(k) != null && row.getQuick(k).equals(Boolean.TRUE)) { sum++; } } supportVector[i] = sum; } applet.combinationMap = this.combinationMap; applet.combinationMapReverse = this.combinationMapReverse; applet.matrix = this.matrix; applet.supportVector = supportVector; System.out.println("data loaded."); return null; }
00
Code Sample 1: public int read(String name) { status = STATUS_OK; try { name = name.trim(); if (name.indexOf("://") > 0) { URL url = new URL(name); in = new BufferedInputStream(url.openStream()); } else { in = new BufferedInputStream(new FileInputStream(name)); } status = read(in); } catch (IOException e) { status = STATUS_OPEN_ERROR; } return status; } Code Sample 2: public File getAppHome() { if (appHome == null) { if (System.getProperty("app.home") != null) { appHome = new File(System.getProperty("app.home")); } if (appHome == null) { URL url = Main.class.getClassLoader().getResource("com/hs/mail/container/Main.class"); if (url != null) { try { JarURLConnection jarConnection = (JarURLConnection) url.openConnection(); url = jarConnection.getJarFileURL(); URI baseURI = new URI(url.toString()).resolve(".."); appHome = new File(baseURI).getCanonicalFile(); System.setProperty("app.home", appHome.getAbsolutePath()); } catch (Exception ignored) { } } } if (appHome == null) { appHome = new File("../."); System.setProperty("app.home", appHome.getAbsolutePath()); } } return appHome; }
00
Code Sample 1: private void sendToFtp(String outputText) { String uid = this.properties.get(PROPERTY_OUTPUT_FTP_USERNAME); String pwd = this.properties.get(PROPERTY_OUTPUT_FTP_PASSWORD); String address = this.properties.get(PROPERTY_OUTPUT_FTP_ADDRESS); int port = 21; try { port = Integer.valueOf(this.properties.get(PROPERTY_OUTPUT_FTP_PORT)); } catch (Exception ex) { LOG.log(Level.WARNING, "Could not read FTP port from properties. Using port 21"); } String location = this.properties.get(PROPERTY_OUTPUT_FTP_LOCATION); String filename = this.properties.get(PROPERTY_OUTPUT_FTP_FILENAME); LOG.log(Level.INFO, "Uploading text output to {0}:{1}/{2}/{3}", new Object[] { address, port, location, filename }); FTPClient ftpClient = new FTPClient(); try { ftpClient.connect(address, port); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftpClient.disconnect(); LOG.log(Level.SEVERE, "Could not connect to FTP server: {0}", reply); return; } if (!ftpClient.login(uid, pwd)) { LOG.log(Level.SEVERE, "Could not login to FTP server ({0}) with given credentials.", address); return; } ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.enterLocalPassiveMode(); if (ftpClient.storeFile(location + "/" + filename, new ByteArrayInputStream(outputText.getBytes()))) { LOG.log(Level.INFO, "Transfer complete"); } else { LOG.log(Level.WARNING, "Transfer incomplete"); } } catch (SocketException ex) { LOG.log(Level.SEVERE, "Could not transfer file.", ex.getMessage()); LOG.log(Level.FINE, "", ex); } catch (IOException ex) { LOG.log(Level.SEVERE, "Could not transfer file.", ex.getMessage()); LOG.log(Level.FINE, "", ex); } if (ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (IOException ex) { LOG.log(Level.SEVERE, "Could not disconnect from FTP.", ex.getMessage()); LOG.log(Level.FINE, "", ex); } } } Code Sample 2: public static void compress(final File zip, final Map<InputStream, String> entries, final IProgressMonitor monitor) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); try { for (InputStream inputStream : entries.keySet()) { ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(inputStream))); out.putNextEntry(zipEntry); IOUtils.copy(inputStream, out); out.closeEntry(); inputStream.close(); if (monitor != null) monitor.worked(1); } } finally { IOUtils.closeQuietly(out); } }
00
Code Sample 1: @Test public void test00_reinitData() throws Exception { Logs.logMethodName(); init(); Db db = DbConnection.defaultCieDbRW(); try { db.begin(); PreparedStatement pst = db.prepareStatement("TRUNCATE e_module;"); pst.executeUpdate(); pst = db.prepareStatement("TRUNCATE e_application_version;"); pst.executeUpdate(); ModuleHelper.synchronizeDbWithModuleList(db); ModuleHelper.declareNewVersion(db); ModuleHelper.updateModuleVersions(db); esisId = com.entelience.directory.PeopleFactory.lookupUserName(db, "esis"); assertNotNull(esisId); guestId = com.entelience.directory.PeopleFactory.lookupUserName(db, "guest"); assertNotNull(guestId); extenId = com.entelience.directory.PeopleFactory.lookupUserName(db, "exten"); assertNotNull(extenId); db.commit(); } catch (Exception e) { db.rollback(); throw e; } } Code Sample 2: public void run() { URLConnection con = null; try { con = url.openConnection(); if ("HTTPS".equalsIgnoreCase(url.getProtocol())) { HttpsURLConnection scon = (HttpsURLConnection) con; try { scon.setSSLSocketFactory(SSLUtil.getSSLSocketFactory(clientCertAlias)); HostnameVerifier hv = SSLUtil.getHostnameVerifier(hostCertLevel); if (hv != null) { scon.setHostnameVerifier(hv); } } catch (GeneralSecurityException e) { Debug.logError(e, module); } catch (GenericConfigException e) { Debug.logError(e, module); } } } catch (IOException e) { Debug.logError(e, module); } synchronized (URLConnector.this) { if (timedOut && con != null) { close(con); } else { connection = con; URLConnector.this.notify(); } } }
11
Code Sample 1: public void addUser(String name, String unit, String organizeName, int userId, int orgId, String email) { Connection connection = null; PreparedStatement ps = null; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { connection = dbo.getConnection(); ps = connection.prepareStatement(INSERT_USER); ps.setInt(1, AddrslistMainDao.getNewID()); ps.setInt(2, -100); ps.setString(3, name.substring(0, 1)); ps.setString(4, name.substring(1)); ps.setString(5, unit); ps.setString(6, organizeName); ps.setString(7, ""); ps.setString(8, email); ps.setString(9, ""); ps.setString(10, ""); ps.setString(11, ""); ps.setString(12, ""); ps.setString(13, ""); ps.setString(14, ""); ps.setString(15, ""); ps.setString(16, ""); ps.setString(17, ""); ps.setString(18, ""); ps.setInt(19, userId); ps.setInt(20, orgId); ps.executeUpdate(); connection.commit(); } catch (Exception e) { e.printStackTrace(); try { connection.rollback(); } catch (SQLException e1) { } } finally { try { ps.close(); connection.close(); dbo.close(); } catch (Exception e) { } } } Code Sample 2: public static synchronized int registerVote(String IDVotazione, byte[] T1, byte[] sbT2, byte[] envelope, Config config) { if (IDVotazione == null) { LOGGER.error("registerVote::IDV null"); return C_addVote_BOH; } if (T1 == null) { LOGGER.error("registerVote::T1 null"); return C_addVote_BOH; } if (envelope == null) { LOGGER.error("registerVote::envelope null"); return C_addVote_BOH; } LOGGER.info("registering vote started"); Connection conn = null; PreparedStatement stmt = null; boolean autoCommitPresent = true; int ANSWER = C_addVote_BOH; try { ByteArrayInputStream tmpXMLStream = new ByteArrayInputStream(envelope); SAXReader tmpXMLReader = new SAXReader(); Document doc = tmpXMLReader.read(tmpXMLStream); if (LOGGER.isTraceEnabled()) LOGGER.trace(doc.asXML()); String sT1 = new String(Base64.encodeBase64(T1), "utf-8"); String ssbT2 = new String(Base64.encodeBase64(sbT2), "utf-8"); String sEnvelope = new String(Base64.encodeBase64(envelope), "utf-8"); LOGGER.trace("loading jdbc driver ..."); Class.forName("com.mysql.jdbc.Driver"); LOGGER.trace("... loaded"); conn = DriverManager.getConnection(config.getSconn()); autoCommitPresent = conn.getAutoCommit(); conn.setAutoCommit(false); String query = "" + " INSERT INTO votes(IDVotazione, T1, signByT2 , envelope) " + " VALUES (? , ? , ? , ? ) "; stmt = conn.prepareStatement(query); stmt.setString(1, IDVotazione); stmt.setString(2, sT1); stmt.setString(3, ssbT2); stmt.setString(4, sEnvelope); stmt.executeUpdate(); stmt.close(); LOGGER.debug("vote saved for references, now start the parsing"); query = "" + " INSERT INTO risposte (IDVotazione, T1, IDquestion , myrisposta,freetext) " + " VALUES (? , ? , ? , ? ,?) "; stmt = conn.prepareStatement(query); Element question, itemsElem, rispostaElem; List<Element> rispList; String id, rispostaText, risposta, freeText, questionType; Iterator<Element> questionIterator = doc.selectNodes("/poll/manifest/question").iterator(); while (questionIterator.hasNext()) { question = (Element) questionIterator.next(); risposta = freeText = ""; id = question.attributeValue("id"); itemsElem = question.element("items"); questionType = itemsElem == null ? "" : itemsElem.attributeValue("type"); rispostaElem = question.element("myrisposta"); rispostaText = rispostaElem == null ? "" : rispostaElem.getText(); if (rispostaText.equals(Votazione.C_TAG_WHITE_XML)) { risposta = C_TAG_WHITE; } else if (rispostaText.equals(Votazione.C_TAG_NULL_XML)) { risposta = C_TAG_NULL; } else { if (!rispostaText.equals("") && LOGGER.isDebugEnabled()) LOGGER.warn("Risposta text should be empty!: " + rispostaText); risposta = C_TAG_BUG; if (questionType.equals("selection")) { Element rispItem = rispostaElem.element("item"); String tmpRisposta = rispItem.attributeValue("index"); if (tmpRisposta != null) { risposta = tmpRisposta; if (risposta.equals("0")) freeText = rispItem.getText(); } } else if (questionType.equals("borda")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index, tokens; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); tokens = rispItem.attributeValue("tokens"); if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index + ":" + tokens; } } } else if (questionType.equals("ordering")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index, order; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); order = rispItem.attributeValue("order"); if (index == null) { continue; } if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index + ":" + order; } } } else if (questionType.equals("multiple")) { rispList = rispostaElem.elements("item"); if (rispList != null) { risposta = ""; String index; for (Element rispItem : rispList) { index = rispItem.attributeValue("index"); if (index.equals("0")) freeText = rispItem.getText(); if (risposta.length() > 0) risposta += ","; risposta += index; } } } else if (questionType.equals("free")) { freeText = rispostaElem.element("item").getText(); risposta = ""; } } if (LOGGER.isTraceEnabled()) { LOGGER.trace("ID_QUESTION: " + id); LOGGER.trace("question type: " + questionType); LOGGER.trace("risposta: " + risposta); LOGGER.trace("freetext: " + freeText); } if (risposta.equals(C_TAG_BUG)) { LOGGER.error("Invalid answer"); LOGGER.error("T1: " + sT1); LOGGER.error("ID_QUESTION: " + id); LOGGER.error("question type: " + questionType); } stmt.setString(1, IDVotazione); stmt.setString(2, sT1); stmt.setString(3, id); stmt.setString(4, risposta); stmt.setString(5, freeText); stmt.addBatch(); } stmt.executeBatch(); stmt.close(); conn.commit(); ANSWER = C_addVote_OK; LOGGER.info("registering vote end successfully"); } catch (SQLException e) { try { conn.rollback(); } catch (Exception ex) { } if (e.getErrorCode() == 1062) { ANSWER = C_addVote_DUPLICATE; LOGGER.error("error while registering vote (duplication)"); } else { ANSWER = C_addVote_BOH; LOGGER.error("error while registering vote", e); } } catch (UnsupportedEncodingException e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("encoding error", e); ANSWER = C_addVote_BOH; } catch (DocumentException e) { LOGGER.error("DocumentException", e); ANSWER = C_addVote_BOH; } catch (ClassNotFoundException e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("error while registering vote", e); ANSWER = C_addVote_BOH; } catch (Exception e) { try { conn.rollback(); } catch (Exception ex) { } LOGGER.error("Unexpected exception while registering vote", e); ANSWER = C_addVote_BOH; } finally { try { conn.setAutoCommit(autoCommitPresent); conn.close(); } catch (Exception e) { } ; } return ANSWER; }
00
Code Sample 1: public void connect() throws SocketException, IOException { Log.i(TAG, "Test attempt login to " + ftpHostname + " as " + ftpUsername); ftpClient = new FTPClient(); ftpClient.connect(this.ftpHostname, this.ftpPort); ftpClient.login(ftpUsername, ftpPassword); int reply = ftpClient.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { String error = "Login failure (" + reply + ") : " + ftpClient.getReplyString(); Log.e(TAG, error); throw new IOException(error); } } Code Sample 2: @Override public void downloadByUUID(final UUID uuid, final HttpServletRequest request, final HttpServletResponse response) throws IOException { if (!exportsInProgress.containsKey(uuid)) { throw new IllegalStateException("No download with UUID: " + uuid); } final File compressedFile = exportsInProgress.get(uuid).file; logger.debug("File size: " + compressedFile.length()); OutputStream output = null; InputStream fileInputStream = null; try { output = response.getOutputStream(); prepareResponse(request, response, compressedFile); fileInputStream = new FileInputStream(compressedFile); IOUtils.copy(fileInputStream, output); output.flush(); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(output); } }
11
Code Sample 1: static List<String> readZipFilesOftypeToFolder(String zipFileLocation, String outputDir, String fileType) { List<String> list = new ArrayList<String>(); ZipFile zipFile = readZipFile(zipFileLocation); FileOutputStream output = null; InputStream inputStream = null; Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); try { while (entries.hasMoreElements()) { java.util.zip.ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName != null && entryName.toLowerCase().endsWith(fileType)) { inputStream = zipFile.getInputStream(entry); String fileName = outputDir + entryName.substring(entryName.lastIndexOf("/")); File file = new File(fileName); output = new FileOutputStream(file); IOUtils.copy(inputStream, output); list.add(fileName); } } } catch (Exception e) { throw new RuntimeException(e); } finally { try { if (output != null) output.close(); if (inputStream != null) inputStream.close(); if (zipFile != null) zipFile.close(); } catch (IOException e) { throw new RuntimeException(e); } } return list; } Code Sample 2: private void copyFile(File source, File target) throws IOException { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(target).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
00
Code Sample 1: public static void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) destFile.createNewFile(); FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) source.close(); if (destination != null) destination.close(); } } Code Sample 2: protected ResourceManager(URL url, String s) { try { properties.load(url.openStream()); path = s; } catch (Exception e) { throw new Error(e.getMessage() + ": trying to load url \"" + url + "\"", e); } }
11
Code Sample 1: private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir, BackUpInfoFileGroup fileGroup, LinkedList<String> restoreList) { LinkedList<BackUpInfoFile> fileList = fileGroup.getFileList(); if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return; } for (int i = 0; i < fileList.size(); i++) { if (fileList.get(i).getId().equals(entry.getName())) { for (int j = 0; j < restoreList.size(); j++) { if ((fileList.get(i).getName() + "." + fileList.get(i).getType()).equals(restoreList.get(j))) { counter += 1; File outputFile = new File(outputDir, fileList.get(i).getName() + "." + fileList.get(i).getType()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream; BufferedOutputStream outputStream; try { inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); outputStream = new BufferedOutputStream(new FileOutputStream(outputFile)); IOUtils.copy(inputStream, outputStream); outputStream.close(); inputStream.close(); } catch (IOException ex) { throw new BackupException(ex.getMessage()); } } } } } } Code Sample 2: public static void copy(File src, File dest) throws IOException { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel destChannel = new FileOutputStream(dest).getChannel(); destChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); destChannel.close(); }
11
Code Sample 1: private Dataset(File f, Properties p, boolean ro) throws DatabaseException { folder = f; logger.debug("Opening dataset [" + ((ro) ? "readOnly" : "read/write") + " mode]"); readOnly = ro; logger = Logger.getLogger(Dataset.class); logger.debug("Opening environment: " + f); EnvironmentConfig envConfig = new EnvironmentConfig(); envConfig.setTransactional(false); envConfig.setAllowCreate(!readOnly); envConfig.setReadOnly(readOnly); env = new Environment(f, envConfig); File props = new File(folder, "dataset.properties"); if (!ro && p != null) { this.properties = p; try { FileOutputStream fos = new FileOutputStream(props); p.store(fos, null); fos.close(); } catch (IOException e) { logger.warn("Error saving dataset properties", e); } } else { if (props.exists()) { try { Properties pr = new Properties(); FileInputStream fis = new FileInputStream(props); pr.load(fis); fis.close(); this.properties = pr; } catch (IOException e) { logger.warn("Error reading dataset properties", e); } } } getPaths(); getNamespaces(); getTree(); pathDatabases = new HashMap(); frequencyDatabases = new HashMap(); lengthDatabases = new HashMap(); clustersDatabases = new HashMap(); pathMaps = new HashMap(); frequencyMaps = new HashMap(); lengthMaps = new HashMap(); clustersMaps = new HashMap(); } Code Sample 2: protected final void loadLogFile(String filename) throws IOException { cleanUp(true, false); InputStream is = null; OutputStream os = null; File f = File.createTempFile("log", null); try { is = getClass().getResourceAsStream(filename); Assert.isTrue(is != null, "File not found: " + filename); os = new FileOutputStream(f); IOUtils.copy(is, os); setLogFile(f); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } }
11
Code Sample 1: private void buildBundle() { if (targetProject == null) { MessageDialog.openError(getShell(), "Error", "No target SPAB project selected!"); return; } if (projectProcessDirSelector.getText().trim().length() == 0) { MessageDialog.openError(getShell(), "Error", "No process directory selected for project " + targetProject.getName() + "!"); return; } deleteBundleFile(); try { File projectDir = targetProject.getLocation().toFile(); File projectProcessesDir = new File(projectDir, projectProcessDirSelector.getText()); boolean bpmoCopied = IOUtils.copyProcessFilesSecure(getBPMOFile(), projectProcessesDir); boolean sbpelCopied = IOUtils.copyProcessFilesSecure(getSBPELFile(), projectProcessesDir); boolean xmlCopied = IOUtils.copyProcessFilesSecure(getBPEL4SWSFile(), projectProcessesDir); bundleFile = IOUtils.archiveBundle(projectDir, Activator.getDefault().getStateLocation().toFile()); if (bpmoCopied) { new File(projectProcessesDir, getBPMOFile().getName()).delete(); } if (sbpelCopied) { new File(projectProcessesDir, getSBPELFile().getName()).delete(); } if (xmlCopied) { new File(projectProcessesDir, getBPEL4SWSFile().getName()).delete(); } } catch (Throwable anyError) { LogManager.logError(anyError); MessageDialog.openError(getShell(), "Error", "Error building SPAB :\n" + anyError.getMessage()); updateBundleUI(); return; } bpmoFile = getBPMOFile(); sbpelFile = getSBPELFile(); xmlFile = getBPEL4SWSFile(); updateBundleUI(); getWizard().getContainer().updateButtons(); } Code Sample 2: public static long removePropertyInOpenXMLDocument(String ext, InputStream in, OutputStreamProvider outProvider, String propriete) { in = new BufferedInputStream(in); try { File tempPptx = null; POIXMLDocument doc; if (ext.toLowerCase().equals("docx")) { doc = new XWPFDocument(in); } else if (ext.toLowerCase().equals("xlsx")) { doc = new XSSFWorkbook(in); } else if (ext.toLowerCase().equals("pptx")) { tempPptx = File.createTempFile("temp", "pptx"); OutputStream tempPptxOut = new FileOutputStream(tempPptx); tempPptxOut = new BufferedOutputStream(tempPptxOut); IOUtils.copy(in, tempPptxOut); tempPptxOut.close(); doc = new XSLFSlideShow(tempPptx.getAbsolutePath()); } else { throw new IllegalArgumentException("Writing properties for a " + ext + " file is not supported"); } CoreProperties coreProperties = doc.getProperties().getCoreProperties(); if (propriete.equals(Metadata.TITLE)) { coreProperties.setTitle(""); } else if (propriete.equals(Metadata.AUTHOR)) { coreProperties.setCreator(""); } else if (propriete.equals(Metadata.KEYWORDS)) { coreProperties.getUnderlyingProperties().setKeywordsProperty(""); } else if (propriete.equals(Metadata.COMMENTS)) { coreProperties.setDescription(""); } else if (propriete.equals(Metadata.SUBJECT)) { coreProperties.setSubjectProperty(""); } else if (propriete.equals(Metadata.COMPANY)) { doc.getProperties().getExtendedProperties().getUnderlyingProperties().setCompany(""); } else { org.apache.poi.POIXMLProperties.CustomProperties customProperties = doc.getProperties().getCustomProperties(); if (customProperties.contains(propriete)) { int index = 0; for (CTProperty prop : customProperties.getUnderlyingProperties().getPropertyArray()) { if (prop.getName().equals(propriete)) { customProperties.getUnderlyingProperties().removeProperty(index); break; } index++; } } } in.close(); File tempOpenXMLDocumentFile = File.createTempFile("temp", "tmp"); OutputStream tempOpenXMLDocumentOut = new FileOutputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentOut = new BufferedOutputStream(tempOpenXMLDocumentOut); doc.write(tempOpenXMLDocumentOut); tempOpenXMLDocumentOut.close(); long length = tempOpenXMLDocumentFile.length(); InputStream tempOpenXMLDocumentIn = new FileInputStream(tempOpenXMLDocumentFile); tempOpenXMLDocumentIn = new BufferedInputStream(tempOpenXMLDocumentIn); OutputStream out = null; try { out = outProvider.getOutputStream(); out = new BufferedOutputStream(out); IOUtils.copy(tempOpenXMLDocumentIn, out); out.flush(); } finally { IOUtils.closeQuietly(out); } if (!FileUtils.deleteQuietly(tempOpenXMLDocumentFile)) { tempOpenXMLDocumentFile.deleteOnExit(); } if (tempPptx != null && !FileUtils.deleteQuietly(tempPptx)) { tempPptx.deleteOnExit(); } return length; } catch (IOException e) { throw new RuntimeException(e); } catch (InvalidFormatException e) { throw new RuntimeException(e); } catch (OpenXML4JException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } }
00
Code Sample 1: private void copyFile(String sourceFilename, String destDirname) throws BuildException { log("Copying file " + sourceFilename + " to " + destDirname); File destFile = getDestFile(sourceFilename, destDirname); InputStream inStream = null; OutputStream outStream = null; try { inStream = new BufferedInputStream(new FileInputStream(sourceFilename)); outStream = new BufferedOutputStream(new FileOutputStream(destFile)); byte[] buffer = new byte[1024]; int n = 0; while ((n = inStream.read(buffer)) != -1) outStream.write(buffer, 0, n); } catch (Exception e) { throw new BuildException("Failed to copy file \"" + sourceFilename + "\" to directory \"" + destDirname + "\""); } finally { try { if (inStream != null) inStream.close(); } catch (IOException e) { } try { if (outStream != null) outStream.close(); } catch (IOException e) { } } } Code Sample 2: private static List<String> getContent(URL url) throws IOException { final HttpURLConnection http = (HttpURLConnection) url.openConnection(); try { http.connect(); final int code = http.getResponseCode(); if (code != 200) throw new IOException("IP Locator failed to get the location. Http Status code : " + code + " [" + url + "]"); return getContent(http); } finally { http.disconnect(); } }
00
Code Sample 1: private void dealWith(String line) throws Exception { if (line.startsWith("#") || (line.length() == 0)) { return; } String sarr[]; sarr = StringUtil.split(line, '\t'); String path = destDir + File.separator + sarr[0]; boolean copyFile = true; if (sarr.length == 2) { try { String serverHash = sarr[1]; String fileHash = loadFileHash(destDir + File.separator + sarr[0]); if (fileHash != null) { if (serverHash.equalsIgnoreCase(fileHash)) { copyFile = false; } else { if (verbose) { System.out.println(" -- " + sarr[0] + " has changed"); } } } } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); System.exit(2); } } if (copyFile) { int idx = path.lastIndexOf('/'); if (idx > 0) { String dir = path.substring(0, idx); File f = new File(dir); f.mkdirs(); } FileOutputStream os = new FileOutputStream(path); byte buf[] = new byte[1024]; URLConnection urc = new URL(urlStr + "/" + sarr[0]).openConnection(); InputStream is = urc.getInputStream(); boolean done = false; while (!done) { int read = is.read(buf, 0, 1024); if (read == -1) { done = true; } else { os.write(buf, 0, read); } } os.close(); is.close(); if (verbose) { System.out.println(" -- Copied: " + sarr[0]); } } } Code Sample 2: public ActionForward sendTrackback(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws RollerException { ActionForward forward = mapping.findForward("weblogEdit.page"); ActionErrors errors = new ActionErrors(); WeblogEntryData entry = null; try { RollerRequest rreq = RollerRequest.getRollerRequest(request); if (rreq.isUserAuthorizedToEdit()) { WeblogEntryFormEx form = (WeblogEntryFormEx) actionForm; String entryid = form.getId(); if (entryid == null) { entryid = request.getParameter(RollerRequest.WEBLOGENTRYID_KEY); } RollerContext rctx = RollerContext.getRollerContext(request); WeblogManager wmgr = rreq.getRoller().getWeblogManager(); entry = wmgr.retrieveWeblogEntry(entryid); String title = entry.getTitle(); PageHelper pageHelper = PageHelper.createPageHelper(request, response); pageHelper.setSkipFlag(true); String excerpt = pageHelper.renderPlugins(entry); excerpt = StringUtils.left(Utilities.removeHTML(excerpt), 255); String url = rctx.createEntryPermalink(entry, request, true); String blog_name = entry.getWebsite().getName(); if (form.getTrackbackUrl() != null) { try { String data = URLEncoder.encode("title", "UTF-8") + "=" + URLEncoder.encode(title, "UTF-8"); data += ("&" + URLEncoder.encode("excerpt", "UTF-8") + "=" + URLEncoder.encode(excerpt, "UTF-8")); data += ("&" + URLEncoder.encode("url", "UTF-8") + "=" + URLEncoder.encode(url, "UTF-8")); data += ("&" + URLEncoder.encode("blog_name", "UTF-8") + "=" + URLEncoder.encode(blog_name, "UTF-8")); URL tburl = new URL(form.getTrackbackUrl()); URLConnection conn = tburl.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; StringBuffer resultBuff = new StringBuffer(); while ((line = rd.readLine()) != null) { resultBuff.append(Utilities.escapeHTML(line, true)); resultBuff.append("<br />"); } ActionMessages resultMsg = new ActionMessages(); resultMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("weblogEdit.trackbackResults", resultBuff)); saveMessages(request, resultMsg); wr.close(); rd.close(); } catch (IOException e) { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.trackback", e)); } } else { errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.noTrackbackUrlSpecified")); } form.setTrackbackUrl(null); } else { forward = mapping.findForward("access-denied"); } } catch (Exception e) { mLogger.error(e); String msg = e.getMessage(); if (msg == null) { msg = e.getClass().getName(); } errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.general", msg)); } if (!errors.isEmpty()) { saveErrors(request, errors); } request.setAttribute("model", new WeblogEntryPageModel(request, response, mapping, (WeblogEntryFormEx) actionForm, WeblogEntryPageModel.EDIT_MODE)); return forward; }
11
Code Sample 1: public void importarBancoDeDadosDARI(File pArquivoXLS, Andamento pAndamento) throws IOException, SQLException, InvalidFormatException { final String ABA_VALOR_DE_MERCADO = "Valor de Mercado"; final int COLUNA_DATA = 1, COLUNA_ANO = 6, COLUNA_VALOR_DE_MERCADO_DIARIO_EM_BILHOES_DE_REAIS = 2, COLUNA_VALOR_DE_MERCADO_DIARIO_EM_BILHOES_DE_DOLARES = 3, COLUNA_VALOR_DE_MERCADO_ANUAL_EM_BILHOES_DE_REAIS = 7, COLUNA_VALOR_DE_MERCADO_ANUAL_EM_BILHOES_DE_DOLARES = 8; final BigDecimal BILHAO = new BigDecimal("1000000000"); int iLinha = -1; Statement stmtLimpezaInicialDestino = null; OraclePreparedStatement stmtDestino = null; try { Workbook arquivo = WorkbookFactory.create(new FileInputStream(pArquivoXLS)); Sheet planilhaValorDeMercado = arquivo.getSheet(ABA_VALOR_DE_MERCADO); int QUANTIDADE_DE_REGISTROS_DE_METADADOS = 7; final Calendar DATA_INICIAL = Calendar.getInstance(); DATA_INICIAL.setTime(planilhaValorDeMercado.getRow(QUANTIDADE_DE_REGISTROS_DE_METADADOS).getCell(COLUNA_DATA).getDateCellValue()); final int ANO_DA_DATA_INICIAL = DATA_INICIAL.get(Calendar.YEAR); final int ANO_INICIAL = Integer.parseInt(planilhaValorDeMercado.getRow(QUANTIDADE_DE_REGISTROS_DE_METADADOS).getCell(COLUNA_ANO).getStringCellValue()); final int ANO_FINAL = Calendar.getInstance().get(Calendar.YEAR); Row registro; int quantidadeDeRegistrosAnuaisEstimada = (ANO_FINAL - ANO_INICIAL + 1), quantidadeDeRegistrosDiariosEstimada = (planilhaValorDeMercado.getPhysicalNumberOfRows() - QUANTIDADE_DE_REGISTROS_DE_METADADOS); final int quantidadeDeRegistrosEstimada = quantidadeDeRegistrosAnuaisEstimada + quantidadeDeRegistrosDiariosEstimada; int vAno; BigDecimal vValorDeMercadoEmReais, vValorDeMercadoEmDolares; Cell celulaDoAno, celulaDoValorDeMercadoEmReais, celulaDoValorDeMercadoEmDolares; stmtLimpezaInicialDestino = conDestino.createStatement(); String sql = "TRUNCATE TABLE TMP_TB_VALOR_MERCADO_BOLSA"; stmtLimpezaInicialDestino.executeUpdate(sql); sql = "INSERT INTO TMP_TB_VALOR_MERCADO_BOLSA(DATA, VALOR_DE_MERCADO_REAL, VALOR_DE_MERCADO_DOLAR) VALUES(:DATA, :VALOR_DE_MERCADO_REAL, :VALOR_DE_MERCADO_DOLAR)"; stmtDestino = (OraclePreparedStatement) conDestino.prepareStatement(sql); stmtDestino.setExecuteBatch(COMANDOS_POR_LOTE); int quantidadeDeRegistrosImportados = 0; Calendar calendario = Calendar.getInstance(); calendario.clear(); calendario.set(Calendar.MONTH, Calendar.DECEMBER); calendario.set(Calendar.DAY_OF_MONTH, 31); for (iLinha = QUANTIDADE_DE_REGISTROS_DE_METADADOS; true; iLinha++) { registro = planilhaValorDeMercado.getRow(iLinha); celulaDoAno = registro.getCell(COLUNA_ANO); String anoTmp = celulaDoAno.getStringCellValue(); if (anoTmp != null && anoTmp.length() > 0) { vAno = Integer.parseInt(anoTmp); if (vAno < ANO_DA_DATA_INICIAL) { celulaDoValorDeMercadoEmReais = registro.getCell(COLUNA_VALOR_DE_MERCADO_ANUAL_EM_BILHOES_DE_REAIS); celulaDoValorDeMercadoEmDolares = registro.getCell(COLUNA_VALOR_DE_MERCADO_ANUAL_EM_BILHOES_DE_DOLARES); } else { break; } calendario.set(Calendar.YEAR, vAno); java.sql.Date vUltimoDiaDoAno = new java.sql.Date(calendario.getTimeInMillis()); vValorDeMercadoEmReais = new BigDecimal(celulaDoValorDeMercadoEmReais.getNumericCellValue()).multiply(BILHAO).setScale(0, RoundingMode.DOWN); vValorDeMercadoEmDolares = new BigDecimal(celulaDoValorDeMercadoEmDolares.getNumericCellValue()).multiply(BILHAO).setScale(0, RoundingMode.DOWN); stmtDestino.clearParameters(); stmtDestino.setDateAtName("DATA", vUltimoDiaDoAno); stmtDestino.setBigDecimalAtName("VALOR_DE_MERCADO_REAL", vValorDeMercadoEmReais); stmtDestino.setBigDecimalAtName("VALOR_DE_MERCADO_DOLAR", vValorDeMercadoEmDolares); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; } else { break; } double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosEstimada * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } java.util.Date dataAnterior = null; String dataTmp; final DateFormat formatadorDeData_ddMMyyyy = new SimpleDateFormat("dd/MM/yyyy", Constantes.IDIOMA_PORTUGUES_BRASILEIRO); final DateFormat formatadorDeData_ddMMMyyyy = new SimpleDateFormat("dd/MMM/yyyy", Constantes.IDIOMA_PORTUGUES_BRASILEIRO); Cell celulaDaData; for (iLinha = QUANTIDADE_DE_REGISTROS_DE_METADADOS; true; iLinha++) { registro = planilhaValorDeMercado.getRow(iLinha); if (registro != null) { celulaDaData = registro.getCell(COLUNA_DATA); java.util.Date data; if (celulaDaData.getCellType() == Cell.CELL_TYPE_NUMERIC) { data = celulaDaData.getDateCellValue(); } else { dataTmp = celulaDaData.getStringCellValue(); try { data = formatadorDeData_ddMMyyyy.parse(dataTmp); } catch (ParseException ex) { data = formatadorDeData_ddMMMyyyy.parse(dataTmp); } } if (dataAnterior == null || data.after(dataAnterior)) { celulaDoValorDeMercadoEmReais = registro.getCell(COLUNA_VALOR_DE_MERCADO_DIARIO_EM_BILHOES_DE_REAIS); celulaDoValorDeMercadoEmDolares = registro.getCell(COLUNA_VALOR_DE_MERCADO_DIARIO_EM_BILHOES_DE_DOLARES); java.sql.Date vData = new java.sql.Date(data.getTime()); vValorDeMercadoEmReais = new BigDecimal(celulaDoValorDeMercadoEmReais.getNumericCellValue()).multiply(BILHAO).setScale(0, RoundingMode.DOWN); vValorDeMercadoEmDolares = new BigDecimal(celulaDoValorDeMercadoEmDolares.getNumericCellValue()).multiply(BILHAO).setScale(0, RoundingMode.DOWN); stmtDestino.clearParameters(); stmtDestino.setDateAtName("DATA", vData); stmtDestino.setBigDecimalAtName("VALOR_DE_MERCADO_REAL", vValorDeMercadoEmReais); stmtDestino.setBigDecimalAtName("VALOR_DE_MERCADO_DOLAR", vValorDeMercadoEmDolares); int contagemDasInsercoes = stmtDestino.executeUpdate(); quantidadeDeRegistrosImportados++; double percentualCompleto = (double) quantidadeDeRegistrosImportados / quantidadeDeRegistrosEstimada * 100; pAndamento.setPercentualCompleto((int) percentualCompleto); } dataAnterior = data; } else { break; } } conDestino.commit(); } catch (Exception ex) { conDestino.rollback(); ProblemaNaImportacaoDeArquivo problemaDetalhado = new ProblemaNaImportacaoDeArquivo(); problemaDetalhado.nomeDoArquivo = pArquivoXLS.getName(); problemaDetalhado.linhaProblematicaDoArquivo = iLinha; problemaDetalhado.detalhesSobreOProblema = ex; throw problemaDetalhado; } finally { pAndamento.setPercentualCompleto(100); if (stmtLimpezaInicialDestino != null && (!stmtLimpezaInicialDestino.isClosed())) { stmtLimpezaInicialDestino.close(); } if (stmtDestino != null && (!stmtDestino.isClosed())) { stmtDestino.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(); } } }
00
Code Sample 1: public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; } Code Sample 2: public static void streamCopyFile(File srcFile, File destFile) { try { FileInputStream fi = new FileInputStream(srcFile); FileOutputStream fo = new FileOutputStream(destFile); byte[] buf = new byte[1024]; int readLength = 0; while (readLength != -1) { readLength = fi.read(buf); if (readLength != -1) { fo.write(buf, 0, readLength); } } fo.close(); fi.close(); } catch (Exception e) { } }
00
Code Sample 1: public static byte[] wrapBMP(Image image) throws IOException { if (image.getOriginalType() != Image.ORIGINAL_BMP) throw new IOException("Only BMP can be wrapped in WMF."); InputStream imgIn; byte data[] = null; if (image.getOriginalData() == null) { imgIn = image.url().openStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int b = 0; while ((b = imgIn.read()) != -1) out.write(b); imgIn.close(); data = out.toByteArray(); } else data = image.getOriginalData(); int sizeBmpWords = (data.length - 14 + 1) >>> 1; ByteArrayOutputStream os = new ByteArrayOutputStream(); writeWord(os, 1); writeWord(os, 9); writeWord(os, 0x0300); writeDWord(os, 9 + 4 + 5 + 5 + (13 + sizeBmpWords) + 3); writeWord(os, 1); writeDWord(os, 14 + sizeBmpWords); writeWord(os, 0); writeDWord(os, 4); writeWord(os, META_SETMAPMODE); writeWord(os, 8); writeDWord(os, 5); writeWord(os, META_SETWINDOWORG); writeWord(os, 0); writeWord(os, 0); writeDWord(os, 5); writeWord(os, META_SETWINDOWEXT); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeDWord(os, 13 + sizeBmpWords); writeWord(os, META_DIBSTRETCHBLT); writeDWord(os, 0x00cc0020); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); writeWord(os, (int) image.height()); writeWord(os, (int) image.width()); writeWord(os, 0); writeWord(os, 0); os.write(data, 14, data.length - 14); if ((data.length & 1) == 1) os.write(0); writeDWord(os, 3); writeWord(os, 0); os.close(); return os.toByteArray(); } Code Sample 2: public void deleteRole(AuthSession authSession, RoleBean roleBean) { DatabaseAdapter dbDyn = null; PreparedStatement ps = null; try { dbDyn = DatabaseAdapter.getInstance(); if (roleBean.getRoleId() == null) throw new IllegalArgumentException("role id is null"); String sql = "delete from WM_AUTH_ACCESS_GROUP where ID_ACCESS_GROUP=? "; ps = dbDyn.prepareStatement(sql); RsetTools.setLong(ps, 1, roleBean.getRoleId()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of deleted records - " + i1); dbDyn.commit(); } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error delete role"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
00
Code Sample 1: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.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 boolean postLogin() { URL url = null; URLConnection urlConn = null; OutputStream out = null; int code = 0; boolean gotPhpsessid = false; try { url = new URL("http://" + m_host + "/forums/index.php?action=login2"); } catch (MalformedURLException e) { e.printStackTrace(); return false; } try { urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("POST"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); out = urlConn.getOutputStream(); out.write(new String("user=" + m_username + "&passwrd=" + m_password + "&cookielength=60").getBytes()); out.flush(); out.close(); do { readCookies(urlConn); m_referer = url.toString(); code = ((HttpURLConnection) urlConn).getResponseCode(); if (code == 301 || code == 302) { url = new URL(urlConn.getHeaderField("Location")); urlConn = url.openConnection(); ((HttpURLConnection) urlConn).setRequestMethod("GET"); ((HttpURLConnection) urlConn).setInstanceFollowRedirects(false); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setRequestProperty("Host", m_host); urlConn.setRequestProperty("Accept", "*/*"); urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConn.setRequestProperty("Connection", "Keep-Alive"); urlConn.setRequestProperty("Cache-Control", "no-cache"); if (m_referer != null) urlConn.setRequestProperty("Referer", m_referer); if (m_cookies != null) urlConn.setRequestProperty("Cookie", m_cookies); continue; } if (code == 200) { String refreshHdr = urlConn.getHeaderField("Refresh"); Pattern p_phpsessid = Pattern.compile(".*?\\?PHPSESSID=(\\w+).*"); Matcher match_phpsessid = p_phpsessid.matcher(refreshHdr); if (match_phpsessid.matches()) { gotPhpsessid = true; } urlConn = null; continue; } String msg = ((HttpURLConnection) urlConn).getResponseMessage(); m_turnSummaryRef = String.valueOf(code) + ": " + msg; return false; } while (urlConn != null); } catch (Exception e) { e.printStackTrace(); return false; } if (!gotPhpsessid) { m_turnSummaryRef = "Error: PHPSESSID not found after login. "; return false; } if (m_cookies == null) { m_turnSummaryRef = "Error: cookies not found after login. "; return false; } try { Thread.sleep(m_loginDelayInSeconds * 1000); } catch (InterruptedException ie) { ie.printStackTrace(); } return true; }
11
Code Sample 1: public void newGuidSeed(boolean secure) { SecureRandom sr = new SecureRandom(); long secureInitializer = sr.nextLong(); Random rand = new Random(secureInitializer); String host_ip = ""; try { host_ip = InetAddress.getLocalHost().toString(); } catch (UnknownHostException err) { err.printStackTrace(); } MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException err) { err.printStackTrace(); } try { long time = System.currentTimeMillis(); long randNumber = 0; if (secure) { randNumber = sr.nextLong(); } else { randNumber = rand.nextLong(); } sbBeforeMd5.append(host_ip); sbBeforeMd5.append(":"); sbBeforeMd5.append(Long.toString(time)); sbBeforeMd5.append(":"); sbBeforeMd5.append(Long.toString(randNumber)); seed = sbBeforeMd5.toString(); md5.update(seed.getBytes()); byte[] array = md5.digest(); StringBuffer temp_sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { int b = array[i] & 0xFF; if (b < 0x10) temp_sb.append('0'); temp_sb.append(Integer.toHexString(b)); } rawGUID = temp_sb.toString(); } catch (Exception err) { err.printStackTrace(); } } Code Sample 2: private String getHash(String string) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md5.reset(); md5.update(string.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < result.length; i++) { hexString.append(Integer.toHexString(0xFF & result[i])); } String str = hexString.toString(); return str; }
11
Code Sample 1: private static boolean computeCustomerAverages(String completePath, String CustomerAveragesOutputFileName, String CustIndexFileName) { try { File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); TIntObjectHashMap CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int startIndex, endIndex; TIntArrayList a; 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"); File outFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustomerAveragesOutputFileName); FileChannel outC = new FileOutputStream(outFile, true).getChannel(); int totalCusts = CustomerLimitsTHash.size(); File movieMMAPDATAFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "MovieRatingBinaryFile.txt"); inC = new FileInputStream(movieMMAPDATAFile).getChannel(); int[] itr = CustomerLimitsTHash.keys(); startIndex = 0; endIndex = 0; a = null; ByteBuffer buf; for (int i = 0; i < totalCusts; i++) { int currentCust = itr[i]; a = (TIntArrayList) CustomerLimitsTHash.get(currentCust); startIndex = a.get(0); endIndex = a.get(1); if (endIndex > startIndex) { buf = ByteBuffer.allocate((endIndex - startIndex + 1) * 3); inC.read(buf, (startIndex - 1) * 3); } else { buf = ByteBuffer.allocate(3); inC.read(buf, (startIndex - 1) * 3); } buf.flip(); int bufsize = buf.capacity() / 3; float sum = 0; for (int q = 0; q < bufsize; q++) { buf.getShort(); sum += buf.get(); } ByteBuffer outbuf = ByteBuffer.allocate(8); outbuf.putInt(currentCust); outbuf.putFloat(sum / bufsize); outbuf.flip(); outC.write(outbuf); buf.clear(); buf = null; a.clear(); a = null; } inC.close(); outC.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } Code Sample 2: public static void encryptFile(String input, String output, String pwd) throws Exception { CipherOutputStream out; InputStream in; Cipher cipher; SecretKey key; byte[] byteBuffer; cipher = Cipher.getInstance("DES"); key = new SecretKeySpec(pwd.getBytes(), "DES"); cipher.init(Cipher.ENCRYPT_MODE, key); in = new FileInputStream(input); out = new CipherOutputStream(new FileOutputStream(output), cipher); byteBuffer = new byte[1024]; for (int n; (n = in.read(byteBuffer)) != -1; out.write(byteBuffer, 0, n)) ; in.close(); out.close(); }
00
Code Sample 1: public byte[] loadRaw(String ontologyUrl) throws IOException { URL url = new URL(ontologyUrl); InputStream is = url.openStream(); final int BUFFER_SIZE = 1024; byte[] buffer = new byte[BUFFER_SIZE]; ByteArrayOutputStream ontologyBytes = new ByteArrayOutputStream(); for (; ; ) { int bytesRead = is.read(buffer); if (bytesRead <= 0) break; ontologyBytes.write(buffer, 0, bytesRead); } return ontologyBytes.toByteArray(); } Code Sample 2: public static byte[] hash(String plainTextValue) { MessageDigest msgDigest; try { msgDigest = MessageDigest.getInstance("MD5"); msgDigest.update(plainTextValue.getBytes("UTF-8")); byte[] digest = msgDigest.digest(); return digest; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } }
00
Code Sample 1: public static Set<Street> getVias(String pURL) { Set<Street> result = new HashSet<Street>(); String iniCuerr = "<cuerr>"; String finCuerr = "</cuerr>"; String iniDesErr = "<des>"; String finDesErr = "</des>"; String iniVia = "<calle>"; String finVia = "</calle>"; String iniCodVia = "<cv>"; String finCodVia = "</cv>"; String iniTipoVia = "<tv>"; String finTipoVia = "</tv>"; String iniNomVia = "<nv>"; String finNomVia = "</nv>"; boolean error = false; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Street via; while ((str = br.readLine()) != null) { if (str.contains(iniCuerr)) { ini = str.indexOf(iniCuerr) + iniCuerr.length(); fin = str.indexOf(finCuerr); if (Integer.parseInt(str.substring(ini, fin)) > 0) error = true; } if (error) { if (str.contains(iniDesErr)) { ini = str.indexOf(iniDesErr) + iniDesErr.length(); fin = str.indexOf(finDesErr); throw (new Exception(str.substring(ini, fin))); } } else { if (str.contains(iniVia)) { via = new Street(); while ((str = br.readLine()) != null && !str.contains(finVia)) { if (str.contains(iniCodVia)) { ini = str.indexOf(iniCodVia) + iniCodVia.length(); fin = str.indexOf(finCodVia); via.setCodeStreet(Integer.parseInt(str.substring(ini, fin))); } if (str.contains(iniTipoVia)) { TypeStreet tipo = new TypeStreet(); if (!str.contains(finTipoVia)) tipo.setCodetpStreet(""); else { ini = str.indexOf(iniTipoVia) + iniTipoVia.length(); fin = str.indexOf(finTipoVia); tipo.setCodetpStreet(str.substring(ini, fin)); } tipo.setDescription(getDescripcionTipoVia(tipo.getCodetpStreet())); via.setTypeStreet(tipo); } if (str.contains(iniNomVia)) { ini = str.indexOf(iniNomVia) + iniNomVia.length(); fin = str.indexOf(finNomVia); via.setStreetName(str.substring(ini, fin).trim()); } } result.add(via); } } } br.close(); } catch (Exception e) { System.err.println(e); } return result; } Code Sample 2: public RecordIterator(URL fileUrl, ModelDataFile modelDataFile) throws DataFileException { this.modelDataFile = modelDataFile; InputStream urlStream = null; try { urlStream = fileUrl.openStream(); } catch (IOException e) { throw new DataFileException("Error open URL: " + fileUrl.toString(), e); } this.setupStream(urlStream, fileUrl.toString()); }
11
Code Sample 1: private String convert(InputStream input, String encoding) throws Exception { Process p = Runtime.getRuntime().exec("tidy -q -f /dev/null -wrap 0 --output-xml yes --doctype omit --force-output true --new-empty-tags " + emptyTags + " --quote-nbsp no -utf8"); Thread t = new CopyThread(input, p.getOutputStream()); t.start(); ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(p.getInputStream(), output); p.waitFor(); t.join(); return output.toString(); } Code Sample 2: @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, final HttpServletResponse response) throws Exception { final String id = request.getParameter("id"); if (id == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return null; } try { jaxrTemplate.execute(new JAXRCallback<Object>() { public Object execute(Connection connection) throws JAXRException { RegistryObject registryObject = connection.getRegistryService().getBusinessQueryManager().getRegistryObject(id); if (registryObject instanceof ExtrinsicObject) { ExtrinsicObject extrinsicObject = (ExtrinsicObject) registryObject; DataHandler dataHandler = extrinsicObject.getRepositoryItem(); if (dataHandler != null) { response.setContentType("text/html"); try { PrintWriter out = response.getWriter(); InputStream is = dataHandler.getInputStream(); try { final XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(out); xmlStreamWriter.writeStartDocument(); xmlStreamWriter.writeStartElement("div"); xmlStreamWriter.writeStartElement("textarea"); xmlStreamWriter.writeAttribute("name", "repositoryItem"); xmlStreamWriter.writeAttribute("class", "xml"); xmlStreamWriter.writeAttribute("style", "display:none"); IOUtils.copy(new XmlInputStreamReader(is), new XmlStreamTextWriter(xmlStreamWriter)); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeStartElement("script"); xmlStreamWriter.writeAttribute("class", "javascript"); xmlStreamWriter.writeCharacters("dp.SyntaxHighlighter.HighlightAll('repositoryItem');"); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndElement(); xmlStreamWriter.writeEndDocument(); xmlStreamWriter.flush(); } finally { is.close(); } } catch (Throwable ex) { log.error("Error while trying to format repository item " + id, ex); } } else { } } else { } return null; } }); } catch (JAXRException ex) { throw new ServletException(ex); } return null; }
00
Code Sample 1: public static String md5(String s) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(s.getBytes()); byte[] md5sum = digest.digest(); BigInteger bigInt = new BigInteger(1, md5sum); String output = bigInt.toString(16); return prepad(output, 32, '0'); } catch (NoSuchAlgorithmException e) { System.err.println("No MD5 algorithm. we are sunk."); return s; } } Code Sample 2: public void elimina(Pedido pe) throws errorSQL, errorConexionBD { System.out.println("GestorPedido.elimina()"); int id = pe.getId(); String sql; Statement stmt = null; try { gd.begin(); sql = "DELETE FROM pedido WHERE id=" + id; System.out.println("Ejecutando: " + sql); stmt = gd.getConexion().createStatement(); stmt.executeUpdate(sql); System.out.println("executeUpdate"); gd.commit(); System.out.println("commit"); stmt.close(); } catch (SQLException e) { gd.rollback(); throw new errorSQL(e.toString()); } catch (errorConexionBD e) { System.err.println("Error en GestorPedido.elimina(): " + e); } catch (errorSQL e) { System.err.println("Error en GestorPedido.elimina(): " + e); } }
00
Code Sample 1: public static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; md.update(text.getBytes("iso-8859-1"), 0, text.length()); md5hash = md.digest(); return convertToHex(md5hash); } Code Sample 2: public static void bubble_sort(int[] objects, int len) { for (int i = len; --i >= 0; ) { boolean flipped = false; for (int j = 0; j < i; j++) { if (objects[j + 1] < objects[j]) { int tmp = objects[j]; objects[j] = objects[j + 1]; objects[j + 1] = tmp; flipped = true; } } if (!flipped) return; } }
11
Code Sample 1: private void copyFile(File source, File destination) throws IOException { FileInputStream fileInputStream = null; FileOutputStream fileOutputStream = null; try { fileInputStream = new FileInputStream(source); fileOutputStream = new FileOutputStream(destination); int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int readCount = 0; while ((readCount = fileInputStream.read(buffer)) != -1) { fileOutputStream.write(buffer, 0, readCount); } } finally { if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } } Code Sample 2: private String transferWSDL(String wsdlURL, String userPassword) throws WiseConnectionException { String filePath = null; try { URL endpoint = new URL(wsdlURL); HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection(); conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"); conn.setRequestProperty("Connection", "close"); if (userPassword != null) { conn.setRequestProperty("Authorization", "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes())); } InputStream is = null; if (conn.getResponseCode() == 200) { is = conn.getInputStream(); } else { is = conn.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); StringWriter sw = new StringWriter(); char[] buf = new char[200]; int read = 0; while (read != -1) { read = isr.read(buf); sw.write(buf); } throw new WiseConnectionException("Remote server's response is an error: " + sw.toString()); } File file = new File(tmpDeployDir, new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString()); OutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copyStream(fos, is); fos.close(); is.close(); filePath = file.getPath(); } catch (WiseConnectionException wce) { throw wce; } catch (Exception e) { throw new WiseConnectionException("Wsdl download failed!", e); } return filePath; }
11
Code Sample 1: public void copyFile(File a_fileSrc, File a_fileDest, boolean a_append) throws IOException { a_fileDest.getParentFile().mkdirs(); FileInputStream in = null; FileOutputStream out = null; FileChannel fcin = null; FileChannel fcout = null; try { in = new FileInputStream(a_fileSrc); out = new FileOutputStream(a_fileDest, a_append); fcin = in.getChannel(); fcout = out.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(16 * 1024); while (true) { buffer.clear(); int r = fcin.read(buffer); if (r == -1) { break; } buffer.flip(); fcout.write(buffer); } } catch (IOException ex) { throw ex; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } if (fcin != null) { fcin.close(); } if (fcout != null) { fcout.close(); } } } Code Sample 2: public static boolean cpy(File a, File b) { try { FileInputStream astream = null; FileOutputStream bstream = null; try { astream = new FileInputStream(a); bstream = new FileOutputStream(b); long flength = a.length(); int bufsize = (int) Math.min(flength, 1024); byte buf[] = new byte[bufsize]; long n = 0; while (n < flength) { int naread = astream.read(buf); bstream.write(buf, 0, naread); n += naread; } } finally { if (astream != null) astream.close(); if (bstream != null) bstream.close(); } } catch (IOException e) { e.printStackTrace(); return false; } return true; }
11
Code Sample 1: public static void unzip(File sourceZipFile, File unzipDestinationDirectory, FileFilter filter) throws IOException { unzipDestinationDirectory.mkdirs(); if (!unzipDestinationDirectory.exists()) { throw new IOException("Unable to create destination directory: " + unzipDestinationDirectory); } ZipFile zipFile; zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); if (!entry.isDirectory()) { String currentEntry = entry.getName(); File destFile = new File(unzipDestinationDirectory, currentEntry); if (filter == null || filter.accept(destFile)) { File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); FileOutputStream fos = new FileOutputStream(destFile); IOUtils.copyLarge(is, fos); fos.flush(); IOUtils.closeQuietly(fos); } } } zipFile.close(); } Code Sample 2: private void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } }
00
Code Sample 1: private void dealWith(String line) throws Exception { if (line.startsWith("#") || (line.length() == 0)) { return; } String sarr[]; sarr = StringUtil.split(line, '\t'); String path = destDir + File.separator + sarr[0]; boolean copyFile = true; if (sarr.length == 2) { try { String serverHash = sarr[1]; String fileHash = loadFileHash(destDir + File.separator + sarr[0]); if (fileHash != null) { if (serverHash.equalsIgnoreCase(fileHash)) { copyFile = false; } else { if (verbose) { System.out.println(" -- " + sarr[0] + " has changed"); } } } } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); System.exit(2); } } if (copyFile) { int idx = path.lastIndexOf('/'); if (idx > 0) { String dir = path.substring(0, idx); File f = new File(dir); f.mkdirs(); } FileOutputStream os = new FileOutputStream(path); byte buf[] = new byte[1024]; URLConnection urc = new URL(urlStr + "/" + sarr[0]).openConnection(); InputStream is = urc.getInputStream(); boolean done = false; while (!done) { int read = is.read(buf, 0, 1024); if (read == -1) { done = true; } else { os.write(buf, 0, read); } } os.close(); is.close(); if (verbose) { System.out.println(" -- Copied: " + sarr[0]); } } } Code Sample 2: public static void copyFile(File source, File dest) throws IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
11
Code Sample 1: public boolean isPasswordValid(String encPass, String rawPass, Object salt) throws DataAccessException { boolean bMatch = false; try { String strSalt = (String) salt; byte[] baSalt = Hex.decodeHex(strSalt.toCharArray()); MessageDigest md = MessageDigest.getInstance(HASH_ALGORITHM); md.update(rawPass.getBytes(CHAR_ENCODING)); md.update(baSalt); byte[] baCalculatedHash = md.digest(); byte[] baStoredHash = Hex.decodeHex(encPass.toCharArray()); bMatch = MessageDigest.isEqual(baCalculatedHash, baStoredHash); } catch (Exception e) { e.printStackTrace(); } return bMatch; } Code Sample 2: public static String calcCRC(String phrase) { StringBuffer crcCalc = new StringBuffer(); try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(phrase.getBytes()); byte[] tabDigest = md.digest(); for (int i = 0; i < tabDigest.length; i++) { String octet = "0" + Integer.toHexString(tabDigest[i]); crcCalc.append(octet.substring(octet.length() - 2)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return crcCalc.toString(); }
11
Code Sample 1: @Override public void downloadByUUID(final UUID uuid, final HttpServletRequest request, final HttpServletResponse response) throws IOException { if (!exportsInProgress.containsKey(uuid)) { throw new IllegalStateException("No download with UUID: " + uuid); } final File compressedFile = exportsInProgress.get(uuid).file; logger.debug("File size: " + compressedFile.length()); OutputStream output = null; InputStream fileInputStream = null; try { output = response.getOutputStream(); prepareResponse(request, response, compressedFile); fileInputStream = new FileInputStream(compressedFile); IOUtils.copy(fileInputStream, output); output.flush(); } finally { IOUtils.closeQuietly(fileInputStream); IOUtils.closeQuietly(output); } } Code Sample 2: public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
11
Code Sample 1: public static String getMD5(String... list) { if (list.length == 0) return null; MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } md.reset(); for (String in : list) md.update(in.getBytes()); byte[] digest = md.digest(); StringBuilder hexString = new StringBuilder(); for (int i = 0; i < digest.length; ++i) { String hex = Integer.toHexString(0xFF & digest[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } Code Sample 2: public static void processString(String text) throws Exception { MessageDigest md5 = MessageDigest.getInstance(MD5_DIGEST); md5.reset(); md5.update(text.getBytes()); displayResult(null, md5.digest()); }
00
Code Sample 1: public static void main(String[] args) throws NoSuchAlgorithmException { String password = "root"; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(password.getBytes()); final byte[] digest = messageDigest.digest(); final StringBuilder buf = new StringBuilder(digest.length * 2); for (int j = 0; j < digest.length; j++) { buf.append(HEX_DIGITS[(digest[j] >> 4) & 0x0f]); buf.append(HEX_DIGITS[digest[j] & 0x0f]); } String pwd = buf.toString(); System.out.println(pwd); } Code Sample 2: public File extractID3v2TagDataIntoFile(File outputFile) throws TagNotFoundException, IOException { int startByte = (int) ((MP3AudioHeader) audioHeader).getMp3StartByte(); if (startByte >= 0) { FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); ByteBuffer bb = ByteBuffer.allocate(startByte); fc.read(bb); FileOutputStream out = new FileOutputStream(outputFile); out.write(bb.array()); out.close(); fc.close(); fis.close(); return outputFile; } throw new TagNotFoundException("There is no ID3v2Tag data in this file"); }
00
Code Sample 1: public static String md5EncodeString(String s) throws UnsupportedEncodingException, NoSuchAlgorithmException { if (s == null) return null; if (StringUtils.isBlank(s)) return ""; MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(s.getBytes("UTF-8")); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } Code Sample 2: private void _save(ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form) throws Exception { List list = (List) req.getAttribute(WebKeys.LANGUAGE_MANAGER_LIST); for (int i = 0; i < list.size(); i++) { long langId = ((Language) list.get(i)).getId(); try { String filePath = getGlobalVariablesPath() + "cms_language_" + langId + ".properties"; String tmpFilePath = getTemporyDirPath() + "cms_language_" + langId + "_properties.tmp"; File from = new java.io.File(tmpFilePath); from.createNewFile(); File to = new java.io.File(filePath); to.createNewFile(); FileChannel srcChannel = new FileInputStream(from).getChannel(); FileChannel dstChannel = new FileOutputStream(to).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (NonWritableChannelException we) { } catch (IOException e) { Logger.error(this, "Property File save Failed " + e, e); } } SessionMessages.add(req, "message", "message.languagemanager.save"); }
00
Code Sample 1: public void readData(int choice) throws IOException { for (i = 0; i < max; i++) for (j = 0; j < max; j++) { phase_x[i][j] = 0.0; phase_y[i][j] = 0.0; } URL url; InputStream is; InputStreamReader isr; if (choice == 0) { url = getClass().getResource("resources/Phase_623_620_Achromat.dat"); is = url.openStream(); isr = new InputStreamReader(is); } else { url = getClass().getResource("resources/Phase_623_620_NoAchromat.dat"); is = url.openStream(); isr = new InputStreamReader(is); } BufferedReader br = new BufferedReader(isr); s = br.readLine(); StringTokenizer st = new StringTokenizer(s); i = 0; j = 0; phase_x[i][j] = 4 * Double.parseDouble(st.nextToken()); phase_y[i][j] = 4 * Double.parseDouble(st.nextToken()); xgridmin = phase_x[i][j]; ygridmin = phase_y[i][j]; temp_prev = phase_x[i][j]; kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); j++; int k = 0; while ((s = br.readLine()) != null) { st = new StringTokenizer(s); temp_new = 4 * Double.parseDouble(st.nextToken()); if (temp_new != temp_prev) { temp_prev = temp_new; i++; j = 0; } phase_x[i][j] = temp_new; phase_y[i][j] = 4 * Double.parseDouble(st.nextToken()); kd[i][j] = Double.parseDouble(st.nextToken()); kfs[i][j] = Double.parseDouble(st.nextToken()); kfl[i][j] = Double.parseDouble(st.nextToken()); kdee[i][j] = Double.parseDouble(st.nextToken()); kdc[i][j] = Double.parseDouble(st.nextToken()); kfc[i][j] = Double.parseDouble(st.nextToken()); imax = i; jmax = j; j++; k++; } xgridmax = phase_x[i][j - 1]; ygridmax = phase_y[i][j - 1]; } Code Sample 2: public static String md5(String string) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException exception) { LOGGER.warn(exception.getMessage()); } byte[] md5hash = new byte[32]; try { md.update(string.getBytes("iso-8859-1"), 0, string.length()); } catch (UnsupportedEncodingException exception) { LOGGER.warn(exception.getMessage()); } md5hash = md.digest(); return convertToHex(md5hash); }
00
Code Sample 1: public void setTableBraille(String tableBraille, boolean sys) { fiConf.setProperty(OptNames.fi_braille_table, tableBraille); fiConf.setProperty(OptNames.fi_is_sys_braille_table, Boolean.toString(sys)); FileChannel in = null; FileChannel out = null; try { String fichTable; if (!(tableBraille.endsWith(".ent"))) { tableBraille = tableBraille + ".ent"; } if (sys) { fichTable = ConfigNat.getInstallFolder() + "xsl/tablesBraille/" + tableBraille; } else { fichTable = ConfigNat.getUserBrailleTableFolder() + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(getUserBrailleTableFolder() + "Brltab.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } try { String fichTable; if (sys) { fichTable = ConfigNat.getInstallFolder() + "/xsl/tablesEmbosseuse/" + tableBraille; } else { fichTable = ConfigNat.getUserEmbossTableFolder() + "/" + tableBraille; } in = new FileInputStream(fichTable).getChannel(); out = new FileOutputStream(ConfigNat.getUserTempFolder() + "Table_pour_chaines.ent").getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public synchronized String encrypt(final String pPassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { final MessageDigest md = MessageDigest.getInstance("SHA"); md.update(pPassword.getBytes("UTF-8")); final byte raw[] = md.digest(); return BASE64Encoder.encodeBuffer(raw); }
00
Code Sample 1: public static int unzipFile(File file_input, File dir_output) { ZipInputStream zip_in_stream; try { FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in); zip_in_stream = new ZipInputStream(source); } catch (IOException e) { return STATUS_IN_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; do { try { ZipEntry zip_entry = zip_in_stream.getNextEntry(); if (zip_entry == null) break; File output_file = new File(dir_output, zip_entry.getName()); FileOutputStream out = new FileOutputStream(output_file); BufferedOutputStream destination = new BufferedOutputStream(out, BUF_SIZE); while ((len = zip_in_stream.read(input_buffer, 0, BUF_SIZE)) != -1) destination.write(input_buffer, 0, len); destination.flush(); out.close(); } catch (IOException e) { return STATUS_GUNZIP_FAIL; } } while (true); try { zip_in_stream.close(); } catch (IOException e) { } return STATUS_OK; } Code Sample 2: @Override public boolean checkConnection() { int status = 0; try { URL url = new URL(TupeloProxy.endpoint); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); status = conn.getResponseCode(); } catch (Exception e) { logger.severe("Connection test failed with code:" + status); e.printStackTrace(); } if (status < 200 || status >= 400) return false; String url = this.url + "?title=Special:UserLogin&action=submitlogin&type=login&returnto=Main_Page&wpDomain=" + domain + "&wpLoginattempt=Log%20in&wpName=" + username + "&wpPassword=" + password; return true; }
11
Code Sample 1: public void notifyTerminated(Writer r) { all_writers.remove(r); if (all_writers.isEmpty()) { all_terminated = true; Iterator iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); do { try { fc.stream.flush(); fc.stream.close(); } catch (IOException e) { } fc = fc.next; } while (fc != null); } iterator = open_files.iterator(); boolean all_ok = true; while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); logger.logComment("File chunk <" + fc.name + "> " + fc.start_byte + " " + fc.position + " " + fc.actual_file); boolean ok = true; while (fc.next != null) { ok = ok && (fc.start_byte + fc.actual_file.length()) == fc.next.start_byte; fc = fc.next; } if (ok) { logger.logComment("Received file <" + fc.name + "> is contiguous (and hopefully complete)"); } else { logger.logError("Received file <" + fc.name + "> is NOT contiguous"); all_ok = false; } } if (all_ok) { byte[] buffer = new byte[16384]; iterator = open_files.iterator(); while (iterator.hasNext()) { FileWriter.FileChunk fc = (FileWriter.FileChunk) iterator.next(); try { if (fc.next != null) { FileOutputStream fos = new FileOutputStream(fc.actual_file, true); fc = fc.next; while (fc != null) { FileInputStream fis = new FileInputStream(fc.actual_file); int actually_read = fis.read(buffer); while (actually_read != -1) { fos.write(buffer, 0, actually_read); actually_read = fis.read(buffer); } fc.actual_file.delete(); fc = fc.next; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } fte.allWritersTerminated(); fte = null; } } Code Sample 2: private static FileEntry writeEntry(Zip64File zip64File, FileEntry targetPath, File toWrite, boolean compress) { InputStream in = null; EntryOutputStream out = null; processAndCreateFolderEntries(zip64File, parseTargetPath(targetPath.getName(), toWrite), compress); try { if (!compress) { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_STORED, getFileDate(toWrite)); } else { out = zip64File.openEntryOutputStream(targetPath.getName(), FileEntry.iMETHOD_DEFLATED, getFileDate(toWrite)); } if (!targetPath.isDirectory()) { in = new FileInputStream(toWrite); IOUtils.copyLarge(in, out); in.close(); } out.flush(); out.close(); if (targetPath.isDirectory()) { log.info("[createZip] Written folder entry to zip: " + targetPath.getName()); } else { log.info("[createZip] Written file entry to zip: " + targetPath.getName()); } } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (ZipException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return targetPath; }
00
Code Sample 1: public static java.io.ByteArrayOutputStream getFileByteStream(URL _url) { java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream(); try { InputStream input = _url.openStream(); IOUtils.copy(input, buffer); IOUtils.closeQuietly(input); } catch (Exception err) { throw new RuntimeException(err); } return buffer; } Code Sample 2: public Long processAddHolding(Holding holdingBean, AuthSession authSession) { if (authSession == null) { return null; } PreparedStatement ps = null; DatabaseAdapter dbDyn = null; try { dbDyn = DatabaseAdapter.getInstance(); CustomSequenceType seq = new CustomSequenceType(); seq.setSequenceName("seq_WM_LIST_HOLDING"); seq.setTableName("WM_LIST_HOLDING"); seq.setColumnName("ID_HOLDING"); Long sequenceValue = dbDyn.getSequenceNextValue(seq); ps = dbDyn.prepareStatement("insert into WM_LIST_HOLDING " + "( ID_HOLDING, full_name_HOLDING, NAME_HOLDING )" + "values " + (dbDyn.getIsNeedUpdateBracket() ? "(" : "") + " ?, ?, ? " + (dbDyn.getIsNeedUpdateBracket() ? ")" : "")); int num = 1; RsetTools.setLong(ps, num++, sequenceValue); ps.setString(num++, holdingBean.getName()); ps.setString(num++, holdingBean.getShortName()); int i1 = ps.executeUpdate(); if (log.isDebugEnabled()) log.debug("Count of inserted records - " + i1); HoldingBean bean = new HoldingBean(holdingBean); bean.setId(sequenceValue); processInsertRelatedCompany(dbDyn, bean, authSession); dbDyn.commit(); return sequenceValue; } catch (Exception e) { try { if (dbDyn != null) dbDyn.rollback(); } catch (Exception e001) { } String es = "Error add new holding"; log.error(es, e); throw new IllegalStateException(es, e); } finally { DatabaseManager.close(dbDyn, ps); dbDyn = null; ps = null; } }
11
Code Sample 1: public static Map<String, File> extractFiles(String input, File tempDirectory) throws IOException { byte data[] = new byte[BUFFER]; BufferedOutputStream out = null; FileInputStream src = new FileInputStream(input); BufferedInputStream in = new BufferedInputStream(src); ZipInputStream zipin = new ZipInputStream(in); Map<String, File> files = new HashMap<String, File>(); ZipEntry entry; while ((entry = zipin.getNextEntry()) != null) { logger.info(TAG + ": entr�e " + entry.getName() + " r�pertoire ? " + entry.isDirectory()); if (entry.isDirectory()) { logger.info(TAG + ": Ajout de l'entr�e pour le r�pertoire: " + entry.getName()); files.put(entry.getName(), extractDirectory(entry.getName(), zipin, tempDirectory)); File f = files.get(entry.getName()); if (f == null) logger.info(TAG + ": NULLL: "); continue; } File tempFile = new File(tempDirectory, entry.getName()); if (tempFile.exists()) tempFile.delete(); tempFile.createNewFile(); FileOutputStream dest = new FileOutputStream(tempFile); out = new BufferedOutputStream(dest, BUFFER); int count; for (int c = zipin.read(); c != -1; c = zipin.read()) dest.write(c); logger.info(TAG + ": Ajout de l'entr�e: " + entry.getName() + " du fichier: " + tempFile.getAbsolutePath()); files.put(entry.getName(), tempFile); out.close(); dest.close(); } zipin.close(); in.close(); src.close(); return files; } Code Sample 2: public static boolean copyFile(File from, File tu) { final int BUFFER_SIZE = 4096; byte[] buffer = new byte[BUFFER_SIZE]; try { FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(tu); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } in.close(); out.close(); } catch (IOException e) { return false; } return true; }
00
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: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } }
00
Code Sample 1: public void copy(String fromFileName, String toFileName) throws IOException { log.info("copy() file:" + fromFileName + " toFile:" + toFileName); File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { log.error(e.getMessage()); } if (to != null) try { to.close(); } catch (IOException e) { log.error(e.getMessage()); } } } Code Sample 2: public static String digest(String password) { try { byte[] digest; synchronized (__TYPE) { if (__md == null) { try { __md = MessageDigest.getInstance("MD5"); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); return null; } } __md.reset(); __md.update(password.getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } return __TYPE + TypeUtil.toString(digest, 16); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); return null; } }
11
Code Sample 1: private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); this.setTitle("�ϥλ���"); jTextPane1.setEditable(false); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(jTextPane1); this.setSize(400, 600); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); URL url = ReadmeFrame.class.getResource("readme.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuilder strBuilder = new StringBuilder(); while (reader.ready()) { strBuilder.append(reader.readLine()); strBuilder.append('\n'); } reader.close(); jTextPane1.setText(strBuilder.toString()); } Code Sample 2: protected void handleUrl(URL url) throws Exception { File file = new File(dir.getAbsolutePath() + "/" + new Date().getTime() + "." + this.ext); FileWriter writer = new FileWriter(file); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String s; while ((s = in.readLine()) != null) { writer.write(s + "\n"); } in.close(); writer.close(); }
00
Code Sample 1: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); } Code Sample 2: public static String encrypt(String txt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(txt.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
00
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: public BasicTraceImpl() { out = System.out; traceEnable = new HashMap(); URL url = Hive.getURL("trace.cfg"); if (url != null) try { InputStream input = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(input)); String line; for (line = line = in.readLine(); line != null; line = in.readLine()) { int i = line.indexOf("="); if (i > 0) { String name = line.substring(0, i).trim(); String value = line.substring(i + 1).trim(); traceEnable.put(name, Boolean.valueOf(value).booleanValue() ? ((Object) (Boolean.TRUE)) : ((Object) (Boolean.FALSE))); } } input.close(); } catch (IOException io) { System.out.println(io); } TRACE = getEnable(THIS); }
11
Code Sample 1: private String fetchContent() throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buf = new StringBuffer(); String str; while ((str = reader.readLine()) != null) { buf.append(str); } return buf.toString(); } Code Sample 2: private static String getDocumentAt(String urlString) { StringBuffer html_text = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) html_text.append(line + "\n"); reader.close(); } catch (MalformedURLException e) { System.out.println("����URL: " + urlString); } catch (IOException e) { e.printStackTrace(); } return html_text.toString(); }
00
Code Sample 1: void bubbleSort(int[] a) { int i = 0; int j = a.length - 1; int aux = 0; int stop = 0; while (stop == 0) { stop = 1; i = 0; while (i < j) { if (a[i] > a[i + 1]) { aux = a[i]; a[i] = a[i + 1]; a[i + 1] = aux; stop = 0; } i = i + 1; } j = j - 1; } } Code Sample 2: public void run() { if (isRunning) return; isRunning = true; Core core = Core.getInstance(); URL url = null; InputStream input = null; DataInputStream datastream; try { url = new URL(Constants.UpdateCheckUrl); } catch (MalformedURLException e) { if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } try { input = url.openStream(); } catch (IOException e) { if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } datastream = new DataInputStream(new BufferedInputStream(input)); String line = null; try { line = datastream.readLine(); } catch (IOException e) { e.printStackTrace(); if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } if (line == null) { if (!firstRun) core.showMessage(1, core.getString("error"), core.getString("errorUpdateCheck")); isRunning = false; return; } if (line.trim().equalsIgnoreCase(Constants.version)) { if (!firstRun) core.showMessage(0, core.getString("checkUpdateButton"), core.getString("versionMatch")); } else { core.showMessage(1, core.getString("checkUpdateButton"), core.getString("errorNewerVersion") + ": " + line); } isRunning = false; }
00
Code Sample 1: public static void copyFile(File oldFile, File newFile) throws Exception { newFile.getParentFile().mkdirs(); newFile.createNewFile(); FileChannel srcChannel = new FileInputStream(oldFile).getChannel(); FileChannel dstChannel = new FileOutputStream(newFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } Code Sample 2: @Override public void run() { File file; try { file = new File(filePath); if (!file.canWrite()) { Thread.sleep(5000); if (!file.canWrite()) { logger.error("Filed to gain write access to file:" + filePath); exitState = false; return; } } fis = new BufferedInputStream(new FileInputStream(filePath)); } catch (FileNotFoundException e) { logger.error("File not found:" + filePath); exitState = false; return; } catch (java.lang.InterruptedException ie) { logger.error("Upload thread halted or interrupted on file:" + filePath); exitState = false; return; } ftp = new FTPClient(); ftp.setDefaultTimeout(20 * 1000); boolean uploadSuccessful = false; try { ftp.enterLocalPassiveMode(); ftp.connect(ftpHostname); ftp.login(username, password); logger.trace("FTP Logged In and connected"); if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) { exitState = false; return; } ftp.setFileType(FTPClient.BINARY_FILE_TYPE); logger.trace("FTP Timeout Set and File Type Set"); ftp.changeWorkingDirectory(serverDirectory); ftp.storeUniqueFile(file.getName(), fis); logger.trace("File Uploaded"); if (FTPReply.isPositiveIntermediate(ftp.getReplyCode())) { System.out.println("Completing pending command"); ftp.completePendingCommand(); } uploadSuccessful = true; } catch (Exception e) { try { ftp.disconnect(); } catch (Exception de) { e.printStackTrace(); } logger.error("Error uploading file:", e); } finally { try { fis.close(); logger.trace("File closed"); ftp.logout(); logger.trace("FTP Logged Out"); ftp.disconnect(); logger.trace("FTP Disconnected"); if (uploadSuccessful) { logger.info("Deleting file:" + new File(filePath).getName()); if (!(new File(filePath)).delete()) { logger.error("Can't delete file for some reason"); } Thread.sleep(1000); exitState = true; return; } } catch (Exception e) { logger.error("Exception on file upload cleanup:", e); exitState = false; return; } } exitState = false; return; }
00
Code Sample 1: private void executeScript(SQLiteDatabase sqlDatabase, InputStream input) { StringWriter writer = new StringWriter(); try { IOUtils.copy(input, writer); } catch (IOException e) { throw new ComixException("Could not read the database script", e); } String multipleSql = writer.toString(); String[] split = multipleSql.split("-- SCRIPT_SPLIT --"); for (String sql : split) { if (!sql.trim().equals("")) { sqlDatabase.execSQL(sql); } } } Code Sample 2: public static String genetateSHA256(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes("UTF-8")); byte[] passWd = md.digest(); String hex = toHex(passWd); return hex; }
00
Code Sample 1: public static void main(String[] args) { if (args.length <= 0) { System.out.println(" *** SQL script generator and executor ***"); System.out.println(" You must specify name of the file with SQL script data"); System.out.println(" Fisrt rows of this file must be:"); System.out.println(" 1) JDBC driver class for your DBMS"); System.out.println(" 2) URL for your database instance"); System.out.println(" 3) user in that database (with administrator priviliges)"); System.out.println(" 4) password of that user"); System.out.println(" Next rows can have: '@' before schema to create,"); System.out.println(" '#' before table to create, '&' before table to insert,"); System.out.println(" '$' before trigger (inverse 'FK on delete cascade') to create,"); System.out.println(" '>' before table to drop, '<' before schema to drop."); System.out.println(" Other rows contain parameters of these actions:"); System.out.println(" for & action each parameter is a list of values,"); System.out.println(" for @ -//- is # acrion, for # -//- is column/constraint "); System.out.println(" definition or $ action. $ syntax to delete from table:"); System.out.println(" fullNameOfTable:itsColInWhereClause=matchingColOfThisTable"); System.out.println(" '!' before row means that it is a comment."); System.out.println(" If some exception is occured, all script is rolled back."); System.out.println(" If you specify 2nd command line argument - file name too -"); System.out.println(" connection will be established but all statements will"); System.out.println(" be saved in that output file and not transmitted to DB"); System.out.println(" If you specify 3nd command line argument - connect_string -"); System.out.println(" connect information will be added to output file"); System.out.println(" in the form 'connect user/password@connect_string'"); System.exit(0); } try { String[] info = new String[4]; BufferedReader reader = new BufferedReader(new FileReader(new File(args[0]))); Writer writer = null; try { for (int i = 0; i < 4; i++) info[i] = reader.readLine(); try { Class.forName(info[0]); Connection connection = DriverManager.getConnection(info[1], info[2], info[3]); SQLScript script = new SQLScript(connection); if (args.length > 1) { writer = new FileWriter(args[1]); if (args.length > 2) writer.write("connect " + info[2] + "/" + info[3] + "@" + args[2] + script.statementTerminator); } try { System.out.println(script.executeScript(reader, writer) + " updates has been performed during script execution"); } catch (SQLException e4) { reader.close(); if (writer != null) writer.close(); System.out.println(" Script execution error: " + e4); } connection.close(); } catch (Exception e3) { reader.close(); if (writer != null) writer.close(); System.out.println(" Connection error: " + e3); } } catch (IOException e2) { System.out.println("Error in file " + args[0]); } } catch (FileNotFoundException e1) { System.out.println("File " + args[0] + " not found"); } } Code Sample 2: public static Vector<Person> parseFriends(Worker me, SmEngine sme, Person resource) throws IOException { URL url = new URL(resource.getUrl()); long fid; if (sme.getProxy() == null) me.conn = (HttpURLConnection) url.openConnection(); else me.conn = (HttpURLConnection) url.openConnection(sme.getProxy()); me.conn.setReadTimeout(20 * 1000); Vector<Person> result; org.htmlparser.Parser parser; NodeList nl; NodeFilter[] filters1 = new NodeFilter[2]; filters1[0] = new TagNameFilter("a"); filters1[1] = new HasAttributeFilter("class", "signup_btn uiButton uiButtonSpecial uiButtonLarge"); NodeFilter[] filters2 = new NodeFilter[3]; filters2[0] = new TagNameFilter("a"); filters2[1] = new HasAttributeFilter("class", "title"); filters2[2] = new HasParentFilter(new HasAttributeFilter("class", "UIPortrait_Text")); try { parser = new org.htmlparser.Parser(me.conn); } catch (ParserException e) { System.err.println(e.getMessage()); return null; } try { nl = parser.parse(new AndFilter(filters1)); fid = Long.parseLong(((LinkTag) nl.elementAt(0)).getLink().split("(fid=|&amp)")[2]); } catch (ParserException e) { e.printStackTrace(); return null; } result = new Vector<Person>(); try { nl = parser.parse(new AndFilter(filters2)); } catch (ParserException e) { e.printStackTrace(); return null; } Person p; for (int i = 0; i < nl.size(); i++) { p = sme.getPerson(fid, ((TagNode) nl.elementAt(i)).getAttribute("title"), ((TagNode) nl.elementAt(i)).getAttribute("href")); resource.addFriend(p); p.addFriend(resource); synchronized (p) { if (!p.isInQueue()) { p.setInQueue(true); sme.addResource(p); } } } return result; }
11
Code Sample 1: public void writeFile(OutputStream outputStream) throws IOException { InputStream inputStream = null; if (file != null) { try { inputStream = new FileInputStream(file); IOUtils.copy(inputStream, outputStream); } finally { if (inputStream != null) { IOUtils.closeQuietly(inputStream); } } } } Code Sample 2: public static boolean encodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.ENCODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
11
Code Sample 1: public static void copyFile(File src, File dst) throws IOException { if (T.t) T.info("Copying " + src + " -> " + dst + "..."); FileInputStream in = new FileInputStream(src); FileOutputStream out = new FileOutputStream(dst); byte buf[] = new byte[40 * KB]; int read; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); } out.flush(); out.close(); in.close(); if (T.t) T.info("File copied."); } Code Sample 2: public OOXMLSignatureService(InputStream documentInputStream, OutputStream documentOutputStream, SignatureFacet signatureFacet, String role, IdentityDTO identity, byte[] photo, RevocationDataService revocationDataService, TimeStampService timeStampService, DigestAlgo signatureDigestAlgo) throws IOException { super(signatureDigestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".ooxml"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(signatureFacet); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
11
Code Sample 1: public void testCopyFolderContents() throws IOException { log.info("Running: testCopyFolderContents()"); IOUtils.copyFolderContents(srcFolderName, destFolderName); Assert.assertTrue(destFile1.exists() && destFile1.isFile()); Assert.assertTrue(destFile2.exists() && destFile2.isFile()); Assert.assertTrue(destFile3.exists() && destFile3.isFile()); } Code Sample 2: public static long toFile(final DigitalObject object, final File file) { try { FileOutputStream fOut = new FileOutputStream(file); long bytesCopied = IOUtils.copyLarge(object.getContent().getInputStream(), fOut); fOut.close(); return bytesCopied; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return 0; }
11
Code Sample 1: public boolean loadResource(String resourcePath) { try { URL url = Thread.currentThread().getContextClassLoader().getResource(resourcePath); if (url == null) { logger.error("Cannot find the resource named: '" + resourcePath + "'. Failed to load the keyword list."); return false; } InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String ligne = br.readLine(); while (ligne != null) { if (!contains(ligne.toUpperCase())) addLast(ligne.toUpperCase()); ligne = br.readLine(); } return true; } catch (IOException ioe) { logger.log(Level.ERROR, "Cannot load default SQL keywords file.", ioe); } return false; } Code Sample 2: private void initialize() { StringBuffer license = new StringBuffer(); URL url; InputStreamReader in; BufferedReader reader; String str; JTextArea textArea; JButton button; GridBagConstraints c; setTitle("mibible License"); setSize(600, 600); setDefaultCloseOperation(DISPOSE_ON_CLOSE); getContentPane().setLayout(new GridBagLayout()); url = getClass().getClassLoader().getResource("LICENSE.txt"); if (url == null) { license.append("Couldn't locate license file (LICENSE.txt)."); } else { try { in = new InputStreamReader(url.openStream()); reader = new BufferedReader(in); while ((str = reader.readLine()) != null) { if (!str.equals(" ")) { license.append(str); } license.append("\n"); } reader.close(); } catch (IOException e) { license.append("Error reading license file "); license.append("(LICENSE.txt):\n\n"); license.append(e.getMessage()); } } textArea = new JTextArea(license.toString()); textArea.setEditable(false); c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0d; c.weighty = 1.0d; c.insets = new Insets(4, 5, 4, 5); getContentPane().add(new JScrollPane(textArea), c); button = new JButton("Close"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); c = new GridBagConstraints(); c.gridy = 1; c.anchor = GridBagConstraints.CENTER; c.insets = new Insets(10, 10, 10, 10); getContentPane().add(button, c); }
11
Code Sample 1: public void save() throws IOException { CodeTimer saveTimer; if (!dirty) { return; } saveTimer = new CodeTimer("PackedFile.save"); saveTimer.setEnabled(log.isDebugEnabled()); File newFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".pak"); ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile))); zout.setLevel(1); try { saveTimer.start("contentFile"); if (hasFile(CONTENT_FILE)) { zout.putNextEntry(new ZipEntry(CONTENT_FILE)); InputStream is = getFileAsInputStream(CONTENT_FILE); IOUtils.copy(is, zout); zout.closeEntry(); } saveTimer.stop("contentFile"); saveTimer.start("propertyFile"); if (getPropertyMap().isEmpty()) { removeFile(PROPERTY_FILE); } else { zout.putNextEntry(new ZipEntry(PROPERTY_FILE)); xstream.toXML(getPropertyMap(), zout); zout.closeEntry(); } saveTimer.stop("propertyFile"); saveTimer.start("addFiles"); addedFileSet.remove(CONTENT_FILE); for (String path : addedFileSet) { zout.putNextEntry(new ZipEntry(path)); InputStream is = getFileAsInputStream(path); IOUtils.copy(is, zout); zout.closeEntry(); } saveTimer.stop("addFiles"); saveTimer.start("copyFiles"); if (file.exists()) { Enumeration<? extends ZipEntry> entries = zFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory() && !addedFileSet.contains(entry.getName()) && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName()) && !PROPERTY_FILE.equals(entry.getName())) { zout.putNextEntry(entry); InputStream is = getFileAsInputStream(entry.getName()); IOUtils.copy(is, zout); zout.closeEntry(); } else if (entry.isDirectory()) { zout.putNextEntry(entry); zout.closeEntry(); } } } try { if (zFile != null) zFile.close(); } catch (IOException e) { } zFile = null; saveTimer.stop("copyFiles"); saveTimer.start("close"); zout.close(); zout = null; saveTimer.stop("close"); saveTimer.start("backup"); File backupFile = new File(tmpDir.getAbsolutePath() + "/" + new GUID() + ".mv"); if (file.exists()) { backupFile.delete(); if (!file.renameTo(backupFile)) { FileUtil.copyFile(file, backupFile); file.delete(); } } saveTimer.stop("backup"); saveTimer.start("finalize"); if (!newFile.renameTo(file)) FileUtil.copyFile(newFile, file); if (backupFile.exists()) backupFile.delete(); saveTimer.stop("finalize"); dirty = false; } finally { saveTimer.start("cleanup"); try { if (zFile != null) zFile.close(); } catch (IOException e) { } if (newFile.exists()) newFile.delete(); try { if (zout != null) zout.close(); } catch (IOException e) { } saveTimer.stop("cleanup"); if (log.isDebugEnabled()) log.debug(saveTimer); saveTimer = null; } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static String createNormalizedJarDescriptorDigest(String path) throws Exception { String descriptor = createNormalizedDescriptor(new JarFile2(path)); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(descriptor.getBytes()); byte[] messageDigest = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return ""; } Code Sample 2: @Test public void testRegisterOwnJceProvider() throws Exception { MyTestProvider provider = new MyTestProvider(); assertTrue(-1 != Security.addProvider(provider)); MessageDigest messageDigest = MessageDigest.getInstance("SHA-1", MyTestProvider.NAME); assertEquals(MyTestProvider.NAME, messageDigest.getProvider().getName()); messageDigest.update("hello world".getBytes()); byte[] result = messageDigest.digest(); Assert.assertArrayEquals("hello world".getBytes(), result); Security.removeProvider(MyTestProvider.NAME); }
11
Code Sample 1: static void createCompleteXML(File file) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(errorFile); fos = new FileOutputStream(file); byte[] data = new byte[Integer.parseInt(BlueXStatics.prop.getProperty("allocationUnit"))]; int offset; while ((offset = fis.read(data)) != -1) fos.write(data, 0, offset); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (Exception e) { } try { fos.close(); } catch (Exception e) { } } FileWriter fw = null; try { fw = new FileWriter(file, true); fw.append("</detail>"); fw.append("\n</exception>"); fw.append("\n</log>"); } catch (Exception e) { e.printStackTrace(); } finally { try { fw.close(); } catch (Exception e) { } } } Code Sample 2: @Override public void copyFile2File(final File src, final File dest, final boolean force) throws C4JException { if (dest.exists()) if (force && !dest.delete()) throw new C4JException(format("Copying ‘%s’ to ‘%s’ failed; cannot overwrite existing file.", src.getPath(), dest.getPath())); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dest).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (src.canExecute()) dest.setExecutable(true, false); } catch (final IOException e) { throw new C4JException(format("Could not copy ‘%s’ to ‘%s’.", src.getPath(), dest.getPath()), e); } finally { if (inChannel != null) try { try { inChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close input stream for ‘%s’.", src.getPath()), e); } } finally { if (outChannel != null) try { outChannel.close(); } catch (final IOException e) { throw new C4JException(format("Could not close output stream for ‘%s’.", dest.getPath()), e); } } } }
11
Code Sample 1: public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); } Code Sample 2: private void copyFile(File in, File out) { try { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException ex) { ex.printStackTrace(); } }
11
Code Sample 1: public static void copyFile(File sourceFile, File destFile) { FileChannel source = null; FileChannel destination = null; try { if (!destFile.exists()) { destFile.createNewFile(); } source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } catch (Exception e) { e.printStackTrace(); } } } 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 zip() throws Exception { System.out.println("zip()"); ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(new File("/zip/myzip.zip"))); ZipEntry entry = new ZipEntry("asdf.script"); zipout.putNextEntry(entry); byte buffer[] = new byte[BLOCKSIZE]; FileInputStream in = new FileInputStream(new File("/zip/asdf.script")); for (int length; (length = in.read(buffer, 0, BLOCKSIZE)) != -1; ) zipout.write(buffer, 0, length); in.close(); zipout.closeEntry(); zipout.close(); } Code Sample 2: public void generate(FileObject outputDirectory, FileObject generatedOutputDirectory, List<Library> libraryModels, String tapdocXml) throws FileSystemException { if (!outputDirectory.exists()) { outputDirectory.createFolder(); } ZipUtils.extractZip(new ClasspathResource(classResolver, "/com/erinors/tapestry/tapdoc/standalone/resources.zip"), outputDirectory); for (Library library : libraryModels) { String libraryName = library.getName(); String libraryLocation = library.getLocation(); outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).createFolder(); try { { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Library.xsl"), "libraryName", libraryName); FileObject index = outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("index.html"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("ComponentIndex.xsl"), "libraryName", libraryName); FileObject index = outputDirectory.resolveFile(fileNameGenerator.getLibraryDirectory(libraryLocation)).resolveFile("components.html"); Writer out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } } catch (Exception e) { throw new RuntimeException(e); } for (Component component : library.getComponents()) { String componentName = component.getName(); System.out.println("Generating " + libraryName + ":" + componentName + "..."); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("libraryName", libraryName); parameters.put("componentName", componentName); String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Component.xsl"), parameters); Writer out = null; try { FileObject index = outputDirectory.resolveFile(fileNameGenerator.getComponentIndexFile(libraryLocation, componentName, true)); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); Resource specificationLocation = component.getSpecificationLocation(); if (specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL() != null) { File srcResourcesDirectory = new File(specificationLocation.getRelativeResource(componentName + "_tapdoc/resource").getResourceURL().toURI()); FileObject dstResourcesFileObject = outputDirectory.resolveFile(fileNameGenerator.getComponentDirectory(libraryLocation, componentName)).resolveFile("resource"); if (srcResourcesDirectory.exists() && srcResourcesDirectory.isDirectory()) { File[] files = srcResourcesDirectory.listFiles(); if (files != null) { for (File resource : files) { if (resource.isFile() && !resource.isHidden()) { FileObject resourceFileObject = dstResourcesFileObject.resolveFile(resource.getName()); resourceFileObject.createFile(); InputStream inResource = null; OutputStream outResource = null; try { inResource = new FileInputStream(resource); outResource = resourceFileObject.getContent().getOutputStream(); IOUtils.copy(inResource, outResource); } finally { IOUtils.closeQuietly(inResource); IOUtils.closeQuietly(outResource); } } } } } } } catch (Exception e) { throw new RuntimeException(e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } } { Writer out = null; try { { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("LibraryIndex.xsl")); FileObject index = outputDirectory.resolveFile("libraries.html"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("Overview.xsl")); FileObject index = outputDirectory.resolveFile("overview.html"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } { String result = XsltUtils.xsltTransform(tapdocXml, getClass().getResourceAsStream("AllComponents.xsl")); FileObject index = outputDirectory.resolveFile("allcomponents.html"); out = new OutputStreamWriter(index.getContent().getOutputStream(), "UTF-8"); out.write(result); out.close(); } } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); } } }
11
Code Sample 1: public void service(TranslationRequest request, TranslationResponse response) { try { Thread.sleep((long) Math.random() * 250); } catch (InterruptedException e1) { } hits.incrementAndGet(); String key = getKey(request); RequestResponse cachedResponse = cache.get(key); if (cachedResponse == null) { response.setEndState(new ResponseStateBean(ResponseCode.ERROR, "response not found for " + key)); return; } response.addHeaders(cachedResponse.getExpectedResponse().getHeaders()); response.setTranslationCount(cachedResponse.getExpectedResponse().getTranslationCount()); response.setFailCount(cachedResponse.getExpectedResponse().getFailCount()); if (cachedResponse.getExpectedResponse().getLastModified() != -1) { response.setLastModified(cachedResponse.getExpectedResponse().getLastModified()); } try { OutputStream output = response.getOutputStream(); InputStream input = cachedResponse.getExpectedResponse().getInputStream(); try { IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(output); } } catch (IOException e) { response.setEndState(new ResponseStateException(e)); return; } response.setEndState(cachedResponse.getExpectedResponse().getEndState()); } Code Sample 2: public static void copy(File src, File dest) throws IOException { log.info("Copying " + src.getAbsolutePath() + " to " + dest.getAbsolutePath()); if (!src.exists()) throw new IOException("File not found: " + src.getAbsolutePath()); if (!src.canRead()) throw new IOException("Source not readable: " + src.getAbsolutePath()); if (src.isDirectory()) { if (!dest.exists()) if (!dest.mkdirs()) throw new IOException("Could not create direcotry: " + dest.getAbsolutePath()); String children[] = src.list(); for (String child : children) { File src1 = new File(src, child); File dst1 = new File(dest, child); copy(src1, dst1); } } else { FileInputStream fin = null; FileOutputStream fout = null; byte[] buffer = new byte[4096]; int bytesRead; fin = new FileInputStream(src); fout = new FileOutputStream(dest); while ((bytesRead = fin.read(buffer)) >= 0) fout.write(buffer, 0, bytesRead); if (fin != null) { fin.close(); } if (fout != null) { fout.close(); } } }
00
Code Sample 1: public String getLastVersion() { try { String server = icescrum2Properties.get("check.url").toString(); Boolean useProxy = new Boolean(icescrum2Properties.get("proxy.active").toString()); Boolean authProxy = new Boolean(icescrum2Properties.get("proxy.auth.active").toString()); URL url = new URL(server); if (useProxy) { String proxy = icescrum2Properties.get("proxy.url").toString(); String port = icescrum2Properties.get("proxy.port").toString(); Properties systemProperties = System.getProperties(); systemProperties.setProperty("http.proxyHost", proxy); systemProperties.setProperty("http.proxyPort", port); } URLConnection connection = url.openConnection(); if (authProxy) { String username = icescrum2Properties.get("proxy.auth.username").toString(); String password = icescrum2Properties.get("proxy.auth.password").toString(); String login = username + ":" + password; String encodedLogin = Base64.base64Encode(login); connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedLogin); } connection.setConnectTimeout(Integer.parseInt(icescrum2Properties.get("check.timeout").toString())); InputStream input = connection.getInputStream(); StringWriter writer = new StringWriter(); InputStreamReader streamReader = new InputStreamReader(input); BufferedReader buffer = new BufferedReader(streamReader); String value = ""; while (null != (value = buffer.readLine())) { writer.write(value); } return writer.toString(); } catch (IOException e) { } return null; } Code Sample 2: public synchronized long nextValue(final Session session) { if (sequence < seqLimit) { return ++sequence; } else { final MetaDatabase db = MetaTable.DATABASE.of(table); Connection connection = null; ResultSet res = null; String sql = null; PreparedStatement statement = null; StringBuilder out = new StringBuilder(64); try { connection = session.getSeqConnection(db); String tableName = db.getDialect().printFullTableName(getTable(), true, out).toString(); out.setLength(0); out.setLength(0); sql = db.getDialect().printSequenceNextValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); int i = statement.executeUpdate(); if (i == 0) { out.setLength(0); sql = db.getDialect().printSequenceInit(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.executeUpdate(); } out.setLength(0); sql = db.getDialect().printSequenceCurrentValue(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); res = statement.executeQuery(); res.next(); seqLimit = res.getLong(1); int step = res.getInt(2); maxValue = res.getLong(3); sequence = (seqLimit - step) + 1; if (maxValue != 0L) { if (seqLimit > maxValue) { seqLimit = maxValue; if (sequence > maxValue) { String msg = "The sequence '" + tableName + "' needs to raise the maximum value: " + maxValue; throw new IllegalStateException(msg); } statement.close(); sql = db.getDialect().printSetMaxSequence(this, out).toString(); if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, sql + "; [" + tableName + ']'); } statement = connection.prepareStatement(sql); statement.setString(1, tableName); statement.execute(); } if (maxValue > Long.MAX_VALUE - step) { String msg = "The sequence attribute '" + tableName + ".maxValue' is too hight," + " the recommended maximal value is: " + (Long.MAX_VALUE - step) + " (Long.MAX_VALUE-step)"; LOGGER.log(Level.WARNING, msg); } } connection.commit(); } catch (Throwable e) { if (connection != null) try { connection.rollback(); } catch (SQLException ex) { LOGGER.log(Level.WARNING, "Rollback fails"); } IllegalStateException exception = e instanceof IllegalStateException ? (IllegalStateException) e : new IllegalStateException("ILLEGAL SQL: " + sql, e); throw exception; } finally { MetaDatabase.close(null, statement, res, true); } return sequence; } }
11
Code Sample 1: public void constructAssociationView() { String className; String methodName; String field; boolean foundRead = false; boolean foundWrite = false; boolean classWritten = false; try { AssocView = new BufferedWriter(new FileWriter("InfoFiles/AssociationView.txt")); FileInputStream fstreamPC = new FileInputStream("InfoFiles/PrincipleClassGroup.txt"); DataInputStream inPC = new DataInputStream(fstreamPC); BufferedReader PC = new BufferedReader(new InputStreamReader(inPC)); while ((field = PC.readLine()) != null) { className = field; AssocView.write(className); AssocView.newLine(); classWritten = true; while ((methodName = PC.readLine()) != null) { if (methodName.contentEquals("EndOfClass")) break; AssocView.write("StartOfMethod"); AssocView.newLine(); AssocView.write(methodName); AssocView.newLine(); for (int i = 0; i < readFileCount && foundRead == false; i++) { if (methodName.compareTo(readArray[i]) == 0) { foundRead = true; for (int j = 1; readArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (readArray[i + j].indexOf(".") > 0) { field = readArray[i + j].substring(0, readArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(readArray[i + j]); AssocView.newLine(); } } } } } for (int i = 0; i < writeFileCount && foundWrite == false; i++) { if (methodName.compareTo(writeArray[i]) == 0) { foundWrite = true; for (int j = 1; writeArray[i + j].compareTo("EndOfMethod") != 0; j++) { if (writeArray[i + j].indexOf(".") > 0) { field = writeArray[i + j].substring(0, writeArray[i + j].indexOf(".")); if (isPrincipleClass(field) == true) { AssocView.write(writeArray[i + j]); AssocView.newLine(); } } } } } AssocView.write("EndOfMethod"); AssocView.newLine(); foundRead = false; foundWrite = false; } if (classWritten == true) { AssocView.write("EndOfClass"); AssocView.newLine(); classWritten = false; } } PC.close(); AssocView.close(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public static void encryptFile(String infile, String outfile, String keyFile) throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, getKey()); java.io.FileInputStream in = new java.io.FileInputStream(infile); java.io.FileOutputStream fileOut = new java.io.FileOutputStream(outfile); javax.crypto.CipherOutputStream out = new javax.crypto.CipherOutputStream(fileOut, cipher); byte[] buffer = new byte[kBufferSize]; int length; while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length); in.close(); out.close(); }
00
Code Sample 1: private static void fileUpload() throws IOException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(postURL); file = new File("h:/UploadingdotcomUploaderPlugin.java"); MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); ContentBody cbFile = new FileBody(file); mpEntity.addPart("upload_type", new StringBody("file")); mpEntity.addPart("sess_id", new StringBody(sessid)); mpEntity.addPart("srv_tmp_url", new StringBody(servertmpurl)); mpEntity.addPart("file_0", cbFile); mpEntity.addPart("submit_btn", new StringBody(" Upload!")); httppost.setEntity(mpEntity); System.out.println("executing request " + httppost.getRequestLine()); System.out.println("Now uploading your file into enterupload.com"); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); System.out.println(response.getStatusLine()); if (resEntity != null) { uploadresponse = EntityUtils.toString(resEntity); } downloadid = parseResponse(uploadresponse, "<textarea name='fn'>", "<"); httpclient.getConnectionManager().shutdown(); } Code Sample 2: public String encripta(String senha) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException ns) { ns.printStackTrace(); return senha; } }
00
Code Sample 1: @Override protected AuthenticationHandlerResponse authenticateInternal(final Connection c, final AuthenticationCriteria criteria) throws LdapException { byte[] hash = new byte[DIGEST_SIZE]; try { final MessageDigest md = MessageDigest.getInstance(passwordScheme); md.update(criteria.getCredential().getBytes()); hash = md.digest(); } catch (NoSuchAlgorithmException e) { throw new LdapException(e); } final LdapAttribute la = new LdapAttribute("userPassword", String.format("{%s}%s", passwordScheme, LdapUtil.base64Encode(hash)).getBytes()); final CompareOperation compare = new CompareOperation(c); final CompareRequest request = new CompareRequest(criteria.getDn(), la); request.setControls(getAuthenticationControls()); final Response<Boolean> compareResponse = compare.execute(request); return new AuthenticationHandlerResponse(compareResponse.getResult(), compareResponse.getResultCode(), c, null, compareResponse.getControls()); } Code Sample 2: protected void initDefaultRolesFile() { String webConfigPath = System.getProperty("dcm4chee-web3.cfg.path", "conf/dcm4chee-web3"); File mappingFile = new File(webConfigPath + "roles.json"); if (!mappingFile.isAbsolute()) mappingFile = new File(ServerConfigLocator.locate().getServerHomeDir(), mappingFile.getPath()); if (mappingFile.exists()) return; log.info("Init default Role Mapping file! mappingFile:" + mappingFile); if (mappingFile.getParentFile().mkdirs()) log.info("M-WRITE dir:" + mappingFile.getParent()); FileChannel fos = null; InputStream is = null; try { URL url = getClass().getResource("/META-INF/roles-default.json"); log.info("Use default Mapping File content of url:" + url); is = url.openStream(); ReadableByteChannel inCh = Channels.newChannel(is); fos = new FileOutputStream(mappingFile).getChannel(); int pos = 0; while (is.available() > 0) pos += fos.transferFrom(inCh, pos, is.available()); } catch (Exception e) { log.error("Roles file doesn't exist and the default can't be created!", e); } finally { close(is); close(fos); } }
11
Code Sample 1: public static String md5(String texto) { String resultado; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(texto.getBytes()); BigInteger hash = new BigInteger(1, md5.digest()); resultado = hash.toString(16); if (resultado.length() < 32) { char chars[] = new char[32 - resultado.length()]; Arrays.fill(chars, '0'); resultado = new String(chars) + resultado; } } catch (NoSuchAlgorithmException e) { resultado = e.toString(); } return resultado; } Code Sample 2: public static final String hash(String data) { MessageDigest digest = null; if (digest == null) { try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException nsae) { System.err.println("Failed to load the MD5 MessageDigest. " + "Jive will be unable to function normally."); nsae.printStackTrace(); } } digest.update(data.getBytes()); return encodeHex(digest.digest()); }
00
Code Sample 1: public void delete(int id) throws FidoDatabaseException { try { Connection conn = null; Statement stmt = null; try { conn = fido.util.FidoDataSource.getConnection(); conn.setAutoCommit(false); stmt = conn.createStatement(); stmt.executeUpdate("delete from WebServices where WebServiceId = " + id); stmt.executeUpdate("delete from WebServiceParams where WebServiceId = " + id); conn.commit(); } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } } catch (SQLException e) { throw new FidoDatabaseException(e); } } Code Sample 2: private void Download(String uri) throws MalformedURLException { URL url = new URL(uri); try { bm = BitmapFactory.decodeStream(url.openConnection().getInputStream()); } catch (IOException ex) { bm = getError(); } }
00
Code Sample 1: public void run() { XmlFilesFilter filter = new XmlFilesFilter(); String pathTemp = Settings.get("vo_store.databaseMetaCollection"); String sectionName = pathTemp.substring(1, pathTemp.indexOf("/", 2)); String templateName = VOAccess.getElementByName(settingsDB, "TEMPLATE", sectionName); String schemaName = VOAccess.getElementByName(settingsDB, "SCHEMA", sectionName); byte[] buf = new byte[1024]; Hashtable templateElements = null; try { URL xmlTemplateUrl = new URL(httpURI + settingsDB + "/" + templateName); URL getDocPathsAndValuesXslUrl = new URL(httpURI + settingsDB + "/" + "getDocPathsValuesAndDisplays.xsl"); org.w3c.dom.Document curTemplateXml = VOAccess.readDocument(xmlTemplateUrl); DOMResult templateResult = new DOMResult(); InputStream tempInput = getDocPathsAndValuesXslUrl.openStream(); javax.xml.transform.sax.SAXSource tempXslSource = new javax.xml.transform.sax.SAXSource(new org.xml.sax.InputSource(tempInput)); Transformer trans = TransformerFactory.newInstance().newTransformer(tempXslSource); trans.setParameter("schemaUrl", httpURI + settingsDB + "/" + schemaName); trans.transform(new javax.xml.transform.dom.DOMSource(curTemplateXml), templateResult); tempInput.close(); templateElements = VOAccess.displaysToHashtable(templateResult); ((CollectionManagementService) CollectionsManager.getService(xmldbURI + rootDB, false, "CollectionManager")).createCollection(rootDB + pathTemp); } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); } while (true) { File[] fileList = sourceMetaFilesDir.listFiles(filter); for (int i = 0; i < Math.min(fileList.length, 500); i++) { File newFile = fileList[i]; try { Document metaDoc = build.build(newFile); Element metaElm = metaDoc.getRootElement(); String dataFileName = metaElm.getChildText("Content"), previewFileName = metaElm.getChildText("Preview"); String objId = VOAccess.getUniqueId(); metaElm.getChild("Content").setText("videostore?type=doc&objId=" + objId); metaElm.getChild("Preview").setText("videostore?type=preview&objId=" + objId); boolean found = false; for (Iterator it = sourceDataFilesDirs.iterator(); it.hasNext() && !found; ) { String sourceDataFilesDir = (String) it.next(); File dataInput = new File(sourceDataFilesDir + "/" + dataFileName); if (dataInput.exists()) { found = true; BufferedInputStream inp = new BufferedInputStream(new FileInputStream(dataInput)); FileOutputStream outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".dat")); int read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); dataInput = new File(sourceDataFilesDir + "/" + previewFileName); inp = new BufferedInputStream(new FileInputStream(dataInput)); outp = new FileOutputStream(new File(targetDataFilesDirs.get(curDirWriteTo) + "/" + objId + ".jpg")); read = inp.read(buf, 0, buf.length); while (read > 0) { outp.write(buf, 0, read); read = inp.read(buf, 0, buf.length); } inp.close(); outp.flush(); outp.close(); curDirWriteTo++; if (curDirWriteTo >= targetDataFilesDirs.size()) { curDirWriteTo = 0; } } } if (!found) { newFile.renameTo(new File(newFile.getAbsolutePath() + ".not_found")); } else { String title = getValueByPath((String) templateElements.get("title"), metaDoc.getRootElement()); String description = getValueByPath((String) templateElements.get("description"), metaDoc.getRootElement()); String onlink = ""; if (null != templateElements.get("onlink")) { onlink = getValueByPath((String) templateElements.get("onlink"), metaDoc.getRootElement()); } String ncover = ""; if (null != templateElements.get("ncover")) { ncover = getValueByPath((String) templateElements.get("ncover"), metaDoc.getRootElement()); } String wcover = ""; if (null != templateElements.get("wcover")) { wcover = getValueByPath((String) templateElements.get("wcover"), metaDoc.getRootElement()); } String ecover = ""; if (null != templateElements.get("ecover")) { ecover = getValueByPath((String) templateElements.get("ecover"), metaDoc.getRootElement()); } String scover = ""; if (null != templateElements.get("scover")) { scover = getValueByPath((String) templateElements.get("scover"), metaDoc.getRootElement()); } String datefrom = ""; if (null != templateElements.get("datefrom")) { datefrom = getValueByPath((String) templateElements.get("datefrom"), metaDoc.getRootElement()); } String dateto = ""; if (null != templateElements.get("dateto")) { dateto = getValueByPath((String) templateElements.get("dateto"), metaDoc.getRootElement()); } String previewimg = ""; if (null != templateElements.get("previewimg")) { previewimg = getValueByPath((String) templateElements.get("previewimg"), metaDoc.getRootElement()); } String discRestr = "false"; String votingRestr = "false"; datefrom = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); dateto = VOAccess.parseDate(datefrom, "yyyy-MM-dd'T'HH:mm:ss", VO.defaultTimeFormat.toPattern()); Hashtable discussionFields = new Hashtable(); discussionFields.put("OBJECT_ID", objId); discussionFields.put("AUTHOR_ID", "auto"); discussionFields.put("AUTHOR_NAME", "auto"); discussionFields.put("OBJECT_SECTION", sectionName); discussionFields.put("OBJECT_PATH", pathTemp); discussionFields.put("FILE_PATH", ""); discussionFields.put("TITLE", title); discussionFields.put("DESCRIPTION", description); discussionFields.put("ONLINK", onlink); discussionFields.put("NCOVER", ncover); discussionFields.put("ECOVER", ecover); discussionFields.put("SCOVER", scover); discussionFields.put("WCOVER", wcover); discussionFields.put("PERIOD_START", datefrom); discussionFields.put("PERIOD_END", dateto); discussionFields.put("PREVIEW_IMG", previewimg); discussionFields.put("DISCUSSRESTRICTION", discRestr); discussionFields.put("VOTINGRESTRICTION", votingRestr); VOAccess.createDiscussionFile(discussionFields); VOAccess.updateLastItem(objId, sectionName); Collection col = CollectionsManager.getCollection(rootDB + pathTemp, true); XMLResource document = (XMLResource) col.createResource(objId + ".xml", XMLResource.RESOURCE_TYPE); document.setContent(outXml.outputString(metaElm)); col.storeResource(document); Indexer.index(objId); newFile.delete(); } } catch (Exception ex) { logger.error("Error parsing input document", ex); ex.printStackTrace(); newFile.renameTo(new File(newFile.getAbsolutePath() + ".bad")); } } try { this.sleep(600000); } catch (InterruptedException ex1) { ex1.printStackTrace(); } } } Code Sample 2: public void addPropertyColumns(WCAChannel destination, Set<Property> properties) throws SQLException { Session session = HibernateUtil.getSessionFactory().openSession(); Connection con = session.connection(); try { createPropertyTable(destination); extendPropertyList(destination, properties); Statement statement = con.createStatement(); for (Property property : properties) { String propertyName = removeBadChars(property.getName()); statement.executeUpdate(alterTable.format(new Object[] { getTableName(destination), propertyName, property.getDBColumnType() })); } con.commit(); con.close(); session.close(); } catch (SQLException e) { con.rollback(); session.close(); throw e; } }
11
Code Sample 1: public void run() { try { FileChannel in = (new FileInputStream(file)).getChannel(); FileChannel out = (new FileOutputStream(updaterFile)).getChannel(); in.transferTo(0, file.length(), out); updater.setProgress(50); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } startUpdater(); } Code Sample 2: private JButton getButtonSonido() { if (buttonSonido == null) { buttonSonido = new JButton(); buttonSonido.setText(Messages.getString("gui.AdministracionResorces.15")); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetree.png")); buttonSonido.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new SoundFilter()); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.17")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "sonidos/" + file.getName(); String rutaRelativa = rutaDatos + "sonidos/" + 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.setSonidoURL(rutaRelativa); System.out.println(rutaGlobal + " " + rutaRelativa); buttonSonido.setIcon(new ImageIcon("data/icons/view_sidetreeOK.png")); gui.getAudio().reproduceAudio(imagen); } catch (IOException ex) { ex.printStackTrace(); } } else { } } }); } return buttonSonido; }
00
Code Sample 1: public void invoke(WorkflowContext arg0, ProgressMonitor arg1, Issues arg2) { File inputFile = new File(getInputFile()); File outputFile = new File(getOutputFile()); if (!getFileExtension(getInputFile()).equalsIgnoreCase(getFileExtension(getOutputFile())) || !getFileExtension(getInputFile()).equalsIgnoreCase(OO_CALC_EXTENSION)) { OpenOfficeConnection connection = new SocketOpenOfficeConnection(); OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection); converter.convert(inputFile, outputFile); connection.disconnect(); } else { FileChannel inputChannel = null; FileChannel outputChannel = null; try { inputChannel = new FileInputStream(inputFile).getChannel(); outputChannel = new FileOutputStream(outputFile).getChannel(); outputChannel.transferFrom(inputChannel, 0, inputChannel.size()); } catch (FileNotFoundException e) { arg2.addError("File not found: " + e.getMessage()); } catch (IOException e) { arg2.addError("Could not copy file: " + e.getMessage()); } finally { if (inputChannel != null) { try { inputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } if (outputChannel != null) { try { outputChannel.close(); } catch (IOException e) { arg2.addError("Could not close input channel: " + e.getMessage()); } } } } } Code Sample 2: public InputStream getResourceAsStream(String name) { try { URL url = getResource(name); System.out.println("Loading \"" + url + "\"..."); URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; httpURLConnection.setFollowRedirects(true); httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); System.out.println(httpURLConnection.getResponseMessage() + ", " + httpURLConnection.getContentLength() + " bytes" + ", " + new Date(httpURLConnection.getDate()) + ", " + new Date(httpURLConnection.getLastModified())); if (responseCode != HttpURLConnection.HTTP_OK) { return null; } } return urlConnection.getInputStream(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
11
Code Sample 1: public void migrateTo(String newExt) throws IOException { DigitalObject input = new DigitalObject.Builder(Content.byReference(new File(AllJavaSEServiceTestsuite.TEST_FILE_LOCATION + "PlanetsLogo.png").toURI().toURL())).build(); System.out.println("Input: " + input); FormatRegistry format = FormatRegistryFactory.getFormatRegistry(); MigrateResult mr = dom.migrate(input, format.createExtensionUri("png"), format.createExtensionUri(newExt), null); ServiceReport sr = mr.getReport(); System.out.println("Got Report: " + sr); DigitalObject doOut = mr.getDigitalObject(); assertTrue("Resulting digital object is null.", doOut != null); System.out.println("Output: " + doOut); System.out.println("Output.content: " + doOut.getContent()); File out = new File("services/java-se/test/results/test." + newExt); FileOutputStream fo = new FileOutputStream(out); IOUtils.copyLarge(doOut.getContent().getInputStream(), fo); fo.close(); System.out.println("Recieved service report: " + mr.getReport()); System.out.println("Recieved service properties: "); ServiceProperties.printProperties(System.out, mr.getReport().getProperties()); } Code Sample 2: public static void unzip(String destDir, String zipPath) { PrintWriter stdout = new PrintWriter(System.out, true); int read = 0; byte[] data = new byte[1024]; ZipEntry entry; try { ZipInputStream in = new ZipInputStream(new FileInputStream(zipPath)); stdout.println(zipPath); while ((entry = in.getNextEntry()) != null) { if (entry.getMethod() == ZipEntry.DEFLATED) { stdout.println(" Inflating: " + entry.getName()); } else { stdout.println(" Extracting: " + entry.getName()); } FileOutputStream out = new FileOutputStream(destDir + File.separator + entry.getName()); while ((read = in.read(data, 0, 1024)) != -1) { out.write(data, 0, read); } out.close(); } in.close(); stdout.println(); } catch (Exception e) { e.printStackTrace(); } }
00
Code Sample 1: public File createReadmeFile(File dir, MavenProject mavenProject) throws IOException { InputStream is = getClass().getResourceAsStream("README.template"); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw); String content = sw.getBuffer().toString(); content = StringUtils.replace(content, "{project_name}", mavenProject.getArtifactId()); File readme = new File(dir, "README.TXT"); FileUtils.writeStringToFile(readme, content); return readme; } Code Sample 2: public static int[] bubbleSort2(int[] source) { if (null != source && source.length > 0) { boolean flag = false; while (!flag) { for (int i = 0; i < source.length - 1; i++) { if (source[i] > source[i + 1]) { int temp = source[i]; source[i] = source[i + 1]; source[i + 1] = temp; break; } else if (i == source.length - 2) { flag = true; } } } } return source; }
11
Code Sample 1: protected void migrateOnDemand() { try { if (fso.fileExists(prefix + ".fat") && !fso.fileExists(prefix + EXTENSIONS[UBM_FILE])) { RandomAccessFile ubm, meta, ctr, rbm; InputStream inputStream; OutputStream outputStream; fso.renameFile(prefix + ".fat", prefix + EXTENSIONS[UBM_FILE]); ubm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); meta = fso.openFile(prefix + EXTENSIONS[MTD_FILE], "rw"); ctr = fso.openFile(prefix + EXTENSIONS[CTR_FILE], "rw"); ubm.seek(ubm.length() - 16); meta.writeInt(blockSize = ubm.readInt()); meta.writeInt(size = ubm.readInt()); ctr.setLength(ubm.readLong() + blockSize); ctr.close(); meta.close(); ubm.setLength(ubm.length() - 16); ubm.seek(0); rbm = fso.openFile(prefix + EXTENSIONS[UBM_FILE], "rw"); inputStream = new BufferedInputStream(new RandomAccessFileInputStream(ubm)); outputStream = new BufferedOutputStream(new RandomAccessFileOutputStream(rbm)); for (int b; (b = inputStream.read()) != -1; ) outputStream.write(b); outputStream.close(); inputStream.close(); rbm.close(); ubm.close(); } } catch (IOException ie) { throw new WrappingRuntimeException(ie); } } Code Sample 2: @Test public void testLargePut() throws Throwable { int size = CommonParameters.BLOCK_SIZE; InputStream is = new FileInputStream(_fileName); RepositoryFileOutputStream ostream = new RepositoryFileOutputStream(_nodeName, _putHandle, CommonParameters.local); int readLen = 0; int writeLen = 0; byte[] buffer = new byte[CommonParameters.BLOCK_SIZE]; while ((readLen = is.read(buffer, 0, size)) != -1) { ostream.write(buffer, 0, readLen); writeLen += readLen; } ostream.close(); CCNStats stats = _putHandle.getNetworkManager().getStats(); Assert.assertEquals(0, stats.getCounter("DeliverInterestFailed")); }
00
Code Sample 1: private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } } Code Sample 2: public static URL[] getURLsForAllJars(URL url, File tmpDir) { FileInputStream fin = null; InputStream in = null; ZipInputStream zin = null; try { ArrayList array = new ArrayList(); in = url.openStream(); String fileName = url.getFile(); int index = fileName.lastIndexOf('/'); if (index != -1) { fileName = fileName.substring(index + 1); } final File f = createTempFile(fileName, in, tmpDir); fin = (FileInputStream) org.apache.axis2.java.security.AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws FileNotFoundException { return new FileInputStream(f); } }); array.add(f.toURL()); zin = new ZipInputStream(fin); ZipEntry entry; String entryName; while ((entry = zin.getNextEntry()) != null) { entryName = entry.getName(); if ((entryName != null) && entryName.toLowerCase().startsWith("lib/") && entryName.toLowerCase().endsWith(".jar")) { String suffix = entryName.substring(4); File f2 = createTempFile(suffix, zin, tmpDir); array.add(f2.toURL()); } } return (URL[]) array.toArray(new URL[array.size()]); } catch (Exception e) { throw new RuntimeException(e); } finally { if (fin != null) { try { fin.close(); } catch (IOException e) { } } if (in != null) { try { in.close(); } catch (IOException e) { } } if (zin != null) { try { zin.close(); } catch (IOException e) { } } } }
11
Code Sample 1: private void parseExternalCss(Document d) throws XPathExpressionException, IOException { InputStream is = null; try { XPath xp = xpf.newXPath(); XPathExpression xpe = xp.compile("//link[@type='text/css']/@href"); NodeList nl = (NodeList) xpe.evaluate(d, XPathConstants.NODESET); for (int i = 0; i < nl.getLength(); i++) { Attr a = (Attr) nl.item(i); String url = a.getValue(); URL u = new URL(url); is = new BufferedInputStream(u.openStream()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); parser.add(new String(baos.toByteArray(), "UTF-8")); Element linkNode = a.getOwnerElement(); Element parent = (Element) linkNode.getParentNode(); parent.removeChild(linkNode); IOUtils.closeQuietly(is); is = null; } } finally { IOUtils.closeQuietly(is); } } Code Sample 2: private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
11
Code Sample 1: public static void main(String[] args) throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.err.println("Could not listen on port: 4444."); System.exit(1); } Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.err.println("Accept failed."); System.exit(1); } DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; inputLine = in.readLine(); String dist_metric = in.readLine(); File outFile = new File("data.txt"); FileWriter outw = new FileWriter(outFile); outw.write(inputLine); outw.close(); File sample_coords = new File("sample_coords.txt"); sample_coords.delete(); File sp_coords = new File("sp_coords.txt"); sp_coords.delete(); try { System.out.println("Running python script..."); System.out.println("Command: " + "python l19test.py " + "\"" + dist_metric + "\""); Process pr = Runtime.getRuntime().exec("python l19test.py " + dist_metric); BufferedReader br = new BufferedReader(new InputStreamReader(pr.getErrorStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Process Exit Value: " + exitVal); System.out.println("done."); } catch (Exception e) { System.out.println("Unable to run python script for PCoA analysis"); } File myFile = new File("sp_coords.txt"); byte[] mybytearray = new byte[(new Long(myFile.length())).intValue()]; FileInputStream fis = new FileInputStream(myFile); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); for (int i = 0; i < myFile.length(); i++) { out.writeByte(fis.read()); } myFile = new File("sample_coords.txt"); mybytearray = new byte[(int) myFile.length()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); myFile = new File("evals.txt"); mybytearray = new byte[(new Long(myFile.length())).intValue()]; fis = new FileInputStream(myFile); fis.read(mybytearray); System.out.println("."); System.out.println(myFile.length()); out.writeInt((int) myFile.length()); out.write(mybytearray); out.flush(); out.close(); in.close(); clientSocket.close(); serverSocket.close(); } Code Sample 2: private void copyFileToPhotoFolder(File photo, String personId) { try { FileChannel in = new FileInputStream(photo).getChannel(); File dirServer = new File(Constants.PHOTO_DIR); if (!dirServer.exists()) { dirServer.mkdirs(); } File fileServer = new File(Constants.PHOTO_DIR + personId + ".jpg"); if (!fileServer.exists()) { fileServer.createNewFile(); } in.transferTo(0, in.size(), new FileOutputStream(fileServer).getChannel()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
11
Code Sample 1: private String generateHash(String key, String data) throws ChiropteraException { try { MessageDigest md = MessageDigest.getInstance(Constants.Connection.Auth.MD5); md.update(key.getBytes()); byte[] raw = md.digest(); String s = toHexString(raw); SecretKey skey = new SecretKeySpec(s.getBytes(), Constants.Connection.Auth.HMACMD5); Mac mac = Mac.getInstance(skey.getAlgorithm()); mac.init(skey); byte digest[] = mac.doFinal(data.getBytes()); String digestB64 = BaculaBase64.binToBase64(digest); return digestB64.substring(0, digestB64.length()); } catch (NoSuchAlgorithmException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } catch (InvalidKeyException e) { throw new ChiropteraException(Constants.Chiroptera.Errors.HASH, e.getMessage(), e); } } Code Sample 2: public static String getHash(String uri) throws NoSuchAlgorithmException { MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(uri.getBytes()); byte d[] = mDigest.digest(); StringBuffer hash = new StringBuffer(); for (int i = 0; i < d.length; i++) { hash.append(Integer.toHexString(0xFF & d[i])); } return hash.toString(); }
11
Code Sample 1: public void createIndex(File indexDir) throws SearchLibException, IOException { if (!indexDir.mkdir()) throw new SearchLibException("directory creation failed (" + indexDir + ")"); InputStream is = null; FileWriter target = null; for (String resource : resources) { String res = rootPath + '/' + resource; is = getClass().getResourceAsStream(res); if (is == null) is = getClass().getResourceAsStream("common" + '/' + resource); if (is == null) throw new SearchLibException("Unable to find resource " + res); try { File f = new File(indexDir, resource); if (f.getParentFile() != indexDir) f.getParentFile().mkdirs(); target = new FileWriter(f); IOUtils.copy(is, target); } finally { if (target != null) target.close(); if (is != null) is.close(); } } } Code Sample 2: private Document saveFile(Document document, File file) throws Exception { List<Preference> preferences = prefService.findAll(); if (preferences != null && !preferences.isEmpty()) { preference = preferences.get(0); } SimpleDateFormat sdf = new SimpleDateFormat(Constants.DATEFORMAT_YYYYMMDD); String repo = preference.getRepository(); Calendar calendar = Calendar.getInstance(); StringBuffer sbRepo = new StringBuffer(repo); sbRepo.append(File.separator); StringBuffer sbFolder = new StringBuffer(sdf.format(calendar.getTime())); sbFolder.append(File.separator).append(calendar.get(Calendar.HOUR_OF_DAY)); File folder = new File(sbRepo.append(sbFolder).toString()); if (!folder.exists()) { folder.mkdirs(); } FileChannel fcSource = null, fcDest = null; try { StringBuffer sbFile = new StringBuffer(folder.getAbsolutePath()); StringBuffer fname = new StringBuffer(document.getId().toString()); fname.append(".").append(document.getExt()); sbFile.append(File.separator).append(fname); fcSource = new FileInputStream(file).getChannel(); fcDest = new FileOutputStream(sbFile.toString()).getChannel(); fcDest.transferFrom(fcSource, 0, fcSource.size()); document.setLocation(sbFolder.toString()); documentService.save(document); } catch (FileNotFoundException notFoundEx) { log.error("saveFile file not found: " + document.getName(), notFoundEx); } catch (IOException ioEx) { log.error("saveFile IOException: " + document.getName(), ioEx); } finally { try { if (fcSource != null) { fcSource.close(); } if (fcDest != null) { fcDest.close(); } } catch (Exception e) { log.error(e.getMessage(), e); } } return document; }
11
Code Sample 1: public static void copyFile(File file, String pathExport) throws IOException { File out = new File(pathExport); FileChannel sourceChannel = new FileInputStream(file).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } Code Sample 2: private void zipFiles(File file, File[] fa) throws Exception { File f = new File(file, ALL_FILES_NAME); if (f.exists()) { f.delete(); f = new File(file, ALL_FILES_NAME); } ZipOutputStream zoutstrm = new ZipOutputStream(new FileOutputStream(f)); for (int i = 0; i < fa.length; i++) { ZipEntry zipEntry = new ZipEntry(fa[i].getName()); zoutstrm.putNextEntry(zipEntry); FileInputStream fr = new FileInputStream(fa[i]); byte[] buffer = new byte[1024]; int readCount = 0; while ((readCount = fr.read(buffer)) > 0) { zoutstrm.write(buffer, 0, readCount); } fr.close(); zoutstrm.closeEntry(); } zoutstrm.close(); log("created zip file: " + file.getName() + "/" + ALL_FILES_NAME); }
11
Code Sample 1: public static void copyFile(File src, File dest) throws IOException { FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest); FileChannel channelSrc = fis.getChannel(); FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } Code Sample 2: public void copyAffix(MailAffix affix, long mailId1, long mailId2) throws Exception { File file = new File(this.getResDir(mailId1) + affix.getAttachAlias()); if (file.exists()) { File file2 = new File(this.getResDir(mailId2) + affix.getAttachAlias()); if (!file2.exists()) { file2.createNewFile(); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file2)); BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); int read; while ((read = in.read()) != -1) { out.write(read); } out.flush(); in.close(); out.close(); } } else { log.debug(file.getAbsolutePath() + file.getName() + "�����ڣ������ļ�ʧ�ܣ���������"); } }
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: @Test public void testWriteAndRead() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwrite.txt"); RFileOutputStream out = new RFileOutputStream(file); out.write("test".getBytes("utf-8")); out.close(); RFileInputStream in = new RFileInputStream(file); byte[] buffer = new byte[4]; int readCount = in.read(buffer); in.close(); assertEquals(4, readCount); String resultRead = new String(buffer, "utf-8"); assertEquals("test", resultRead); } finally { server.stop(); } }
00
Code Sample 1: public int down(String downLoadUrl, String saveUrl) { int status = 1; long fileSize = 0; int len = 0; byte[] bt = new byte[1024]; RandomAccessFile raFile = null; long totalSize = 0; URL url = null; HttpURLConnection httpConn = null; BufferedInputStream bis = null; try { url = new URL(downLoadUrl); httpConn = (HttpURLConnection) url.openConnection(); if (httpConn.getHeaderField("Content-Length") == null) { status = 500; } else { totalSize = Long.parseLong(httpConn.getHeaderField("Content-Length")); System.out.println("文件大小:" + totalSize / 1000000 + " M"); httpConn.disconnect(); httpConn = (HttpURLConnection) url.openConnection(); fileSize = loadFileSize(saveUrl + BACK_SUFFIX); System.out.println("已下载:" + fileSize / 1000000 + " M"); httpConn.setRequestProperty("RANGE", "bytes=" + fileSize + "-"); httpConn.setRequestProperty("Accept", "image/gif,image/x-xbitmap,application/msword,*/*"); raFile = new RandomAccessFile(saveUrl + BACK_SUFFIX, "rw"); raFile.seek(fileSize); bis = new BufferedInputStream(httpConn.getInputStream()); while ((len = bis.read(bt)) > 0) { raFile.write(bt, 0, len); float progress = 0.f; float downSize = raFile.length(); progress = downSize / totalSize; System.out.println(progress * 100 + "%" + "\t\t" + downSize / 1000000 + "M"); } } } catch (FileNotFoundException e) { status = 404; } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (raFile != null) raFile.close(); } catch (IOException e) { e.printStackTrace(); } } if (loadFileSize(saveUrl + BACK_SUFFIX) == totalSize) { fileRename(saveUrl + BACK_SUFFIX, saveUrl); } return status; } Code Sample 2: private void RotaDraw(GeoPoint orig, GeoPoint dest, int color, MapView mapa) { StringBuilder urlString = new StringBuilder(); urlString.append("http://maps.google.com/maps?f=d&hl=en"); urlString.append("&saddr="); urlString.append(Double.toString((double) orig.getLatitudeE6() / 1.0E6)); urlString.append(","); urlString.append(Double.toString((double) orig.getLongitudeE6() / 1.0E6)); urlString.append("&daddr="); urlString.append(Double.toString((double) dest.getLatitudeE6() / 1.0E6)); urlString.append(","); urlString.append(Double.toString((double) dest.getLongitudeE6() / 1.0E6)); urlString.append("&ie=UTF8&0&om=0&output=kml"); Document doc = null; HttpURLConnection urlConnection = null; URL url = null; try { url = new URL(urlString.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.connect(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(urlConnection.getInputStream()); if (doc.getElementsByTagName("GeometryCollection").getLength() > 0) { String path = doc.getElementsByTagName("GeometryCollection").item(0).getFirstChild().getFirstChild().getFirstChild().getNodeValue(); Log.d("xxx", "path=" + path); String[] pairs = path.split(" "); String[] lngLat = pairs[0].split(","); GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); mapa.getOverlays().add(new CamadaGS(startGP, startGP, 1)); GeoPoint gp1; GeoPoint gp2 = startGP; for (int i = 1; i < pairs.length; i++) { lngLat = pairs[i].split(","); gp1 = gp2; gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); mapa.getOverlays().add(new CamadaGS(gp1, gp2, 2, color)); Log.d("xxx", "pair:" + pairs[i]); } mapa.getOverlays().add(new CamadaGS(dest, dest, 3)); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } }
11
Code Sample 1: private LinkedList<Datum> processDatum(Datum dataset) { ArrayList<Object[]> markerTestResults = new ArrayList<Object[]>(); ArrayList<Object[]> alleleEstimateResults = new ArrayList<Object[]>(); boolean hasAlleleNames = false; String blank = new String(""); MarkerPhenotypeAdapter theAdapter; if (dataset.getDataType().equals(MarkerPhenotype.class)) { theAdapter = new MarkerPhenotypeAdapter((MarkerPhenotype) dataset.getData()); } else theAdapter = new MarkerPhenotypeAdapter((Phenotype) dataset.getData()); int numberOfMarkers = theAdapter.getNumberOfMarkers(); if (numberOfMarkers == 0) { return calculateBLUEsFromPhenotypes(theAdapter, dataset.getName()); } int numberOfCovariates = theAdapter.getNumberOfCovariates(); int numberOfFactors = theAdapter.getNumberOfFactors(); int numberOfPhenotypes = theAdapter.getNumberOfPhenotypes(); int expectedIterations = numberOfPhenotypes * numberOfMarkers; int iterationsSofar = 0; int percentFinished = 0; File tempFile = null; File ftestFile = null; File blueFile = null; BufferedWriter ftestWriter = null; BufferedWriter BLUEWriter = null; String ftestHeader = "Trait\tMarker\tLocus\tLocus_pos\tChr\tChr_pos\tmarker_F\tmarker_p\tperm_p\tmarkerR2\tmarkerDF\tmarkerMS\terrorDF\terrorMS\tmodelDF\tmodelMS"; String BLUEHeader = "Trait\tMarker\tObs\tLocus\tLocus_pos\tChr\tChr_pos\tAllele\tEstimate"; if (writeOutputToFile) { String outputbase = outputName; if (outputbase.endsWith(".txt")) { int index = outputbase.lastIndexOf("."); outputbase = outputbase.substring(0, index); } String datasetNameNoSpace = dataset.getName().trim().replaceAll("\\ ", "_"); ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.txt"); int count = 0; while (ftestFile.exists()) { count++; ftestFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest" + count + ".txt"); } blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs.txt"); count = 0; while (blueFile.exists()) { count++; blueFile = new File(outputbase + "_" + datasetNameNoSpace + "_BLUEs" + count + ".txt"); } tempFile = new File(outputbase + "_" + datasetNameNoSpace + "_ftest.tmp"); try { if (permute) { ftestWriter = new BufferedWriter(new FileWriter(tempFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } else { ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(ftestHeader); ftestWriter.newLine(); } if (reportBLUEs) { BLUEWriter = new BufferedWriter(new FileWriter(blueFile)); BLUEWriter.write(BLUEHeader); BLUEWriter.newLine(); } } catch (IOException e) { myLogger.error("Failed to open file for output"); myLogger.error(e); return null; } } if (permute) { minP = new double[numberOfPhenotypes][numberOfPermutations]; for (int i = 0; i < numberOfPermutations; i++) { for (int j = 0; j < numberOfPhenotypes; j++) { minP[j][i] = 1; } } } for (int ph = 0; ph < numberOfPhenotypes; ph++) { double[] phenotypeData = theAdapter.getPhenotypeValues(ph); boolean[] missing = theAdapter.getMissingPhenotypes(ph); ArrayList<String[]> factorList = MarkerPhenotypeAdapterUtils.getFactorList(theAdapter, ph, missing); ArrayList<double[]> covariateList = MarkerPhenotypeAdapterUtils.getCovariateList(theAdapter, ph, missing); double[][] permutedData = null; if (permute) { permutedData = permuteData(phenotypeData, missing, factorList, covariateList, theAdapter); } for (int m = 0; m < numberOfMarkers; m++) { Object[] markerData = theAdapter.getMarkerValue(ph, m); boolean[] finalMissing = new boolean[missing.length]; System.arraycopy(missing, 0, finalMissing, 0, missing.length); MarkerPhenotypeAdapterUtils.updateMissing(finalMissing, theAdapter.getMissingMarkers(ph, m)); int[] nonmissingRows = MarkerPhenotypeAdapterUtils.getNonMissingIndex(finalMissing); int numberOfObs = nonmissingRows.length; double[] y = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) y[i] = phenotypeData[nonmissingRows[i]]; int firstMarkerAlleleEstimate = 1; ArrayList<ModelEffect> modelEffects = new ArrayList<ModelEffect>(); FactorModelEffect meanEffect = new FactorModelEffect(new int[numberOfObs], false); meanEffect.setID("mean"); modelEffects.add(meanEffect); if (numberOfFactors > 0) { for (int f = 0; f < numberOfFactors; f++) { String[] afactor = factorList.get(f); String[] factorLabels = new String[numberOfObs]; for (int i = 0; i < numberOfObs; i++) factorLabels[i] = afactor[nonmissingRows[i]]; FactorModelEffect fme = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(factorLabels), true, theAdapter.getFactorName(f)); modelEffects.add(fme); firstMarkerAlleleEstimate += fme.getNumberOfLevels() - 1; } } if (numberOfCovariates > 0) { for (int c = 0; c < numberOfCovariates; c++) { double[] covar = new double[numberOfObs]; double[] covariateData = covariateList.get(c); for (int i = 0; i < numberOfObs; i++) covar[i] = covariateData[nonmissingRows[i]]; modelEffects.add(new CovariateModelEffect(covar, theAdapter.getCovariateName(c))); firstMarkerAlleleEstimate++; } } ModelEffect markerEffect; boolean markerIsDiscrete = theAdapter.isMarkerDiscrete(m); ArrayList<Object> alleleNames = new ArrayList<Object>(); if (markerIsDiscrete) { Object[] markers = new Object[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markers[i] = markerData[nonmissingRows[i]]; int[] markerLevels = ModelEffectUtils.getIntegerLevels(markers, alleleNames); markerEffect = new FactorModelEffect(markerLevels, true, theAdapter.getMarkerName(m)); hasAlleleNames = true; } else { double[] markerdbl = new double[numberOfObs]; for (int i = 0; i < numberOfObs; i++) markerdbl[i] = ((Double) markerData[nonmissingRows[i]]).doubleValue(); markerEffect = new CovariateModelEffect(markerdbl, theAdapter.getMarkerName(m)); } int[] alleleCounts = markerEffect.getLevelCounts(); modelEffects.add(markerEffect); int markerEffectNumber = modelEffects.size() - 1; Identifier[] taxaSublist = new Identifier[numberOfObs]; Identifier[] taxa = theAdapter.getTaxa(ph); for (int i = 0; i < numberOfObs; i++) taxaSublist[i] = taxa[nonmissingRows[i]]; boolean areTaxaReplicated = containsDuplicates(taxaSublist); double[] markerSSdf = null, errorSSdf = null, modelSSdf = null; double F, p; double[] beta = null; if (areTaxaReplicated && markerIsDiscrete) { ModelEffect taxaEffect = new FactorModelEffect(ModelEffectUtils.getIntegerLevels(taxaSublist), true); modelEffects.add(taxaEffect); SweepFastNestedModel sfnm = new SweepFastNestedModel(modelEffects, y); double[] taxaSSdf = sfnm.getTaxaInMarkerSSdf(); double[] residualSSdf = sfnm.getErrorSSdf(); markerSSdf = sfnm.getMarkerSSdf(); errorSSdf = sfnm.getErrorSSdf(); modelSSdf = sfnm.getModelcfmSSdf(); F = markerSSdf[0] / markerSSdf[1] / taxaSSdf[0] * taxaSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], taxaSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sfnm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sfnm.getInverseOfXtX(), markerdf); } } else { SweepFastLinearModel sflm = new SweepFastLinearModel(modelEffects, y); modelSSdf = sflm.getModelcfmSSdf(); markerSSdf = sflm.getMarginalSSdf(markerEffectNumber); errorSSdf = sflm.getResidualSSdf(); F = markerSSdf[0] / markerSSdf[1] / errorSSdf[0] * errorSSdf[1]; try { p = LinearModelUtils.Ftest(F, markerSSdf[1], errorSSdf[1]); } catch (Exception e) { p = Double.NaN; } beta = sflm.getBeta(); int markerdf = (int) markerSSdf[1]; if (permute && markerdf > 0) { updatePermutationPValues(ph, permutedData, nonMissingIndex(missing, finalMissing), getXfromModelEffects(modelEffects), sflm.getInverseOfXtX(), markerdf); } } if (!filterOutput || p < maxp) { String traitname = theAdapter.getPhenotypeName(ph); if (traitname == null) traitname = blank; String marker = theAdapter.getMarkerName(m); if (marker == null) marker = blank; String locus = theAdapter.getLocusName(m); Integer site = new Integer(theAdapter.getLocusPosition(m)); String chrname = ""; Double chrpos = Double.NaN; if (hasMap) { int ndx = -1; ndx = myMap.getMarkerIndex(marker); if (ndx > -1) { chrname = myMap.getChromosome(ndx); chrpos = myMap.getGeneticPosition(ndx); } } Object[] result = new Object[16]; int col = 0; result[col++] = traitname; result[col++] = marker; result[col++] = locus; result[col++] = site; result[col++] = chrname; result[col++] = chrpos; result[col++] = new Double(F); result[col++] = new Double(p); result[col++] = Double.NaN; result[col++] = new Double(markerSSdf[0] / (modelSSdf[0] + errorSSdf[0])); result[col++] = new Double(markerSSdf[1]); result[col++] = new Double(markerSSdf[0] / markerSSdf[1]); result[col++] = new Double(errorSSdf[1]); result[col++] = new Double(errorSSdf[0] / errorSSdf[1]); result[col++] = new Double(modelSSdf[1]); result[col++] = new Double(modelSSdf[0] / modelSSdf[1]); if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int i = 1; i < 16; i++) sb.append("\t").append(result[i]); try { ftestWriter.write(sb.toString()); ftestWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { markerTestResults.add(result); } int numberOfMarkerAlleles = alleleNames.size(); if (numberOfMarkerAlleles == 0) numberOfMarkerAlleles++; for (int i = 0; i < numberOfMarkerAlleles; i++) { result = new Object[9]; result[0] = traitname; result[1] = marker; result[2] = new Integer(alleleCounts[i]); result[3] = locus; result[4] = site; result[5] = chrname; result[6] = chrpos; if (numberOfMarkerAlleles == 1) result[7] = ""; else result[7] = alleleNames.get(i); if (i == numberOfMarkerAlleles - 1) result[8] = 0.0; else result[8] = beta[firstMarkerAlleleEstimate + i]; if (writeOutputToFile) { StringBuilder sb = new StringBuilder(); sb.append(result[0]); for (int j = 1; j < 9; j++) sb.append("\t").append(result[j]); try { BLUEWriter.write(sb.toString()); BLUEWriter.newLine(); } catch (IOException e) { myLogger.error("Failed to write output to ftest file. Ending prematurely"); try { ftestWriter.flush(); BLUEWriter.flush(); } catch (Exception e1) { } myLogger.error(e); return null; } } else { alleleEstimateResults.add(result); } } } int tmpPercent = ++iterationsSofar * 100 / expectedIterations; if (tmpPercent > percentFinished) { percentFinished = tmpPercent; fireProgress(percentFinished); } } } fireProgress(0); if (writeOutputToFile) { try { ftestWriter.close(); BLUEWriter.close(); } catch (IOException e) { e.printStackTrace(); } } HashMap<String, Integer> traitnameMap = new HashMap<String, Integer>(); if (permute) { for (int ph = 0; ph < numberOfPhenotypes; ph++) { Arrays.sort(minP[ph]); traitnameMap.put(theAdapter.getPhenotypeName(ph), ph); } if (writeOutputToFile) { try { BufferedReader tempReader = new BufferedReader(new FileReader(tempFile)); ftestWriter = new BufferedWriter(new FileWriter(ftestFile)); ftestWriter.write(tempReader.readLine()); ftestWriter.newLine(); String input; String[] data; Pattern tab = Pattern.compile("\t"); while ((input = tempReader.readLine()) != null) { data = tab.split(input); String trait = data[0]; double pval = Double.parseDouble(data[7]); int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; data[8] = Double.toString((double) ndx / (double) numberOfPermutations); ftestWriter.write(data[0]); for (int i = 1; i < data.length; i++) { ftestWriter.write("\t"); ftestWriter.write(data[i]); } ftestWriter.newLine(); } tempReader.close(); ftestWriter.close(); tempFile.delete(); } catch (IOException e) { myLogger.error(e); } } else { for (Object[] result : markerTestResults) { String trait = result[0].toString(); double pval = (Double) result[7]; int ph = traitnameMap.get(trait); int ndx = Arrays.binarySearch(minP[ph], pval); if (ndx < 0) ndx = -ndx - 1; if (ndx == 0) ndx = 1; result[8] = new Double((double) ndx / (double) numberOfPermutations); } } } String[] columnLabels = new String[] { "Trait", "Marker", "Locus", "Locus_pos", "Chr", "Chr_pos", "marker_F", "marker_p", "perm_p", "markerR2", "markerDF", "markerMS", "errorDF", "errorMS", "modelDF", "modelMS" }; boolean hasMarkerNames = theAdapter.hasMarkerNames(); LinkedList<Integer> outputList = new LinkedList<Integer>(); outputList.add(0); if (hasMarkerNames) outputList.add(1); outputList.add(2); outputList.add(3); if (hasMap) { outputList.add(4); outputList.add(5); } outputList.add(6); outputList.add(7); if (permute) outputList.add(8); for (int i = 9; i < 16; i++) outputList.add(i); LinkedList<Datum> resultset = new LinkedList<Datum>(); int nrows = markerTestResults.size(); Object[][] table = new Object[nrows][]; int numberOfColumns = outputList.size(); String[] colnames = new String[numberOfColumns]; int count = 0; for (Integer ndx : outputList) colnames[count++] = columnLabels[ndx]; for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = markerTestResults.get(i); count = 0; for (Integer ndx : outputList) table[i][count++] = result[ndx]; } StringBuilder tableName = new StringBuilder("GLM_marker_test_"); tableName.append(dataset.getName()); StringBuilder comments = new StringBuilder("Tests of Marker-Phenotype Association"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + ftestFile.getPath()); } TableReport markerTestReport = new SimpleTableReport("Marker Test", colnames, table); resultset.add(new Datum(tableName.toString(), markerTestReport, comments.toString())); int[] outputIndex; columnLabels = new String[] { "Trait", "Marker", "Obs", "Locus", "Locus_pos", "Chr", "Chr_pos", "Allele", "Estimate" }; if (hasAlleleNames) { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 7, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 7, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 7, 8 }; } } else { if (hasMarkerNames && hasMap) { outputIndex = new int[] { 0, 1, 2, 3, 4, 5, 6, 8 }; } else if (hasMarkerNames) { outputIndex = new int[] { 0, 1, 2, 3, 4, 8 }; } else if (hasMap) { outputIndex = new int[] { 0, 2, 3, 4, 5, 6, 8 }; } else { outputIndex = new int[] { 0, 2, 3, 4, 8 }; } } nrows = alleleEstimateResults.size(); table = new Object[nrows][]; numberOfColumns = outputIndex.length; colnames = new String[numberOfColumns]; for (int j = 0; j < numberOfColumns; j++) { colnames[j] = columnLabels[outputIndex[j]]; } for (int i = 0; i < nrows; i++) { table[i] = new Object[numberOfColumns]; Object[] result = alleleEstimateResults.get(i); for (int j = 0; j < numberOfColumns; j++) { table[i][j] = result[outputIndex[j]]; } } tableName = new StringBuilder("GLM allele estimates for "); tableName.append(dataset.getName()); comments = new StringBuilder("Marker allele effect estimates\n"); comments.append("GLM: fixed effect linear model\n"); comments.append("Data set: ").append(dataset.getName()); comments.append("\nmodel: trait = mean"); for (int i = 0; i < theAdapter.getNumberOfFactors(); i++) { comments.append(" + "); comments.append(theAdapter.getFactorName(i)); } for (int i = 0; i < theAdapter.getNumberOfCovariates(); i++) { comments.append(" + "); comments.append(theAdapter.getCovariateName(i)); } comments.append(" + marker"); if (writeOutputToFile) { comments.append("\nOutput written to " + blueFile.getPath()); } TableReport alleleEstimateReport = new SimpleTableReport("Allele Estimates", colnames, table); resultset.add(new Datum(tableName.toString(), alleleEstimateReport, comments.toString())); fireProgress(0); return resultset; } Code Sample 2: private void copy(FileInfo inputFile, FileInfo outputFile) { try { FileReader in = new FileReader(inputFile.file); FileWriter out = new FileWriter(outputFile.file); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); outputFile.file.setLastModified(inputFile.lastModified); } catch (IOException e) { } }
11
Code Sample 1: private void getRandomGUID(boolean secure) { MessageDigest md5 = 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 = 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(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { int b = array[j] & 0xFF; if (b < 0x10) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } } Code Sample 2: public boolean authenticate() { if (empresaFeta == null) empresaFeta = new AltaEmpresaBean(); log.info("authenticating {0}", credentials.getUsername()); boolean bo; try { String passwordEncriptat = credentials.getPassword(); MessageDigest m = MessageDigest.getInstance("MD5"); m.update(passwordEncriptat.getBytes(), 0, passwordEncriptat.length()); passwordEncriptat = new BigInteger(1, m.digest()).toString(16); Query q = entityManager.createQuery("select usuari from Usuaris usuari where usuari.login=? and usuari.password=?"); q.setParameter(1, credentials.getUsername()); q.setParameter(2, passwordEncriptat); Usuaris usuari = (Usuaris) q.getSingleResult(); bo = (usuari != null); if (bo) { if (usuari.isEsAdministrador()) { identity.addRole("admin"); } else { carregaDadesEmpresa(); log.info("nom de l'empresa: " + empresaFeta.getInstance().getNom()); } } } catch (Throwable t) { log.error(t); bo = false; } log.info("L'usuari {0} s'ha identificat bé? : {1} ", credentials.getUsername(), bo ? "si" : "no"); return bo; }
11
Code Sample 1: public void saveUploadFile(String toFileName, UploadFile uploadFile, SysConfig sysConfig) throws IOException { OutputStream bos = new FileOutputStream(toFileName); IOUtils.copy(uploadFile.getInputStream(), bos); if (sysConfig.isAttachImg(uploadFile.getFileName()) && sysConfig.getReduceAttachImg() == 1) { ImgUtil.reduceImg(toFileName, toFileName + Constant.IMG_SMALL_FILEPREFIX, sysConfig.getReduceAttachImgSize(), sysConfig.getReduceAttachImgSize(), 1); } } 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 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 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) { } } } }
11
Code Sample 1: private void unzipResource(final String resourceName, final File targetDirectory) throws IOException { 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; } } } } Code Sample 2: public void write(File file) throws Exception { if (medooFile != null) { if (!medooFile.renameTo(file)) { BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(medooFile)); out = new BufferedOutputStream(new FileOutputStream(file)); IOUtils.copy(in, out); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } } } else { throw new FileUploadException("Cannot write uploaded file to disk!"); } }
00
Code Sample 1: public static void main(String[] args) { try { FTPClient p = new FTPClient(); p.connect("url"); p.login("login", "pass"); int sendCommand = p.sendCommand("SYST"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PWD"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("NOOP"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); sendCommand = p.sendCommand("PASV"); System.out.println("TryMe.main() - " + sendCommand + " (sendCommand)"); p.changeWorkingDirectory("/"); try { printDir(p, "/"); } catch (Exception e) { e.printStackTrace(); } p.logout(); p.disconnect(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } Code Sample 2: public void downloadTranslationsAndReload() { File languages = new File(this.translationsFile); try { URL languageURL = new URL(languageServer); InputStream is = languageURL.openStream(); OutputStream os = new FileOutputStream(languages); byte[] read = new byte[512000]; int bytesRead = 0; do { bytesRead = is.read(read); if (bytesRead > 0) { os.write(read, 0, bytesRead); } } while (bytesRead > 0); is.close(); os.close(); this.loadTranslations(); } catch (Exception e) { System.err.println("Remote languages file not found!"); if (languages.exists()) { try { XMLDecoder loader = new XMLDecoder(new FileInputStream(languages)); this.languages = (Hashtable) loader.readObject(); loader.close(); } catch (Exception ex) { ex.printStackTrace(); this.languages.put(naiveLanguage, new Hashtable()); } } else this.languages.put(naiveLanguage, new Hashtable()); } }
11
Code Sample 1: public static void copyFile(File source, File destination) { if (!source.exists()) { return; } if ((destination.getParentFile() != null) && (!destination.getParentFile().exists())) { destination.getParentFile().mkdirs(); } try { FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(destination).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } Code Sample 2: public void copyFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; Closer c = new Closer(); try { source = c.register(new FileInputStream(sourceFile).getChannel()); destination = c.register(new FileOutputStream(destFile).getChannel()); destination.transferFrom(source, 0, source.size()); } catch (IOException e) { c.doNotThrow(); throw e; } finally { c.closeAll(); } }
11
Code Sample 1: public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; } Code Sample 2: protected static String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); URLConnection c = url.openConnection(); c.setConnectTimeout(2000); IOUtils.copy(c.getInputStream(), output); return output.toString(); }
00
Code Sample 1: public static void main(String[] args) { FTPClient client = new FTPClient(); FileInputStream fis = null; try { client.connect("192.168.1.10"); client.login("a", "123456"); String filename = "D:\\DHTH5CLT\\HK3\\Ung dung phan tan\\FTP_JAVA\\FTP_DETAI\\FTP\\src\\DemoFTP\\filename\\5s.txt"; fis = new FileInputStream(filename); client.storeFile(filename, fis); client.logout(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } client.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } Code Sample 2: public static void copy(File src, File dest) throws IOException { if (!src.exists()) { throw new IOException(StaticUtils.format(OStrings.getString("LFC_ERROR_FILE_DOESNT_EXIST"), new Object[] { src.getAbsolutePath() })); } FileInputStream fis = new FileInputStream(src); dest.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(dest); byte[] b = new byte[BUFSIZE]; int readBytes; while ((readBytes = fis.read(b)) > 0) fos.write(b, 0, readBytes); fis.close(); fos.close(); }
11
Code Sample 1: public 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: @Test public void testCopy_inputStreamToWriter_Encoding_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, "UTF8"); fail(); } catch (NullPointerException ex) { } }
00
Code Sample 1: private boolean doDelete(String identifier) throws IOException, MalformedURLException { URL url = new URL(baseurl.toString() + "/" + identifier); HttpURLConnection huc = (HttpURLConnection) (url.openConnection()); huc.setRequestMethod("DELETE"); huc.connect(); if (huc.getResponseCode() == 200) { return true; } else return false; } Code Sample 2: public static void createBackup() { String workspacePath = Workspace.INSTANCE.getWorkspace(); if (workspacePath.length() == 0) return; workspacePath += "/"; String backupPath = workspacePath + "Backup"; File directory = new File(backupPath); if (!directory.exists()) directory.mkdirs(); String dateString = DataUtils.DateAndTimeOfNowAsLocalString(); dateString = dateString.replace(" ", "_"); dateString = dateString.replace(":", ""); backupPath += "/Backup_" + dateString + ".zip"; ArrayList<String> backupedFiles = new ArrayList<String>(); backupedFiles.add("Database/Database.properties"); backupedFiles.add("Database/Database.script"); FileInputStream in; byte[] data = new byte[1024]; int read = 0; try { ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(backupPath)); zip.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < backupedFiles.size(); i++) { String backupedFile = backupedFiles.get(i); try { File inFile = new File(workspacePath + backupedFile); if (inFile.exists()) { in = new FileInputStream(workspacePath + backupedFile); if (in != null) { ZipEntry entry = new ZipEntry(backupedFile); zip.putNextEntry(entry); while ((read = in.read(data, 0, 1024)) != -1) zip.write(data, 0, read); zip.closeEntry(); in.close(); } } } catch (Exception e) { Logger.logError(e, "Error during file backup:" + backupedFile); } } zip.close(); } catch (IOException ex) { Logger.logError(ex, "Error during backup"); } }
00
Code Sample 1: @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { PrintWriter writer = null; InputStream is = null; FileOutputStream fos = null; try { writer = response.getWriter(); } catch (IOException ex) { log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } String filename = request.getHeader("X-File-Name"); try { is = request.getInputStream(); fos = new FileOutputStream(new File(targetPath + filename)); IOUtils.copy(is, fos); response.setStatus(HttpServletResponse.SC_OK); writer.print("{success: true}"); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); writer.print("{success: false}"); log(OctetStreamReader.class.getName() + "has thrown an exception: " + ex.getMessage()); } finally { try { fos.close(); is.close(); } catch (IOException ignored) { } } writer.flush(); writer.close(); } Code Sample 2: private static String scramble(String text) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(text.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (byte b : md.digest()) sb.append(Integer.toString(b & 0xFF, 16)); return sb.toString(); } catch (UnsupportedEncodingException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } }
00
Code Sample 1: public void backup(File source) throws BackupException { try { int index = source.getAbsolutePath().lastIndexOf("."); if (index == -1) return; File dest = new File(source.getAbsolutePath().substring(0, index) + ".bak"); FileChannel srcChannel = new FileInputStream(source).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (Exception ex) { throw new BackupException(ex.getMessage(), ex, source); } } Code Sample 2: static void test() throws SQLException { Connection conn = null; Statement st = null; ResultSet rs = null; Savepoint sp = null; try { conn = JdbcUtils.getConnection(); conn.setAutoCommit(false); st = conn.createStatement(); String sql = "update user set money=money-10 where id=1"; st.executeUpdate(sql); sp = conn.setSavepoint(); sql = "update user set money=money-10 where id=3"; st.executeUpdate(sql); sql = "select money from user where id=2"; rs = st.executeQuery(sql); float money = 0.0f; if (rs.next()) { money = rs.getFloat("money"); } if (money > 300) throw new RuntimeException("�Ѿ��������ֵ��"); sql = "update user set money=money+10 where id=2"; st.executeUpdate(sql); conn.commit(); } catch (RuntimeException e) { if (conn != null && sp != null) { conn.rollback(sp); conn.commit(); } throw e; } catch (SQLException e) { if (conn != null) conn.rollback(); throw e; } finally { JdbcUtils.free(rs, st, conn); } }