label
int64
0
1
func1
stringlengths
173
53.1k
func2
stringlengths
173
53.1k
id
int64
0
901k
1
public static void joinFiles(FileValidator validator, File target, File[] sources) { FileOutputStream fos = null; try { if (!validator.verifyFile(target)) return; fos = new FileOutputStream(target); FileInputStream fis = null; byte[] bytes = new byte[512]; for (int i = 0; i < sources.length; i++) { fis = new FileInputStream(sources[i]); int nbread = 0; try { while ((nbread = fis.read(bytes)) > -1) { fos.write(bytes, 0, nbread); } } catch (IOException ioe) { JOptionPane.showMessageDialog(null, ioe, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { fis.close(); } } } catch (Exception e) { JOptionPane.showMessageDialog(null, e, i18n.getString("Failure"), JOptionPane.ERROR_MESSAGE); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } } }
private void prepareJobFile(ZipEntryRef zer, String nodeDir, String reportDir, Set<ZipEntryRef> statusZers) throws Exception { String jobDir = nodeDir + File.separator + "job_" + zer.getUri(); if (!isWorkingDirectoryValid(jobDir)) { throw new Exception("Cannot acces to " + jobDir); } File f = new File(jobDir + File.separator + "result.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to result file " + f.getAbsolutePath()); } String fcopyName = reportDir + File.separator + zer.getName() + ".xml"; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); zer.setUri(fcopyName); f = new File(jobDir + File.separator + "status.xml"); if (!f.exists() || !f.isFile() || !f.canRead()) { throw new Exception("Cannot acces to status file " + f.getAbsolutePath()); } fcopyName = reportDir + File.separator + zer.getName() + "_status.xml"; bis = new BufferedInputStream(new FileInputStream(f)); bos = new BufferedOutputStream(new FileOutputStream(fcopyName)); IOUtils.copy(bis, bos); bis.close(); bos.close(); statusZers.add(new ZipEntryRef(ZipEntryRef.JOB, zer.getName(), fcopyName)); }
600
1
private void copyFromStdin(Path dst, FileSystem dstFs) throws IOException { if (dstFs.isDirectory(dst)) { throw new IOException("When source is stdin, destination must be a file."); } if (dstFs.exists(dst)) { throw new IOException("Target " + dst.toString() + " already exists."); } FSDataOutputStream out = dstFs.create(dst); try { IOUtils.copyBytes(System.in, out, getConf(), false); } finally { out.close(); } }
private static void copyFile(File source, File dest, boolean visibleFilesOnly) throws IOException { if (visibleFilesOnly && isHiddenOrDotFile(source)) { return; } if (dest.exists()) { System.err.println("Destination File Already Exists: " + dest); } FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); in.transferTo(0, in.size(), out); } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } }
601
1
private void setInlineXML(Entry entry, DatastreamXMLMetadata ds) throws UnsupportedEncodingException, StreamIOException { String content; if (m_obj.hasContentModel(Models.SERVICE_DEPLOYMENT_3_0) && (ds.DatastreamID.equals("SERVICE-PROFILE") || ds.DatastreamID.equals("WSDL"))) { content = DOTranslationUtility.normalizeInlineXML(new String(ds.xmlContent, m_encoding), m_transContext); } else { content = new String(ds.xmlContent, m_encoding); } if (m_format.equals(ATOM_ZIP1_1)) { String name = ds.DSVersionID + ".xml"; try { m_zout.putNextEntry(new ZipEntry(name)); InputStream is = new ByteArrayInputStream(content.getBytes(m_encoding)); IOUtils.copy(is, m_zout); m_zout.closeEntry(); is.close(); } catch (IOException e) { throw new StreamIOException(e.getMessage(), e); } IRI iri = new IRI(name); entry.setSummary(ds.DSVersionID); entry.setContent(iri, ds.DSMIME); } else { entry.setContent(content, ds.DSMIME); } }
private static void downloadFile(URL url, File destFile) throws Exception { try { URLConnection urlConnection = url.openConnection(); File tmpFile = null; try { tmpFile = File.createTempFile("remoteLib_", null); InputStream in = null; FileOutputStream out = null; try { in = urlConnection.getInputStream(); out = new FileOutputStream(tmpFile); IOUtils.copy(in, out); } finally { if (out != null) { out.close(); } if (in != null) { in.close(); } } FileUtils.copyFile(tmpFile, destFile); } finally { if (tmpFile != null) { tmpFile.delete(); } } } catch (Exception ex) { throw new RuntimeException("Could not download URL: " + url, ex); } }
602
1
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
public void actionPerformed(ActionEvent evt) { try { File tempFile = new File("/tmp/controler.xml"); File f = new File("/tmp/controler-temp.xml"); BufferedInputStream copySource = new BufferedInputStream(new FileInputStream(tempFile)); BufferedOutputStream copyDestination = new BufferedOutputStream(new FileOutputStream(f)); int read = 0; while (read != -1) { read = copySource.read(buffer, 0, BUFFER_SIZE); if (read != -1) { copyDestination.write(buffer, 0, read); } } copyDestination.write(new String("</log>\n").getBytes()); copySource.close(); copyDestination.close(); XMLParser parser = new XMLParser("Controler"); parser.parse(f); f.delete(); } catch (IOException ex) { System.out.println("An error occured during the file copy!"); } }
603
1
@HttpAction(name = "map.saveOrUpdate", method = { HttpAction.Method.post }, responseType = "text/plain") @HttpAuthentication(method = { HttpAuthentication.Method.WSSE }) public String saveOrUpdate(FileItem file, User user, MapOriginal map) throws HttpRpcException { File tmpFile; GenericDAO<MapOriginal> mapDao = DAOFactory.createDAO(MapOriginal.class); try { assert (file != null); String jobid = null; if (file.getContentType().startsWith("image/")) { tmpFile = File.createTempFile("gmap", "img"); OutputStream out = new FileOutputStream(tmpFile); IOUtils.copy(file.getInputStream(), out); out.flush(); out.close(); map.setState(MapOriginal.MapState.UPLOAD); map.setUser(user); map.setMapPath(tmpFile.getPath()); map.setThumbnailUrl("/map/inproc.gif"); map.setMimeType(file.getContentType()); mapDao.saveOrUpdate(map); jobid = PoolFactory.getClientPool().put(map, TaskState.STATE_MO_FINISH, MapOverrideStrategy.class); } return jobid; } catch (IOException e) { logger.error(e); throw ERROR_INTERNAL; } catch (DAOException e) { logger.error(e); throw ERROR_INTERNAL; } }
@Override public void actionPerformed(ActionEvent e) { if (copiedFiles_ != null) { File[] tmpFiles = new File[copiedFiles_.length]; File tmpDir = new File(Settings.getPropertyString(ConstantKeys.project_dir), "tmp/"); tmpDir.mkdirs(); for (int i = copiedFiles_.length - 1; i >= 0; i--) { Frame f = FrameManager.getInstance().getFrameAtIndex(i); try { File in = f.getFile(); File out = new File(tmpDir, f.getFile().getName()); FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); tmpFiles[i] = out; } catch (IOException e1) { e1.printStackTrace(); } } try { FrameManager.getInstance().insertFrames(getTable().getSelectedRow(), FrameManager.INSERT_TYPE.MOVE, tmpFiles); } catch (IOException e1) { e1.printStackTrace(); } } }
604
0
public static void copy(String fromFileName, String toFileName) throws IOException { File fromFile = new File(fromFileName); File toFile = new File(toFileName); if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFileName); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFileName); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFileName); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFileName); System.out.print("Overwrite existing file " + toFile.getName() + "? (Y/N): "); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
public static String loadSite(String spec) throws IOException { URL url = new URL(spec); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String output = ""; String str; while ((str = in.readLine()) != null) { output += str + "\n"; } in.close(); return output; }
605
0
public static boolean copyfile(String file0, String file1) { try { File f0 = new File(file0); File f1 = new File(file1); FileInputStream in = new FileInputStream(f0); FileOutputStream out = new FileOutputStream(f1); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); in = null; out = null; return true; } catch (Exception e) { return false; } }
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; }
606
1
protected String insertCommand(String command) throws ServletException { String digest; try { MessageDigest md = MessageDigest.getInstance(m_messagedigest_algorithm); md.update(command.getBytes()); byte bytes[] = new byte[20]; m_random.nextBytes(bytes); md.update(bytes); digest = bytesToHex(md.digest()); } catch (NoSuchAlgorithmException e) { throw new ServletException("NoSuchAlgorithmException while " + "attempting to generate graph ID: " + e); } String id = System.currentTimeMillis() + "-" + digest; m_map.put(id, command); return id; }
public NodeId generateTopicId(String topicName) { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA"); } catch (NoSuchAlgorithmException e) { System.err.println("No SHA support!"); } md.update(topicName.getBytes()); byte[] digest = md.digest(); NodeId newId = new NodeId(digest); return newId; }
607
0
public String hmacSHA256(String message, byte[] key) { MessageDigest sha256 = null; try { sha256 = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new java.lang.AssertionError(this.getClass().getName() + ".hmacSHA256(): SHA-256 algorithm not found!"); } if (key.length > 64) { sha256.update(key); key = sha256.digest(); sha256.reset(); } byte block[] = new byte[64]; for (int i = 0; i < key.length; ++i) block[i] = key[i]; for (int i = key.length; i < block.length; ++i) block[i] = 0; for (int i = 0; i < 64; ++i) block[i] ^= 0x36; sha256.update(block); try { sha256.update(message.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new java.lang.AssertionError("ITunesU.hmacSH256(): UTF-8 encoding not supported!"); } byte[] hash = sha256.digest(); sha256.reset(); for (int i = 0; i < 64; ++i) block[i] ^= (0x36 ^ 0x5c); sha256.update(block); sha256.update(hash); hash = sha256.digest(); char[] hexadecimals = new char[hash.length * 2]; for (int i = 0; i < hash.length; ++i) { for (int j = 0; j < 2; ++j) { int value = (hash[i] >> (4 - 4 * j)) & 0xf; char base = (value < 10) ? ('0') : ('a' - 10); hexadecimals[i * 2 + j] = (char) (base + value); } } return new String(hexadecimals); }
private static void zip(ZipArchiveOutputStream zos, File efile, String base) throws IOException { if (efile.isDirectory()) { File[] lf = efile.listFiles(); base = base + File.separator + efile.getName(); for (File file : lf) { zip(zos, file, base); } } else { ZipArchiveEntry entry = new ZipArchiveEntry(efile, base + File.separator + efile.getName()); zos.setEncoding("utf-8"); zos.putArchiveEntry(entry); InputStream is = new FileInputStream(efile); IOUtils.copy(is, zos); is.close(); zos.closeArchiveEntry(); } }
608
1
public boolean authenticate(String userName, String loginPassword) { if (!systemConfigManager.getBool("ldap", "authEnable")) { return false; } String ldapName = userName; AkteraUser user = userDAO.findUserByName(userName); if (user != null && StringTools.isNotTrimEmpty(user.getLdapName())) { ldapName = user.getLdapName(); } String server = systemConfigManager.getString("ldap", "authHost"); if (StringTools.isTrimEmpty(server)) { return false; } int port = NumberTools.toInt(systemConfigManager.get("ldap", "authPort"), 389); String type = StringTools.trim(systemConfigManager.getString("ldap", "authType")); String baseDn = StringTools.trim(systemConfigManager.getString("ldap", "authBaseDn")); String userDn = StringTools.trim(systemConfigManager.getString("ldap", "authUserDn")); String password = StringTools.trim(systemConfigManager.getString("ldap", "authPassword")); String query = StringTools.trim(systemConfigManager.getString("ldap", "authQuery")); String bindDn = StringTools.trim(systemConfigManager.getString("ldap", "authBindDn")); String passwordAttributeName = StringTools.trim(systemConfigManager.getString("ldap", "authPasswordAttributeName")); Map<String, Object> params = new HashMap<String, Object>(); params.put("userName", userName); params.put("ldapName", ldapName); params.put("loginName", StringTools.isTrimEmpty(ldapName) ? userName : ldapName); query = StringTools.replaceTemplate(query, params); bindDn = StringTools.replaceTemplate(bindDn, params); Hashtable<String, Object> env = new Hashtable<String, Object>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://" + server + ":" + port + "/" + baseDn); env.put(Context.SECURITY_AUTHENTICATION, "simple"); if ("ldapAuthBind".equals(type)) { env.put(Context.SECURITY_PRINCIPAL, bindDn); env.put(Context.SECURITY_CREDENTIALS, loginPassword); try { DirContext ctx = new InitialDirContext(env); try { ctx.close(); } catch (Exception ignored) { } return true; } catch (Exception ignored) { return false; } } if (StringTools.isTrimEmpty(userDn) || StringTools.isTrimEmpty(password)) { return false; } env.put(Context.SECURITY_PRINCIPAL, userDn); env.put(Context.SECURITY_CREDENTIALS, password); DirContext ctx = null; NamingEnumeration<SearchResult> results = null; try { ctx = new InitialDirContext(env); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); results = ctx.search("", query, controls); if (results.hasMore()) { SearchResult searchResult = results.next(); Attributes attributes = searchResult.getAttributes(); if (attributes.get(passwordAttributeName) == null) { return false; } String pass = new String((byte[]) attributes.get(passwordAttributeName).get()); if (pass.startsWith("{SHA}") || pass.startsWith("{MD5}")) { String method = pass.substring(1, pass.indexOf('}')); MessageDigest digest = MessageDigest.getInstance(method); digest.update(loginPassword.getBytes(), 0, loginPassword.length()); if (pass.equals("{" + method + "}" + Base64.encode(digest.digest()))) { return true; } } else { if (pass.equals(loginPassword)) { return true; } } } } catch (Exception x) { } finally { if (results != null) { try { results.close(); } catch (Exception e) { } } if (ctx != null) { try { ctx.close(); } catch (Exception e) { } } } return false; }
public static String generateGuid(boolean secure) { MessageDigest md5 = null; String valueBeforeMD5 = null; String valueAfterMD5 = null; StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { System.out.println("Error: " + e); } try { long time = System.currentTimeMillis(); long rand = 0L; if (secure) rand = mySecureRand.nextLong(); else rand = myRand.nextLong(); sbValueBeforeMD5.append(s_id); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(":"); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); byte array[] = md5.digest(); StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; j++) { int b = array[j] & 0xff; if (b < 16) sb.append('0'); sb.append(Integer.toHexString(b)); } valueAfterMD5 = sb.toString(); } catch (Exception e) { System.out.println("Error:" + e); } String raw = valueAfterMD5.toUpperCase(); StringBuffer sb = new StringBuffer(); sb.append(raw.substring(0, 8)); sb.append("-"); sb.append(raw.substring(8, 12)); sb.append("-"); sb.append(raw.substring(12, 16)); sb.append("-"); sb.append(raw.substring(16, 20)); sb.append("-"); sb.append(raw.substring(20)); return sb.toString(); }
609
1
public XmldbURI createFile(String newName, InputStream is, Long length, String contentType) throws IOException, PermissionDeniedException, CollectionDoesNotExistException { if (LOG.isDebugEnabled()) LOG.debug("Create '" + newName + "' in '" + xmldbUri + "'"); XmldbURI newNameUri = XmldbURI.create(newName); MimeType mime = MimeTable.getInstance().getContentTypeFor(newName); if (mime == null) { mime = MimeType.BINARY_TYPE; } DBBroker broker = null; Collection collection = null; BufferedInputStream bis = new BufferedInputStream(is); VirtualTempFile vtf = new VirtualTempFile(); BufferedOutputStream bos = new BufferedOutputStream(vtf); IOUtils.copy(bis, bos); bis.close(); bos.close(); vtf.close(); if (mime.isXMLType() && vtf.length() == 0L) { if (LOG.isDebugEnabled()) LOG.debug("Creating dummy XML file for null resource lock '" + newNameUri + "'"); vtf = new VirtualTempFile(); IOUtils.write("<null_resource/>", vtf); vtf.close(); } TransactionManager transact = brokerPool.getTransactionManager(); Txn txn = transact.beginTransaction(); try { broker = brokerPool.get(subject); collection = broker.openCollection(xmldbUri, Lock.WRITE_LOCK); if (collection == null) { LOG.debug("Collection " + xmldbUri + " does not exist"); transact.abort(txn); throw new CollectionDoesNotExistException(xmldbUri + ""); } if (mime.isXMLType()) { if (LOG.isDebugEnabled()) LOG.debug("Inserting XML document '" + mime.getName() + "'"); VirtualTempFileInputSource vtfis = new VirtualTempFileInputSource(vtf); IndexInfo info = collection.validateXMLResource(txn, broker, newNameUri, vtfis); DocumentImpl doc = info.getDocument(); doc.getMetadata().setMimeType(mime.getName()); collection.store(txn, broker, info, vtfis, false); } else { if (LOG.isDebugEnabled()) LOG.debug("Inserting BINARY document '" + mime.getName() + "'"); InputStream fis = vtf.getByteStream(); bis = new BufferedInputStream(fis); DocumentImpl doc = collection.addBinaryResource(txn, broker, newNameUri, bis, mime.getName(), length.longValue()); bis.close(); } transact.commit(txn); if (LOG.isDebugEnabled()) LOG.debug("Document created sucessfully"); } catch (EXistException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (TriggerException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (SAXException e) { LOG.error(e); transact.abort(txn); throw new IOException(e); } catch (LockException e) { LOG.error(e); transact.abort(txn); throw new PermissionDeniedException(xmldbUri + ""); } catch (IOException e) { LOG.error(e); transact.abort(txn); throw e; } catch (PermissionDeniedException e) { LOG.error(e); transact.abort(txn); throw e; } finally { if (vtf != null) { vtf.delete(); } if (collection != null) { collection.release(Lock.WRITE_LOCK); } brokerPool.release(broker); if (LOG.isDebugEnabled()) LOG.debug("Finished creation"); } XmldbURI newResource = xmldbUri.append(newName); return newResource; }
private void copyFile(File sourceFile, File destFile) throws IOException { if (log.isDebugEnabled()) { log.debug("CopyFile : Source[" + sourceFile.getAbsolutePath() + "] Dest[" + destFile.getAbsolutePath() + "]"); } 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(); } } }
610
1
public boolean load() { if (getFilename() != null && getFilename().length() > 0) { try { File file = new File(PreferencesManager.getDirectoryLocation("macros") + File.separator + getFilename()); URL url = file.toURL(); InputStreamReader isr = new InputStreamReader(url.openStream()); BufferedReader br = new BufferedReader(isr); String line = br.readLine(); String macro_text = ""; while (line != null) { macro_text = macro_text.concat(line); line = br.readLine(); if (line != null) { macro_text = macro_text.concat(System.getProperty("line.separator")); } } code = macro_text; } catch (Exception e) { System.err.println("Exception at StoredMacro.load(): " + e.toString()); return false; } } return true; }
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
611
0
public void doUpdate(String version) { try { final String hyperlink_url = "http://xnavigator.sourceforge.net/dist/"; JFrame updateInfoFrame = null; try { JPanel panel = new JPanel(); panel.setLayout(null); panel.setBackground(new java.awt.Color(255, 255, 255)); panel.setBorder(new TitledBorder("")); ClassLoader cl = this.getClass().getClassLoader(); int BORDER_TOP = 10; int PANEL_WIDTH = 400; int TEXT_WIDTH = 360; int TEXT_HEIGHT = 50; int TEXT_LEFT = 20; int y = BORDER_TOP; I3Label title = new I3Label("XNavigator Update"); title.setBounds(30, y, 350, 25); panel.add(title); ImageIcon splash3 = new ImageIcon(Toolkit.getDefaultToolkit().getImage(cl.getResource("resources/splash3.jpg"))); JButton left = new JButton(splash3); left.setBounds(20, y += 30, 350, 235); left.setBorder(null); left.setFocusPainted(false); panel.add(left); JTextPane informText = new JTextPane(); informText.setLayout(null); informText.setBounds(TEXT_LEFT, y += 235, TEXT_WIDTH, TEXT_HEIGHT); informText.setBackground(new java.awt.Color(255, 255, 255)); informText.setEditable(false); informText.setFocusable(false); panel.add(informText); JTextPane progressText = new JTextPane(); progressText.setLayout(null); progressText.setBounds(TEXT_LEFT, y += TEXT_HEIGHT, TEXT_WIDTH, TEXT_HEIGHT); progressText.setBackground(new java.awt.Color(255, 255, 255)); progressText.setEditable(false); progressText.setFocusable(false); panel.add(progressText); updateInfoFrame = new JFrame(); updateInfoFrame.setUndecorated(false); updateInfoFrame.setTitle("XNavigator Update"); updateInfoFrame.setSize(400, 430); updateInfoFrame.getContentPane().add(panel); updateInfoFrame.setVisible(true); updateInfoFrame.setEnabled(true); updateInfoFrame.setResizable(false); updateInfoFrame.setLocation(300, 150); updateInfoFrame.addWindowListener(this); panel.repaint(); informText.setText(i18n.getString("UPDATE_CHECK_INSTANCES")); String message0 = i18n.getString("UPDATE_INSTANCES"); JLabel label01 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: bold;}--></style></head><body><span class=\"Stil2\">XNavigator Update</span></body></html>"); JLabel label02 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + message0 + " " + "</span></body></html>"); Object[] objects0 = { label01, label02 }; Object[] options0 = { i18n.getString("CONTINUE"), i18n.getString("CANCEL") }; int option = JOptionPane.showOptionDialog(null, objects0, "Update", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options0, options0[0]); if (option == 0) { } else { updateInfoFrame.dispose(); return; } informText.setText(i18n.getString("UPDATE_CHECK_ENVIRONMENT")); if ((new File(".project")).exists()) { Object[] objects = { "Im Eclipse Projekt solltest Du besser die neueste Version aus dem SVN ziehen -Arne-", "Update abgebrochen" }; JOptionPane.showMessageDialog(null, objects, "Update Error", JOptionPane.ERROR_MESSAGE); updateInfoFrame.dispose(); return; } Object[] objects1 = { i18n.getString("UPDATE_WARNING") }; Object[] options1 = { i18n.getString("CONTINUE"), i18n.getString("CANCEL") }; int opt = JOptionPane.showOptionDialog(null, objects1, i18n.getString("WARNING"), JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options1, options1[0]); if (opt == 1) { updateInfoFrame.dispose(); return; } updateInfoFrame.requestFocus(); updateInfoFrame.requestFocusInWindow(); informText.setText(i18n.getString("UPDATE_DOWNLOADING")); String updateFile = "XNavigator-" + version + ".zip"; URL url = new URL(hyperlink_url + updateFile); URLConnection conn = url.openConnection(); int fileSize = conn.getContentLength(); String urlString = url.toString(); progressText.setText("Download " + urlString + " ... 0%"); java.io.BufferedInputStream in = new java.io.BufferedInputStream(url.openStream()); java.io.FileOutputStream fos = new java.io.FileOutputStream(updateFile); java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); int BUFFER_SIZE = 1024; byte data[] = new byte[BUFFER_SIZE]; int count = 0; int size = 0; int prev_perc = 0; while ((count = in.read(data, 0, BUFFER_SIZE)) > 0) { bout.write(data, 0, count); size += count; int perc = (100 * size) / fileSize; if (perc > prev_perc) { progressText.setText("Download " + urlString + " ... " + perc + "%"); prev_perc = perc; } } bout.close(); fos.close(); in.close(); progressText.setText("Download " + url.toString() + " ... ok."); informText.setText(i18n.getString("UPDATE_EXTRACTING")); boolean deleted = deleteFiles(new File("./lib"), false); if (!deleted) { updateInfoFrame.dispose(); return; } extractZipFile(updateFile, progressText); progressText.setText(i18n.getString("UPDATE_COMPLETE")); Object[] objects = { i18n.getString("UPDATE_COMPLETE") }; Object[] options = { i18n.getString("OK") }; JOptionPane.showOptionDialog(null, objects, "Success", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, options[0]); System.exit(0); } catch (Exception e) { e.printStackTrace(); String message = ""; String hyperlink = ""; message = i18n.getString("UPDATE_FAILED"); hyperlink = "<a href='" + hyperlink_url + "'>" + hyperlink_url + "</a>"; JLabel label2 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + "<br>" + message + " " + "</span></body></html>"); JLabel label3 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + hyperlink + "<br>" + "</span></body></html>"); JLabel label4 = new JLabel("<html><head><style type=\"text/css\"><!--.Stil2 {font-size: 10px;font-weight: normal;}--></style></head><body><span class=\"Stil2\">" + version + "</span></body></html>"); label3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); label3.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() > 0) { try { javax.jnlp.BasicService basicService; basicService = (javax.jnlp.BasicService) javax.jnlp.ServiceManager.lookup("javax.jnlp.BasicService"); basicService.showDocument(new URL(hyperlink_url)); } catch (Exception e1) { e1.printStackTrace(); try { Runtime.getRuntime().exec("cmd.exe /c start " + hyperlink_url); } catch (IOException e2) { e2.printStackTrace(); } } } } }); Object[] objects = { label2, label3, label4 }; Object[] options = { i18n.getString("OK") }; updateInfoFrame.dispose(); JOptionPane.showOptionDialog(null, objects, "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]); } updateInfoFrame.setVisible(false); updateInfoFrame.dispose(); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String argv[]) { Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL; int errorCount = 0; int warningCount = 0; double tmp, s; double[] columnwise = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12. }; double[] rowwise = { 1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12. }; double[][] avals = { { 1., 4., 7., 10. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] rankdef = avals; double[][] tvals = { { 1., 2., 3. }, { 4., 5., 6. }, { 7., 8., 9. }, { 10., 11., 12. } }; double[][] subavals = { { 5., 8., 11. }, { 6., 9., 12. } }; double[][] rvals = { { 1., 4., 7. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] pvals = { { 4., 1., 1. }, { 1., 2., 3. }, { 1., 3., 6. } }; double[][] ivals = { { 1., 0., 0., 0. }, { 0., 1., 0., 0. }, { 0., 0., 1., 0. } }; double[][] evals = { { 0., 1., 0., 0. }, { 1., 0., 2.e-7, 0. }, { 0., -2.e-7, 0., 1. }, { 0., 0., 1., 0. } }; double[][] square = { { 166., 188., 210. }, { 188., 214., 240. }, { 210., 240., 270. } }; double[][] sqSolution = { { 13. }, { 15. } }; double[][] condmat = { { 1., 3. }, { 7., 9. } }; int rows = 3, cols = 4; int invalidld = 5; int raggedr = 0; int raggedc = 4; int validld = 3; int nonconformld = 4; int ib = 1, ie = 2, jb = 1, je = 3; int[] rowindexset = { 1, 2 }; int[] badrowindexset = { 1, 3 }; int[] columnindexset = { 1, 2, 3 }; int[] badcolumnindexset = { 1, 2, 4 }; double columnsummax = 33.; double rowsummax = 30.; double sumofdiagonals = 15; double sumofsquares = 650; print("\nTesting constructors and constructor-like methods...\n"); try { A = new Matrix(columnwise, invalidld); errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input"); } catch (IllegalArgumentException e) { try_success("Catch invalid length in packed constructor... ", e.getMessage()); } try { A = new Matrix(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to default constructor... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { A = Matrix.constructWithCopy(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to constructWithCopy... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructWithCopy... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } A = new Matrix(columnwise, validld); B = new Matrix(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; C = B.minus(A); avals[0][0] = tmp; B = Matrix.constructWithCopy(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; if ((tmp - B.get(0, 0)) != 0.0) { errorCount = try_failure(errorCount, "constructWithCopy... ", "copy not effected... data visible outside"); } else { try_success("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; I = new Matrix(ivals); try { check(I, Matrix.identity(3, 4)); try_success("identity... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "identity... ", "identity Matrix not successfully created"); } print("\nTesting access methods...\n"); B = new Matrix(avals); if (B.getRowDimension() != rows) { errorCount = try_failure(errorCount, "getRowDimension... ", ""); } else { try_success("getRowDimension... ", ""); } if (B.getColumnDimension() != cols) { errorCount = try_failure(errorCount, "getColumnDimension... ", ""); } else { try_success("getColumnDimension... ", ""); } B = new Matrix(avals); double[][] barray = B.getArray(); if (barray != avals) { errorCount = try_failure(errorCount, "getArray... ", ""); } else { try_success("getArray... ", ""); } barray = B.getArrayCopy(); if (barray == avals) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied"); } try { check(barray, avals); try_success("getArrayCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied"); } double[] bpacked = B.getColumnPackedCopy(); try { check(bpacked, columnwise); try_success("getColumnPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns"); } bpacked = B.getRowPackedCopy(); try { check(bpacked, rowwise); try_success("getRowPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows"); } try { tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension()); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("get(int,int)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } try { if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1) != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) { errorCount = try_failure(errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived"); } else { try_success("get(int,int)... ", ""); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } SUB = new Matrix(subavals); try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, jb, je); try { check(SUB, M); try_success("getMatrix(int,int,int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(ib, ie, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, columnindexset); try { check(SUB, M); try_success("getMatrix(int,int,int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, jb, je); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, jb, je); try { check(SUB, M); try_success("getMatrix(int[],int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, columnindexset); try { check(SUB, M); try_success("getMatrix(int[],int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("set(int,int,double)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } try { B.set(ib, jb, 0.); tmp = B.get(ib, jb); try { check(tmp, 0.); try_success("set(int,int,double)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Matrix element not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException"); } M = new Matrix(2, 3, 0.); try { B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, jb, je, M); try { check(M.minus(B.getMatrix(ib, ie, jb, je)), M); try_success("setMatrix(int,int,int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, columnindexset, M); try { check(M.minus(B.getMatrix(ib, ie, columnindexset)), M); try_success("setMatrix(int,int,int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, jb, je, M); try { check(M.minus(B.getMatrix(rowindexset, jb, je)), M); try_success("setMatrix(int[],int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, columnindexset, M); try { check(M.minus(B.getMatrix(rowindexset, columnindexset)), M); try_success("setMatrix(int[],int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } print("\nTesting array-like methods...\n"); S = new Matrix(columnwise, nonconformld); R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); A = R; try { S = A.minus(S); errorCount = try_failure(errorCount, "minus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minus conformance check... ", ""); } if (A.minus(R).norm1() != 0.) { errorCount = try_failure(errorCount, "minus... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minus... ", ""); } A = R.copy(); A.minusEquals(R); Z = new Matrix(A.getRowDimension(), A.getColumnDimension()); try { A.minusEquals(S); errorCount = try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minusEquals conformance check... ", ""); } if (A.minus(Z).norm1() != 0.) { errorCount = try_failure(errorCount, "minusEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minusEquals... ", ""); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); C = A.minus(B); try { S = A.plus(S); errorCount = try_failure(errorCount, "plus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plus conformance check... ", ""); } try { check(C.plus(B), A); try_success("plus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)"); } C = A.minus(B); C.plusEquals(B); try { A.plusEquals(S); errorCount = try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plusEquals conformance check... ", ""); } try { check(C, A); try_success("plusEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)"); } A = R.uminus(); try { check(A.plus(R), Z); try_success("uminus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)"); } A = R.copy(); O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0); C = A.arrayLeftDivide(R); try { S = A.arrayLeftDivide(S); errorCount = try_failure(errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivide conformance check... ", ""); } try { check(C, O); try_success("arrayLeftDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)"); } try { A.arrayLeftDivideEquals(S); errorCount = try_failure(errorCount, "arrayLeftDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivideEquals conformance check... ", ""); } A.arrayLeftDivideEquals(R); try { check(A, O); try_success("arrayLeftDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)"); } A = R.copy(); try { A.arrayRightDivide(S); errorCount = try_failure(errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivide conformance check... ", ""); } C = A.arrayRightDivide(R); try { check(C, O); try_success("arrayRightDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)"); } try { A.arrayRightDivideEquals(S); errorCount = try_failure(errorCount, "arrayRightDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivideEquals conformance check... ", ""); } A.arrayRightDivideEquals(R); try { check(A, O); try_success("arrayRightDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)"); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); try { S = A.arrayTimes(S); errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimes conformance check... ", ""); } C = A.arrayTimes(B); try { check(C.arrayRightDivideEquals(B), A); try_success("arrayTimes... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)"); } try { A.arrayTimesEquals(S); errorCount = try_failure(errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimesEquals conformance check... ", ""); } A.arrayTimesEquals(B); try { check(A.arrayRightDivideEquals(B), R); try_success("arrayTimesEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)"); } print("\nTesting I/O methods...\n"); try { DecimalFormat fmt = new DecimalFormat("0.0000E00"); fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read()...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } catch (Exception e) { try { e.printStackTrace(System.out); warningCount = try_warning(warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); DecimalFormat fmt = new DecimalFormat("0.0000"); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read() (2nd attempt) ...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } } R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); String tmpname = "TMPMATRIX.serial"; try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname)); out.writeObject(R); ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname)); A = (Matrix) sin.readObject(); try { check(A, R); try_success("writeObject(Matrix)/readObject(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "Matrix not serialized correctly"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; check write permission in current directory and retry"); } catch (Exception e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "unexpected error in serialization test"); } print("\nTesting linear algebra methods...\n"); A = new Matrix(columnwise, 3); T = new Matrix(tvals); T = A.transpose(); try { check(A.transpose(), T); try_success("transpose...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful"); } A.transpose(); try { check(A.norm1(), columnsummax); try_success("norm1...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation"); } try { check(A.normInf(), rowsummax); try_success("normInf()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation"); } try { check(A.normF(), Math.sqrt(sumofsquares)); try_success("normF...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation"); } try { check(A.trace(), sumofdiagonals); try_success("trace()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation"); } try { check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.); try_success("det()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation"); } SQ = new Matrix(square); try { check(A.times(A.transpose()), SQ); try_success("times(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation"); } try { check(A.times(0.), Z); try_success("times(double)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(double)...", "incorrect Matrix-scalar product calculation"); } A = new Matrix(columnwise, 4); QRDecomposition QR = A.qr(); R = QR.getR(); try { check(A, QR.getQ().times(R)); try_success("QRDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation"); } SingularValueDecomposition SVD = A.svd(); try { check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose()))); try_success("SingularValueDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation"); } DEF = new Matrix(rankdef); try { check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1); try_success("rank()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation"); } B = new Matrix(condmat); SVD = B.svd(); double[] singularvalues = SVD.getSingularValues(); try { check(B.cond(), singularvalues[0] / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]); try_success("cond()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation"); } int n = A.getColumnDimension(); A = A.getMatrix(0, n - 1, 0, n - 1); A.set(0, 0, 0.); LUDecomposition LU = A.lu(); try { check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU())); try_success("LUDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation"); } X = A.inverse(); try { check(A.times(X), Matrix.identity(3, 3)); try_success("inverse()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation"); } O = new Matrix(SUB.getRowDimension(), 1, 1.0); SOL = new Matrix(sqSolution); SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1); try { check(SQ.solve(SOL), O); try_success("solve()...", ""); } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "solve()...", e1.getMessage()); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "solve()...", e.getMessage()); } A = new Matrix(pvals); CholeskyDecomposition Chol = A.chol(); Matrix L = Chol.getL(); try { check(A, L.times(L.transpose())); try_success("CholeskyDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation"); } X = Chol.solve(Matrix.identity(3, 3)); try { check(A.times(X), Matrix.identity(3, 3)); try_success("CholeskyDecomposition solve()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation"); } EigenvalueDecomposition Eig = A.eig(); Matrix D = Eig.getD(); Matrix V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (symmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation"); } A = new Matrix(evals); Eig = A.eig(); D = Eig.getD(); V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (nonsymmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation"); } print("\nTestMatrix completed.\n"); print("Total errors reported: " + Integer.toString(errorCount) + "\n"); print("Total warnings reported: " + Integer.toString(warningCount) + "\n"); }
612
0
public static void main(String args[]) { try { URL url = new URL("http://www.hungry.com/"); InputStream stream = url.openStream(); int size = 0; while (-1 != stream.read()) { size++; } stream.close(); System.out.println("PASSED: new URL() size=" + size); } catch (Exception e) { System.out.println("FAILED: " + e); } }
public void run() { try { Debug.log("Integrity test", "Getting MD5 instance"); MessageDigest m = MessageDigest.getInstance("MD5"); Debug.log("Integrity test", "Creating URL " + target); URL url = new URL(this.target); Debug.log("Integrity test", "Setting up connection"); URLConnection urlConnection = url.openConnection(); InputStream in = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int numRead; int fileSize = 0; Debug.log("Integrity test", "Reading file"); while ((numRead = in.read(buffer)) != -1) { m.update(buffer, 0, numRead); fileSize += numRead; } in.close(); Debug.log("Integrity test", "File read: " + fileSize + " bytes"); Debug.log("Integrity test", "calculating Hash"); String fileHash = new BigInteger(1, m.digest()).toString(16); if (fileHash.equals(this.hash)) { Debug.log("Integrity test", "Test OK"); this.result.put("Integrity", "OK"); } else { Debug.log("Integrity test", "Test failed: different hashes (" + fileHash + " but expected " + hash + ")"); this.result.put("Integrity", "FAIL"); } } catch (Exception e) { Debug.log("Integrity test", "Test failed"); this.result.put("Integrity", "FAIL"); } }
613
1
public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException { if (format != null && "gif".equals(format.toLowerCase())) { resize(originalFile, resizedFile, width, 1); return; } FileInputStream fis = new FileInputStream(originalFile); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); int readLength = -1; int bufferSize = 1024; byte bytes[] = new byte[bufferSize]; while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) { byteStream.write(bytes, 0, readLength); } byte[] in = byteStream.toByteArray(); fis.close(); byteStream.close(); Image inputImage = Toolkit.getDefaultToolkit().createImage(in); waitForImage(inputImage); int imageWidth = inputImage.getWidth(null); if (imageWidth < 1) throw new IllegalArgumentException("image width " + imageWidth + " is out of range"); int imageHeight = inputImage.getHeight(null); if (imageHeight < 1) throw new IllegalArgumentException("image height " + imageHeight + " is out of range"); int height = -1; double scaleW = (double) imageWidth / (double) width; double scaleY = (double) imageHeight / (double) height; if (scaleW >= 0 && scaleY >= 0) { if (scaleW > scaleY) { height = -1; } else { width = -1; } } Image outputImage = inputImage.getScaledInstance(width, height, java.awt.Image.SCALE_DEFAULT); checkImage(outputImage); encode(new FileOutputStream(resizedFile), outputImage, format); }
private static void processFile(String file) throws IOException { FileInputStream in = new FileInputStream(file); int read = 0; byte[] buf = new byte[2048]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); while ((read = in.read(buf)) > 0) bout.write(buf, 0, read); in.close(); String converted = bout.toString().replaceAll("@project.name@", projectNameS).replaceAll("@base.package@", basePackageS).replaceAll("@base.dir@", baseDir).replaceAll("@webapp.dir@", webAppDir).replaceAll("path=\"target/classes\"", "path=\"src/main/webapp/WEB-INF/classes\""); FileOutputStream out = new FileOutputStream(file); out.write(converted.getBytes()); out.close(); }
614
0
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(); } }
@Override protected ResourceHandler doGet(final URI resourceUri) throws ResourceNotFoundException, ResourceException { if (resourceUri.getHost() == null) { throw new IllegalStateException(InternalBundleHelper.StoreMessageBundle.getMessage("store.uri.http.illegal", resourceUri.toString())); } try { final URL configUrl = resourceUri.toURL(); final URLConnection urlConnection; Proxy httpProxy = null; if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxySet))) { if (context.getBoolean(FileStoreContextBuilder.ProxySet)) { final String proxyHost = context.getString(FileStoreContextBuilder.ProxyHost); final String proxyPort = context.getString(FileStoreContextBuilder.ProxyPort); if (!StringHelper.isEmpty(proxyHost)) { httpProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, !StringHelper.isEmpty(proxyPort) ? Integer.parseInt(proxyPort) : 80)); if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.NonProxyHosts))) { System.getProperties().put("http.nonProxyHosts", context.getProperty(FileStoreContextBuilder.NonProxyHosts)); } if (!StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxyUser)) && !StringHelper.isEmpty(context.getString(FileStoreContextBuilder.ProxyPassword))) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(context.getString(FileStoreContextBuilder.ProxyUser), context.getString(FileStoreContextBuilder.ProxyPassword).toCharArray()); } }); } } } } if (httpProxy == null) { urlConnection = configUrl.openConnection(); } else { urlConnection = configUrl.openConnection(httpProxy); } setUrlConnectionSettings(urlConnection); urlConnection.connect(); try { return createResourceHandler(resourceUri.toString(), urlConnection.getInputStream()); } catch (final FileNotFoundException fnfe) { throw new ResourceNotFoundException(resourceUri.toString()); } } catch (final MalformedURLException mure) { throw new IllegalStateException(InternalBundleHelper.StoreMessageBundle.getMessage("store.uri.malformed", resourceUri.toString())); } catch (final ConnectException ce) { throw new ResourceException("store.connection.error", ce, resourceUri.toString()); } catch (final IOException ioe) { if (ioe instanceof ResourceException) { throw (ResourceException) ioe; } else { throw new ResourceException(ioe, resourceUri.toString()); } } }
615
1
public String parse(String term) throws OntologyAdaptorException { try { String sUrl = getUrl(term); if (sUrl.length() > 0) { URL url = new URL(sUrl); InputStream in = url.openStream(); StringBuilder sb = new StringBuilder(); BufferedReader r = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = r.readLine()) != null) { if (sb.length() > 0) { sb.append("\r\n"); } sb.append(line); } return sb.toString(); } else { return ""; } } catch (Exception ex) { throw new OntologyAdaptorException("Convertion to lucene failed.", ex); } }
private List parseUrlGetUids(String url) throws FetchError { List hids = new ArrayList(); try { InputStream is = (new URL(url)).openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringBuffer buffer = new StringBuffer(); String inputLine = ""; Pattern pattern = Pattern.compile("\\<input\\s+type=hidden\\s+name=hid\\s+value=(\\d+)\\s?\\>", Pattern.CASE_INSENSITIVE); while ((inputLine = in.readLine()) != null) { Matcher matcher = pattern.matcher(inputLine); if (matcher.find()) { String id = matcher.group(1); if (!hids.contains(id)) { hids.add(id); } } } } catch (Exception e) { System.out.println(e); throw new FetchError(e); } return hids; }
616
1
public static void main(String[] args) { try { String completePath = null; String predictionFileName = null; if (args.length == 2) { completePath = args[0]; predictionFileName = args[1]; } else { System.out.println("Please provide complete path to training_set parent folder as an argument. EXITING"); System.exit(0); } File inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + MovieIndexFileName); FileChannel inC = new FileInputStream(inputFile).getChannel(); int filesize = (int) inC.size(); ByteBuffer mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); MovieLimitsTHash = new TShortObjectHashMap(17770, 1); int i = 0, totalcount = 0; short movie; int startIndex, endIndex; TIntArrayList a; while (mappedfile.hasRemaining()) { movie = mappedfile.getShort(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); MovieLimitsTHash.put(movie, a); } inC.close(); mappedfile = null; System.out.println("Loaded movie index hash"); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + CustIndexFileName); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); mappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); CustomerLimitsTHash = new TIntObjectHashMap(480189, 1); int custid; while (mappedfile.hasRemaining()) { custid = mappedfile.getInt(); startIndex = mappedfile.getInt(); endIndex = mappedfile.getInt(); a = new TIntArrayList(2); a.add(startIndex); a.add(endIndex); CustomerLimitsTHash.put(custid, a); } inC.close(); mappedfile = null; System.out.println("Loaded customer index hash"); MoviesAndRatingsPerCustomer = InitializeMovieRatingsForCustomerHashMap(completePath, CustomerLimitsTHash); System.out.println("Populated MoviesAndRatingsPerCustomer hashmap"); File outfile = new File(completePath + fSep + "SmartGRAPE" + fSep + predictionFileName); FileChannel out = new FileOutputStream(outfile, true).getChannel(); inputFile = new File(completePath + fSep + "SmartGRAPE" + fSep + "formattedProbeData.txt"); inC = new FileInputStream(inputFile).getChannel(); filesize = (int) inC.size(); ByteBuffer probemappedfile = inC.map(FileChannel.MapMode.READ_ONLY, 0, filesize); int custAndRatingSize = 0; TIntByteHashMap custsandratings = new TIntByteHashMap(); int ignoreProcessedRows = 0; int movieViewershipSize = 0; while (probemappedfile.hasRemaining()) { short testmovie = probemappedfile.getShort(); int testCustomer = probemappedfile.getInt(); if ((CustomersAndRatingsPerMovie != null) && (CustomersAndRatingsPerMovie.containsKey(testmovie))) { } else { CustomersAndRatingsPerMovie = InitializeCustomerRatingsForMovieHashMap(completePath, testmovie); custsandratings = (TIntByteHashMap) CustomersAndRatingsPerMovie.get(testmovie); custAndRatingSize = custsandratings.size(); } TShortByteHashMap testCustMovieAndRatingsMap = (TShortByteHashMap) MoviesAndRatingsPerCustomer.get(testCustomer); short[] testCustMovies = testCustMovieAndRatingsMap.keys(); float finalPrediction = 0; finalPrediction = predictRating(testCustomer, testmovie, custsandratings, custAndRatingSize, testCustMovies, testCustMovieAndRatingsMap); System.out.println("prediction for movie: " + testmovie + " for customer " + testCustomer + " is " + finalPrediction); ByteBuffer buf = ByteBuffer.allocate(11); buf.putShort(testmovie); buf.putInt(testCustomer); buf.putFloat(finalPrediction); buf.flip(); out.write(buf); buf = null; testCustMovieAndRatingsMap = null; testCustMovies = null; } } catch (Exception e) { e.printStackTrace(); } }
public void fileCopy(File inFile, File outFile) { try { FileInputStream in = new FileInputStream(inFile); FileOutputStream out = new FileOutputStream(outFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (IOException e) { System.err.println("Hubo un error de entrada/salida!!!"); } }
617
0
private final boolean copy_to_file_nio(File src, File dst) throws IOException { FileChannel srcChannel = null, dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dst).getChannel(); { int safe_max = (64 * 1024 * 1024) / 4; long size = srcChannel.size(); long position = 0; while (position < size) { position += srcChannel.transferTo(position, safe_max, dstChannel); } } return true; } finally { try { if (srcChannel != null) srcChannel.close(); } catch (IOException e) { Debug.debug(e); } try { if (dstChannel != null) dstChannel.close(); } catch (IOException e) { Debug.debug(e); } } }
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String version = null; String build = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".version")) version = line.substring(8).trim(); else if (line.startsWith(".build")) build = line.substring(6).trim(); } bin.close(); if (version != null && build != null) { if (jEdit.getBuild().compareTo(build) < 0) newVersionAvailable(view, version, url); else { GUIUtilities.message(view, "version-check" + ".up-to-date", new String[0]); } } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
618
0
private Reader getReader(String uri, Query query) throws SourceException { if (OntoramaConfig.DEBUG) { System.out.println("uri = " + uri); } InputStreamReader reader = null; try { System.out.println("class UrlSource, uri = " + uri); URL url = new URL(uri); URLConnection connection = url.openConnection(); reader = new InputStreamReader(connection.getInputStream()); } catch (MalformedURLException urlExc) { throw new SourceException("Url " + uri + " specified for this ontology source is not well formed, error: " + urlExc.getMessage()); } catch (IOException ioExc) { throw new SourceException("Couldn't read input data source for " + uri + ", error: " + ioExc.getMessage()); } return reader; }
public String parse() { try { URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; boolean flag1 = false; while ((line = reader.readLine()) != null) { line = line.trim(); if (!flag1 && line.contains("</center>")) flag1 = true; if (flag1 && line.contains("<br><center>")) break; if (flag1) { mText.append(line); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mText.toString(); }
619
0
private Concept fetchDataNeeded(String conceptUri) { if (cache.size() > MAX_CACHE) cache.clear(); if (cache.containsKey(conceptUri)) return this.cache.get(conceptUri); try { URL url = new URL(conceptUri); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setInstanceFollowRedirects(true); connection.setRequestProperty("Accept", "application/rdf+xml"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK && connection.getContentType().contains("application/rdf+xml")) { InputStream is = connection.getInputStream(); HashMap<String, String> parameters = new HashMap<String, String>(); parameters.put("uri", conceptUri); Transformer tf = this.templates.getDAOTransformer(keyTemplates, parameters); DOMResult outputTarget = new DOMResult(); tf.transform(new StreamSource(is), outputTarget); Concept concept = ConceptXMLBind.getInstance().restoreConcept(outputTarget.getNode()); this.cache.put(conceptUri, concept); return concept; } else { logger.error("Unable to get a representation of the resource: " + connection.getResponseCode() + " => " + connection.getContentType()); throw new RuntimeException("Unable to get a representation of the resource"); } } catch (Exception e) { logger.error("Unable to fetch data for concept " + conceptUri, e); throw new RuntimeException(e); } }
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; }
620
1
private void copy(File fin, File fout) throws IOException { FileOutputStream out = new FileOutputStream(fout); FileInputStream in = new FileInputStream(fin); byte[] buf = new byte[2048]; int read = in.read(buf); while (read > 0) { out.write(buf, 0, read); read = in.read(buf); } in.close(); out.close(); }
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; }
621
1
protected InputStream createIconType(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { JavaliController.debug(JavaliController.LG_VERBOSE, "Creating iconType"); String cHash = PRM_TYPE + "=" + TP_ICON; String iconName = req.getParameter("iconName"); if (iconName == null) { res.sendError(res.SC_NOT_FOUND); return null; } Locale loc = null; HttpSession sess = req.getSession(false); JavaliSession jsess = null; int menuType = -1; String menuTypeString = req.getParameter(PRM_MENU_TYPE); try { menuType = new Integer(menuTypeString).intValue(); } catch (Exception e) { } if (sess != null) jsess = (JavaliSession) sess.getAttribute(FormConstants.SESSION_BINDING); if (jsess != null && jsess.getUser() != null) loc = jsess.getUser().getLocale(); else if (sess != null) loc = (Locale) sess.getAttribute(FormConstants.LOCALE_BINDING); if (loc == null) loc = Locale.getDefault(); if (menuType == -1) menuType = MENU_TYPE_TEXTICON; String iconText = JavaliResource.getString("icon." + iconName, loc); if (iconText == null) { iconText = req.getParameter(PRM_MENU_NAME); if (iconText == null) iconText = ""; } cHash += ", " + PRM_ICON_NAME + "=" + iconName + ", text=" + iconText + ", menuType=" + menuType; String iconFileName = null; String fontName = req.getParameter(PRM_FONT_NAME); if (fontName == null) { fontName = "Helvetica"; } cHash += "," + PRM_FONT_NAME + "=" + fontName; String fontSizeString = req.getParameter(PRM_FONT_SIZE); int fontSize; try { fontSize = Integer.parseInt(fontSizeString); } catch (NumberFormatException nfe) { fontSize = 12; } cHash += "," + PRM_FONT_SIZE + "=" + fontSize; String fontTypeString = req.getParameter(PRM_FONT_TYPE); int fontType = Font.BOLD; if ("PLAIN".equalsIgnoreCase(fontTypeString)) fontType = Font.PLAIN; if ("BOLD".equalsIgnoreCase(fontTypeString)) fontType = Font.BOLD; if ("ITALIC".equalsIgnoreCase(fontTypeString)) fontType = Font.ITALIC; if ("ITALICBOLD".equalsIgnoreCase(fontTypeString) || "BOLDITALIC".equalsIgnoreCase(fontTypeString) || "BOLD_ITALIC".equalsIgnoreCase(fontTypeString) || "ITALIC_BOLD".equalsIgnoreCase(fontTypeString)) { fontType = Font.ITALIC | Font.BOLD; } cHash += "," + PRM_FONT_TYPE + "=" + fontType; String fontColor = req.getParameter(PRM_FONT_COLOR); if (fontColor == null || fontColor.equals("")) fontColor = "0x000000"; cHash += "," + PRM_FONT_COLOR + "=" + fontColor; String fName = cacheInfo.file(cHash); JavaliController.debug(JavaliController.LG_VERBOSE, "Called for: " + fName); if (fName == null) { JavaliController.debug(JavaliController.LG_VERBOSE, "No cache found for: " + cHash); if (getServletConfig() != null && getServletConfig().getServletContext() != null) { if (iconName != null && iconName.startsWith("/")) iconFileName = getServletConfig().getServletContext().getRealPath(iconName + ".gif"); else iconFileName = getServletConfig().getServletContext().getRealPath("/icons/" + iconName + ".gif"); File iconFile = new File(iconFileName); if (!iconFile.exists()) { JavaliController.debug(JavaliController.LG_VERBOSE, "Could not find: " + iconFileName); res.sendError(res.SC_NOT_FOUND); return null; } iconFileName = iconFile.getAbsolutePath(); JavaliController.debug(JavaliController.LG_VERBOSE, "file: " + iconFileName + " and cHash=" + cHash); } else { JavaliController.debug(JavaliController.LG_VERBOSE, "No ServletConfig=" + getServletConfig() + " or servletContext"); res.sendError(res.SC_NOT_FOUND); return null; } File tmp = File.createTempFile(PREFIX, SUFIX, cacheDir); OutputStream out = new FileOutputStream(tmp); if (menuType == MENU_TYPE_ICON) { FileInputStream in = new FileInputStream(iconFileName); byte buf[] = new byte[2048]; int read = -1; while ((read = in.read(buf)) != -1) out.write(buf, 0, read); } else if (menuType == MENU_TYPE_TEXT) MessageImage.sendAsGIF(MessageImage.makeMessageImage(iconText, fontName, fontSize, fontType, fontColor, false, "0x000000", true), out); else MessageImage.sendAsGIF(MessageImage.makeIconImage(iconFileName, iconText, fontName, fontColor, fontSize, fontType), out); out.close(); cacheInfo.putFile(cHash, tmp); fName = cacheInfo.file(cHash); } return new FileInputStream(new File(cacheDir, fName)); }
public void sendResponse(DjdocRequest req, HttpServletResponse res) throws IOException { File file = (File) req.getResult(); InputStream in = null; try { in = new FileInputStream(file); IOUtils.copy(in, res.getOutputStream()); } finally { if (in != null) { in.close(); } } }
622
1
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String arg = req.getParameter("file"); if (arg == null) { resp.sendError(404, "Missing 'file' Arg"); return; } int mfid = NumberUtils.toInt(arg); Object sageFile = MediaFileAPI.GetMediaFileForID(mfid); if (sageFile == null) { resp.sendError(404, "Sage File not found " + mfid); return; } int seconds = NumberUtils.toInt(req.getParameter("ss"), -1); long offset = NumberUtils.toLong(req.getParameter("sb"), -1); if (seconds < 0 && offset < 0) { resp.sendError(501, "Missing 'ss' or 'sb' args"); return; } int width = NumberUtils.toInt(req.getParameter("w"), 320); int height = NumberUtils.toInt(req.getParameter("h"), 320); File dir = new File(Phoenix.getInstance().getUserCacheDir(), "videothumb/" + mfid); if (!dir.exists()) { dir.mkdirs(); } String prefix = ""; if (offset > 0) { prefix = "O" + offset; } else { prefix = "S" + seconds; } File f = new File(dir, prefix + "_" + width + "_" + height + ".jpg").getCanonicalFile(); if (!f.exists()) { try { generateThumbnailNew(sageFile, f, seconds, offset, width, height); } catch (Exception e) { e.printStackTrace(); resp.sendError(503, "Failed to generate thumbnail\n " + e.getMessage()); return; } } if (!f.exists()) { resp.sendError(404, "Missing File: " + f); return; } resp.setContentType("image/jpeg"); resp.setContentLength((int) f.length()); FileInputStream fis = null; try { fis = new FileInputStream(f); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(fis, os); os.flush(); fis.close(); } catch (Throwable e) { log.error("Failed to send file: " + f); resp.sendError(500, "Failed to get file " + f); } finally { IOUtils.closeQuietly(fis); } }
protected void copy(File src, File dest) throws IOException { if (src.isDirectory() && dest.isFile()) throw new IOException("Cannot copy a directory to a file"); if (src.isDirectory()) { File newDir = new File(dest, src.getName()); if (!newDir.mkdirs()) throw new IOException("Cannot create a new Directory"); File[] entries = src.listFiles(); for (int i = 0; i < entries.length; ++i) copy(entries[i], newDir); return; } if (dest.isDirectory()) { File newFile = new File(dest, src.getName()); newFile.createNewFile(); copy(src, newFile); return; } try { if (src.length() == 0) { dest.createNewFile(); return; } FileChannel fc = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); long transfered = 0; long totalLength = src.length(); while (transfered < totalLength) { long num = fc.transferTo(transfered, totalLength - transfered, dstChannel); if (num == 0) throw new IOException("Error while copying"); transfered += num; } dstChannel.close(); fc.close(); } catch (IOException e) { if (os.equals("Unix")) { _logger.fine("Trying to use cp to copy file..."); File cp = new File("/usr/bin/cp"); if (!cp.exists()) cp = new File("/bin/cp"); if (!cp.exists()) cp = new File("/usr/local/bin/cp"); if (!cp.exists()) cp = new File("/sbin/cp"); if (!cp.exists()) cp = new File("/usr/sbin/cp"); if (!cp.exists()) cp = new File("/usr/local/sbin/cp"); if (cp.exists()) { Process cpProcess = Runtime.getRuntime().exec(cp.getAbsolutePath() + " '" + src.getAbsolutePath() + "' '" + dest.getAbsolutePath() + "'"); int errCode; try { errCode = cpProcess.waitFor(); } catch (java.lang.InterruptedException ie) { throw e; } return; } } throw e; } }
623
1
public static boolean copyFile(final File fileFrom, final File fileTo) { assert fileFrom != null : "fileFrom is null"; assert fileTo != null : "fileTo is null"; LOGGER.info(buildLogString(COPY_FILE_INFO, new Object[] { fileFrom, fileTo })); boolean error = true; FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(fileFrom); outputStream = new FileOutputStream(fileTo); final FileChannel inChannel = inputStream.getChannel(); final FileChannel outChannel = outputStream.getChannel(); inChannel.transferTo(0, inChannel.size(), outChannel); error = false; } catch (final IOException e) { LOGGER.log(SEVERE, buildLogString(COPY_FILE_ERROR, new Object[] { fileFrom, fileTo }), e); } finally { closeCloseable(inputStream, fileFrom); closeCloseable(outputStream, fileTo); } return error; }
public static void unzip(final File file, final ZipFile zipFile, final File targetDirectory) throws PtException { LOG.info("Unzipping zip file '" + file.getAbsolutePath() + "' to directory " + "'" + targetDirectory.getAbsolutePath() + "'."); assert (file.exists() && file.isFile()); if (targetDirectory.exists() == false) { LOG.debug("Creating target directory."); if (targetDirectory.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + targetDirectory.getAbsolutePath() + "'!"); } } ZipInputStream zipin = null; try { zipin = new ZipInputStream(new FileInputStream(file)); ZipEntry nextZipEntry = zipin.getNextEntry(); while (nextZipEntry != null) { LOG.debug("Unzipping entry '" + nextZipEntry.getName() + "'."); if (nextZipEntry.isDirectory()) { LOG.debug("Skipping directory."); continue; } final File targetFile = new File(targetDirectory, nextZipEntry.getName()); final File parentTargetFile = targetFile.getParentFile(); if (parentTargetFile.exists() == false) { LOG.debug("Creating directory '" + parentTargetFile.getAbsolutePath() + "'."); if (parentTargetFile.mkdirs() == false) { throw new PtException("Could not create target directory at " + "'" + parentTargetFile.getAbsolutePath() + "'!"); } } InputStream input = null; FileOutputStream output = null; try { input = zipFile.getInputStream(nextZipEntry); if (targetFile.createNewFile() == false) { throw new PtException("Could not create target file " + "'" + targetFile.getAbsolutePath() + "'!"); } output = new FileOutputStream(targetFile); byte[] buffer = new byte[BUFFER_SIZE]; int readBytes = input.read(buffer, 0, buffer.length); while (readBytes > 0) { output.write(buffer, 0, readBytes); readBytes = input.read(buffer, 0, buffer.length); } } finally { PtCloseUtil.close(input, output); } nextZipEntry = zipin.getNextEntry(); } } catch (IOException e) { throw new PtException("Could not unzip file '" + file.getAbsolutePath() + "'!", e); } finally { PtCloseUtil.close(zipin); } }
624
0
private void preprocessObjects(GeoObject[] objects) throws IOException { System.out.println("objects.length " + objects.length); for (int i = 0; i < objects.length; i++) { String fileName = objects[i].getPath(); int dotindex = fileName.lastIndexOf("."); dotindex = dotindex < 0 ? 0 : dotindex; String tmp = dotindex < 1 ? fileName : fileName.substring(0, dotindex + 3) + "w"; System.out.println("i: " + " world filename " + tmp); File worldFile = new File(tmp); if (worldFile.exists()) { BufferedReader worldFileReader = new BufferedReader(new InputStreamReader(new FileInputStream(worldFile))); if (staticDebugOn) debug("b4nextline: "); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); if (line != null) { line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLon(Double.valueOf(tokenizer.nextToken()).doubleValue()); line = worldFileReader.readLine(); if (staticDebugOn) debug("line: " + line); tokenizer = new StringTokenizer(line, " \n\t\r\"", false); objects[i].setLat(Double.valueOf(tokenizer.nextToken()).doubleValue()); } } File file = new File(objects[i].getPath()); if (file.exists()) { System.out.println("object src file found "); int slashindex = fileName.lastIndexOf(java.io.File.separator); slashindex = slashindex < 0 ? 0 : slashindex; if (slashindex == 0) { slashindex = fileName.lastIndexOf("/"); slashindex = slashindex < 0 ? 0 : slashindex; } tmp = slashindex < 1 ? fileName : fileName.substring(slashindex + 1, fileName.length()); System.out.println("filename " + destinationDirectory + XPlat.fileSep + tmp); objects[i].setPath(tmp); file = new File(fileName); if (file.exists()) { DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationDirectory + XPlat.fileSep + tmp))); System.out.println("copying to " + destinationDirectory + XPlat.fileSep + tmp); for (; ; ) { try { dataOut.writeShort(dataIn.readShort()); } catch (EOFException e) { break; } catch (IOException e) { break; } } dataOut.close(); } } } }
public static synchronized String getPageContent(String pageUrl) { URL url = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; String line = null; StringBuilder page = null; if (pageUrl == null || pageUrl.trim().length() == 0) { return null; } else { try { url = new URL(pageUrl); inputStreamReader = new InputStreamReader(url.openStream()); bufferedReader = new BufferedReader(inputStreamReader); page = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } } } if (page == null) { return null; } else { return page.toString(); } }
625
0
private void readCard() { try { final String urlString = createURLStringExistRESTGetXQuery("//scheda[cata = \"" + cata + "\"]"); InputStream inputStream = new URL(urlString).openStream(); uiSchedaXml.read(inputStream); inputStream.close(); } catch (MalformedURLException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } }
private void readVersion() { URL url = ClassLoader.getSystemResource("version"); if (url == null) { return; } BufferedReader reader = null; String line = null; try { reader = new BufferedReader(new InputStreamReader(url.openStream())); while ((line = reader.readLine()) != null) { if (line.startsWith("Version=")) { version = (line.split("="))[1]; } if (line.startsWith("Revision=")) { revision = (line.split("="))[1]; } if (line.startsWith("Date=")) { String sSec = (line.split("="))[1]; Long lSec = Long.valueOf(sSec); compileDate = new Date(lSec); } } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return; }
626
0
@SuppressWarnings("unchecked") protected void displayFreeMarkerResponse(HttpServletRequest request, HttpServletResponse response, String templateName, Map<String, Object> variableMap) throws IOException { Enumeration<String> attrNameEnum = request.getSession().getAttributeNames(); String attrName; while (attrNameEnum.hasMoreElements()) { attrName = attrNameEnum.nextElement(); if (attrName != null && attrName.startsWith(ADMIN4J_SESSION_VARIABLE_PREFIX)) { variableMap.put("Session" + attrName, request.getSession().getAttribute(attrName)); } } variableMap.put("RequestAdmin4jCurrentUri", request.getRequestURI()); Template temp = FreemarkerUtils.createConfiguredTemplate(this.getClass(), templateName); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); try { temp.process(variableMap, new OutputStreamWriter(outStream)); response.setContentLength(outStream.size()); IOUtils.copy(new ByteArrayInputStream(outStream.toByteArray()), response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (Exception e) { throw new Admin4jRuntimeException(e); } }
public static RecordResponse loadRecord(RecordRequest recordRequest) { RecordResponse recordResponse = new RecordResponse(); try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(recordRequest.isContact() ? URL_RECORD_CONTACT : URL_RECORD_COMPANY); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6); nameValuePairs.add(new BasicNameValuePair("format", "xml")); nameValuePairs.add(new BasicNameValuePair("token", recordRequest.getToken())); nameValuePairs.add(new BasicNameValuePair("id", recordRequest.getId())); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); String line = EntityUtils.toString(response.getEntity()); Document document = XMLfunctions.XMLfromString(line); NodeList nodes = document.getElementsByTagName("response"); Element e = (Element) nodes.item(0); String Name__Last__First_ = XMLfunctions.getValue(e, recordRequest.isContact() ? "Name__Last__First_" : "Name"); String phone = ""; if (!recordRequest.isContact()) phone = XMLfunctions.getValue(e, "Phone"); String Email1 = XMLfunctions.getValue(e, recordRequest.isContact() ? "Personal_Email" : "Email"); String Home_Fax = XMLfunctions.getValue(e, recordRequest.isContact() ? "Home_Fax" : "Fax1"); String Address1 = XMLfunctions.getValue(e, "Address1"); String Address2 = XMLfunctions.getValue(e, "Address2"); String City = XMLfunctions.getValue(e, "City"); String State = XMLfunctions.getValue(e, "State"); String Zip = XMLfunctions.getValue(e, "Zip"); String Country = XMLfunctions.getValue(e, "Country"); String Profile = XMLfunctions.getValue(e, "Profile"); String success = XMLfunctions.getValue(e, "success"); String error = XMLfunctions.getValue(e, "error"); recordResponse.setName(Name__Last__First_); recordResponse.setPhone(phone); recordResponse.setEmail(Email1); recordResponse.setHomeFax(Home_Fax); recordResponse.setAddress1(Address1); recordResponse.setAddress2(Address2); recordResponse.setCity(City); recordResponse.setState(State); recordResponse.setZip(Zip); recordResponse.setProfile(Profile); recordResponse.setCountry(Country); recordResponse.setSuccess(success); recordResponse.setError(error); } catch (Exception e) { } return recordResponse; }
627
1
public RemotePolicyMigrator createRemotePolicyMigrator() { return new RemotePolicyMigrator() { public String migratePolicy(InputStream stream, String url) throws ResourceMigrationException, IOException { ByteArrayOutputCreator oc = new ByteArrayOutputCreator(); IOUtils.copyAndClose(stream, oc.getOutputStream()); return oc.getOutputStream().toString(); } }; }
public void writeToStream(OutputStream out) throws IOException { InputStream result = null; if (tempFile != null) { InputStream input = new BufferedInputStream(new FileInputStream(tempFile)); IOUtils.copy(input, out); IOUtils.closeQuietly(input); } else if (tempBuffer != null) { out.write(tempBuffer); } }
628
0
public OAuthResponseMessage access(OAuthMessage request, net.oauth.ParameterStyle style) throws IOException { HttpMessage httpRequest = HttpMessage.newRequest(request, style); HttpResponseMessage httpResponse = http.execute(httpRequest, httpParameters); httpResponse = HttpMessageDecoder.decode(httpResponse); return new OAuthResponseMessage(httpResponse); }
private void mergeInDefaultMenuItemActionPerformed(java.awt.event.ActionEvent evt) { try { String surl = AutoplotUtil.getProperty("autoplot.default.bookmarks", "http://www.autoplot.org/data/demos.xml"); URL url = new URL(surl); Document doc = AutoplotUtil.readDoc(url.openStream()); List<Bookmark> importBook = Bookmark.parseBookmarks(doc.getDocumentElement()); List<Bookmark> newList = new ArrayList(model.list.size()); for (int i = 0; i < model.list.size(); i++) { newList.add(i, model.list.get(i).copy()); } model.mergeList(importBook, newList); model.setList(newList); formatToFile(bookmarksFile); } catch (SAXException ex) { logger.log(Level.SEVERE, null, ex); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } catch (ParserConfigurationException ex) { logger.log(Level.SEVERE, null, ex); } }
629
0
public static String move_tags(String sessionid, String absolutePathForTheMovedTags, String absolutePathForTheDestinationTag) { String resultJsonString = "some problem existed inside the create_new_tag() function if you see this string"; try { Log.d("current running function name:", "move_tags"); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("https://mt0-app.cloud.cm/rpc/json"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("c", "Storage")); nameValuePairs.add(new BasicNameValuePair("m", "move_tag")); nameValuePairs.add(new BasicNameValuePair("absolute_new_parent_tag", absolutePathForTheDestinationTag)); nameValuePairs.add(new BasicNameValuePair("absolute_tags", absolutePathForTheMovedTags)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setHeader("Cookie", "PHPSESSID=" + sessionid); HttpResponse response = httpclient.execute(httppost); resultJsonString = EntityUtils.toString(response.getEntity()); return resultJsonString; } catch (Exception e) { e.printStackTrace(); } return resultJsonString; }
public static final void copy(String source, String destination) { FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(source); fos = new FileOutputStream(destination); java.nio.channels.FileChannel channelSrc = fis.getChannel(); java.nio.channels.FileChannel channelDest = fos.getChannel(); channelSrc.transferTo(0, channelSrc.size(), channelDest); fis.close(); fos.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } }
630
0
public void loadRegistry(URL url) throws PacketAnalyzerRegistryException { if (analyzers != null) { return; } analyzers = new Hashtable(); roots = new Vector(); try { InputStream in = url.openStream(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.parse(in); NodeList list = doc.getElementsByTagName(PACKET_ANALYZER); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); NamedNodeMap map = node.getAttributes(); String id = map.getNamedItem(ID).getNodeValue(); String name = map.getNamedItem(NAME).getNodeValue(); String clazz = map.getNamedItem(CLASS).getNodeValue(); Node n = map.getNamedItem(EXTENDS); String[] split = null; if (n != null) { String extendedAnalyzers = n.getNodeValue(); if (extendedAnalyzers.trim().length() != 0) { split = extendedAnalyzers.split("\\s*\\,+\\s*"); } } PacketAnalyzerDescriptor descriptor = new PacketAnalyzerDescriptor(id, name, clazz, split); addDescriptor(descriptor); } if (roots.size() == 0) { throw new PacketAnalyzerRegistryException("There is no root analyzer in the registry!"); } } catch (IOException e) { throw new PacketAnalyzerRegistryException("Cannot open registry file.", e); } catch (ParserConfigurationException e) { throw new PacketAnalyzerRegistryException("Cannot parse registry file.", e); } catch (SAXException e) { throw new PacketAnalyzerRegistryException("Cannot parse registry file", e); } catch (Throwable e) { throw new PacketAnalyzerRegistryException("Cannot build PacketAnalyzerRegistry.", e); } }
private String encryptPassword(String password) throws NoSuchAlgorithmException { StringBuffer encryptedPassword = new StringBuffer(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(password.getBytes()); byte digest[] = md5.digest(); for (int i = 0; i < digest.length; i++) { String hex = Integer.toHexString(0xFF & digest[i]); if (hex.length() == 1) { encryptedPassword.append('0'); } encryptedPassword.append(hex); } return encryptedPassword.toString(); }
631
1
private static void readAndRewrite(File inFile, File outFile) throws IOException { ImageInputStream iis = ImageIO.createImageInputStream(new BufferedInputStream(new FileInputStream(inFile))); DcmParser dcmParser = DcmParserFactory.getInstance().newDcmParser(iis); Dataset ds = DcmObjectFactory.getInstance().newDataset(); dcmParser.setDcmHandler(ds.getDcmHandler()); dcmParser.parseDcmFile(null, Tags.PixelData); PixelDataReader pdReader = pdFact.newReader(ds, iis, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); System.out.println("reading " + inFile + "..."); pdReader.readPixelData(false); ImageOutputStream out = ImageIO.createImageOutputStream(new BufferedOutputStream(new FileOutputStream(outFile))); DcmEncodeParam dcmEncParam = DcmEncodeParam.IVR_LE; ds.writeDataset(out, dcmEncParam); ds.writeHeader(out, dcmEncParam, Tags.PixelData, dcmParser.getReadVR(), dcmParser.getReadLength()); System.out.println("writing " + outFile + "..."); PixelDataWriter pdWriter = pdFact.newWriter(pdReader.getPixelDataArray(), false, ds, out, dcmParser.getDcmDecodeParam().byteOrder, dcmParser.getReadVR()); pdWriter.writePixelData(); out.flush(); out.close(); System.out.println("done!"); }
public static boolean compress(File source, File target, Manifest manifest) { try { if (!(source.exists() & source.isDirectory())) return false; if (target.exists()) target.delete(); ZipOutputStream output = null; boolean isJar = target.getName().toLowerCase().endsWith(".jar"); if (isJar) { File manifestDir = new File(source, "META-INF"); remove(manifestDir); if (manifest != null) output = new JarOutputStream(new FileOutputStream(target), manifest); else output = new JarOutputStream(new FileOutputStream(target)); } else output = new ZipOutputStream(new FileOutputStream(target)); ArrayList list = getContents(source); String baseDir = source.getAbsolutePath().replace('\\', '/'); if (!baseDir.endsWith("/")) baseDir = baseDir + "/"; int baseDirLength = baseDir.length(); byte[] buffer = new byte[1024]; int bytesRead; for (int i = 0, n = list.size(); i < n; i++) { File file = (File) list.get(i); FileInputStream f_in = new FileInputStream(file); String filename = file.getAbsolutePath().replace('\\', '/'); if (filename.startsWith(baseDir)) filename = filename.substring(baseDirLength); if (isJar) output.putNextEntry(new JarEntry(filename)); else output.putNextEntry(new ZipEntry(filename)); while ((bytesRead = f_in.read(buffer)) != -1) output.write(buffer, 0, bytesRead); f_in.close(); output.closeEntry(); } output.close(); } catch (Exception exc) { exc.printStackTrace(); return false; } return true; }
632
0
protected Connection openRelativeFile(String file) throws IOException { if (cachedBits == null) { cachedBits = new ByteArray(url.openConnection().getInputStream()).getBytes(); } ZipInputStream zin = new ZipInputStream(new ByteArrayInputStream(cachedBits)); ZipEntry zentry; while (true) { zentry = zin.getNextEntry(); if (zentry == null) { throw new IOException("Couldn't find resource " + file + " in ZIP-file"); } if (zentry.getName().equals(file)) { return new Connection(zin, zentry.getSize()); } } }
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletConfig config = getServletConfig(); ServletContext context = config.getServletContext(); try { String driver = context.getInitParameter("driver"); Class.forName(driver); String dbURL = context.getInitParameter("db"); String username = context.getInitParameter("username"); String password = ""; connection = DriverManager.getConnection(dbURL, username, password); } catch (ClassNotFoundException e) { System.out.println("Database driver not found."); } catch (SQLException e) { System.out.println("Error opening the db connection: " + e.getMessage()); } String action = ""; String notice; String error = ""; HttpSession session = request.getSession(); session.setMaxInactiveInterval(300); if (request.getParameter("action") != null) { action = request.getParameter("action"); } else { notice = "Unknown action!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } if (action.equals("edit_events")) { String sql; String month_name = ""; int month; int year; Event event; if (request.getParameter("month") != null) { month = Integer.parseInt(request.getParameter("month")); String temp = request.getParameter("year_num"); year = Integer.parseInt(temp); int month_num = month - 1; event = new Event(year, month_num, 1); month_name = event.getMonthName(); year = event.getYearNumber(); if (month < 10) { sql = "SELECT * FROM event WHERE date LIKE '" + year + "-0" + month + "-%'"; } else { sql = "SELECT * FROM event WHERE date LIKE '" + year + "-" + month + "-%'"; } } else { event = new Event(); month_name = event.getMonthName(); month = event.getMonthNumber() + 1; year = event.getYearNumber(); sql = "SELECT * FROM event WHERE date LIKE '" + year + "-%" + month + "-%'"; } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); request.setAttribute("year", Integer.toString(year)); request.setAttribute("month", Integer.toString(month)); request.setAttribute("month_name", month_name); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_events.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving events from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_event")) { int id = Integer.parseInt(request.getParameter("id")); Event event = new Event(); event = event.getEvent(id); if (event != null) { request.setAttribute("event", event); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving event from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("save_event")) { String title = request.getParameter("title"); String description = request.getParameter("description"); String month = request.getParameter("month"); String day = request.getParameter("day"); String year = request.getParameter("year"); String start_time = ""; String end_time = ""; if (request.getParameter("all_day") == null) { String start_hour = request.getParameter("start_hour"); String start_minutes = request.getParameter("start_minutes"); String start_ampm = request.getParameter("start_ampm"); String end_hour = request.getParameter("end_hour"); String end_minutes = request.getParameter("end_minutes"); String end_ampm = request.getParameter("end_ampm"); if (Integer.parseInt(start_hour) < 10) { start_hour = "0" + start_hour; } if (Integer.parseInt(end_hour) < 10) { end_hour = "0" + end_hour; } start_time = start_hour + ":" + start_minutes + " " + start_ampm; end_time = end_hour + ":" + end_minutes + " " + end_ampm; } Event event = null; if (!start_time.equals("") && !end_time.equals("")) { event = new Event(title, description, month, day, year, start_time, end_time); } else { event = new Event(title, description, month, day, year); } if (event.saveEvent()) { notice = "Calendar event saved!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error saving calendar event."; request.setAttribute("notice", notice); request.setAttribute("event", event); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_event")) { String title = request.getParameter("title"); String description = request.getParameter("description"); String month = request.getParameter("month"); String day = request.getParameter("day"); String year = request.getParameter("year"); String start_time = ""; String end_time = ""; int id = Integer.parseInt(request.getParameter("id")); if (request.getParameter("all_day") == null) { String start_hour = request.getParameter("start_hour"); String start_minutes = request.getParameter("start_minutes"); String start_ampm = request.getParameter("start_ampm"); String end_hour = request.getParameter("end_hour"); String end_minutes = request.getParameter("end_minutes"); String end_ampm = request.getParameter("end_ampm"); if (Integer.parseInt(start_hour) < 10) { start_hour = "0" + start_hour; } if (Integer.parseInt(end_hour) < 10) { end_hour = "0" + end_hour; } start_time = start_hour + ":" + start_minutes + " " + start_ampm; end_time = end_hour + ":" + end_minutes + " " + end_ampm; } Event event = null; if (!start_time.equals("") && !end_time.equals("")) { event = new Event(title, description, month, day, year, start_time, end_time); } else { event = new Event(title, description, month, day, year); } if (event.updateEvent(id)) { notice = "Calendar event updated!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error updating calendar event."; request.setAttribute("notice", notice); request.setAttribute("event", event); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_event.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete_event")) { int id = Integer.parseInt(request.getParameter("id")); Event event = new Event(); if (event.deleteEvent(id)) { notice = "Calendar event successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_events"); dispatcher.forward(request, response); return; } else { notice = "Error deleting event from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_events"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_members")) { String sql = "SELECT * FROM person ORDER BY lname"; if (request.getParameter("member_type") != null) { String member_type = request.getParameter("member_type"); if (member_type.equals("all")) { sql = "SELECT * FROM person ORDER BY lname"; } else { sql = "SELECT * FROM person where member_type LIKE '" + member_type + "' ORDER BY lname"; } request.setAttribute("member_type", member_type); } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_members.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving members from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_person")) { int id = Integer.parseInt(request.getParameter("id")); String member_type = request.getParameter("member_type"); Person person = new Person(); person = person.getPerson(id); if (member_type.equals("student")) { Student student = person.getStudent(); request.setAttribute("student", student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_student.jsp"); dispatcher.forward(request, response); return; } else if (member_type.equals("alumni")) { Alumni alumni = person.getAlumni(); request.setAttribute("alumni", alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_alumni.jsp"); dispatcher.forward(request, response); return; } else if (member_type.equals("hospital")) { Hospital hospital = person.getHospital(id); request.setAttribute("hospital", hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_hospital.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_alumni")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Alumni cur_alumni = person.getAlumni(); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String company_name = request.getParameter("company_name"); String position = request.getParameter("position"); int mentor = 0; if (request.getParameter("mentor") != null) { mentor = 1; } String graduation_date = request.getParameter("graduation_year") + "-" + request.getParameter("graduation_month") + "-01"; String password = ""; if (request.getParameter("password") != null) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_alumni.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Alumni new_alumni = new Alumni(fname, lname, address1, address2, city, state, zip, email, password, is_admin, company_name, position, graduation_date, mentor); if (!new_alumni.getEmail().equals(cur_alumni.getEmail())) { if (new_alumni.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("alumni", new_alumni); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_alumni.updateAlumni(person_id)) { session.setAttribute("alumni", new_alumni); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Member information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("update_hospital")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Hospital cur_hospital = person.getHospital(person_id); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String name = request.getParameter("name"); String phone = request.getParameter("phone"); String url = request.getParameter("url"); String password = ""; if (cur_hospital.getPassword() != null) { if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_hospital.getPassword(); } } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Hospital new_hospital = new Hospital(fname, lname, address1, address2, city, state, zip, email, password, is_admin, name, phone, url); if (!new_hospital.getEmail().equals(cur_hospital.getEmail())) { if (new_hospital.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("hospital", new_hospital); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_hospital.updateHospital(person_id)) { session.setAttribute("hospital", new_hospital); notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("update_student")) { int person_id = Integer.parseInt(request.getParameter("person_id")); Person person = new Person(); person = person.getPerson(person_id); Student cur_student = person.getStudent(); String fname = request.getParameter("fname"); String lname = request.getParameter("lname"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String email = request.getParameter("email"); String start_date = request.getParameter("start_year") + "-" + request.getParameter("start_month") + "-01"; String graduation_date = ""; if (!request.getParameter("grad_year").equals("") && !request.getParameter("grad_month").equals("")) { graduation_date = request.getParameter("grad_year") + "-" + request.getParameter("grad_month") + "-01"; } String password = ""; if (request.getParameter("password") != null && !request.getParameter("password").equals("")) { password = request.getParameter("password"); MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); md.update(password.getBytes("UTF-8")); } catch (Exception x) { notice = "Could not encrypt your password. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } password = (new BASE64Encoder()).encode(md.digest()); } else { password = cur_student.getPassword(); } int is_admin = 0; if (request.getParameter("is_admin") != null) { is_admin = 1; } Student new_student = new Student(fname, lname, address1, address2, city, state, zip, email, password, is_admin, start_date, graduation_date); if (!new_student.getEmail().equals(cur_student.getEmail())) { if (new_student.checkEmailIsRegistered()) { notice = "That email address is already registered!"; request.setAttribute("notice", notice); request.setAttribute("student", new_student); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } } if (!new_student.updateStudent(person_id)) { notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } notice = "Information successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members"); dispatcher.forward(request, response); return; } else if (action.equals("delete_person")) { int id = Integer.parseInt(request.getParameter("id")); String member_type = request.getParameter("member_type"); Person person = new Person(); person = person.getPerson(id); if (person.deletePerson(member_type)) { notice = person.getFname() + ' ' + person.getLname() + " successfully deleted from database."; request.setAttribute("notice", notice); person = null; RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=edit_members&member_type=all"); dispatcher.forward(request, response); return; } } else if (action.equals("manage_pages")) { String sql = "SELECT * FROM pages WHERE parent_id=0 OR parent_id IN (SELECT id FROM pages WHERE title LIKE 'root')"; if (request.getParameter("id") != null) { int id = Integer.parseInt(request.getParameter("id")); sql = "SELECT * FROM pages WHERE parent_id=" + id; } try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_pages.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("add_page")) { String sql = "SELECT id, title FROM pages WHERE parent_id=0 OR parent_id IN (SELECT id FROM pages WHERE title LIKE 'root')"; try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("save_page")) { String title = request.getParameter("title"); String content = request.getParameter("content"); Page page = null; if (request.getParameter("parent_id") != null) { int parent_id = Integer.parseInt(request.getParameter("parent_id")); page = new Page(title, content, parent_id); } else { page = new Page(title, content, 0); } if (page.savePage()) { notice = "Content page saved!"; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "There was an error saving the page."; request.setAttribute("page", page); request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_page")) { String sql = "SELECT * FROM pages WHERE parent_id=0"; int id = Integer.parseInt(request.getParameter("id")); Page page = new Page(); page = page.getPage(id); try { dbStatement = connection.createStatement(); dbResultSet = dbStatement.executeQuery(sql); request.setAttribute("resultset", dbResultSet); } catch (SQLException e) { notice = "Error retrieving content pages from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } if (page != null) { request.setAttribute("page", page); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving content page from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("update_page")) { int id = Integer.parseInt(request.getParameter("id")); String title = request.getParameter("title"); String content = request.getParameter("content"); int parent_id = 0; if (request.getParameter("parent_id") != null) { parent_id = Integer.parseInt(request.getParameter("parent_id")); } Page page = new Page(title, content, parent_id); if (page.updatePage(id)) { notice = "Content page was updated successfully."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error updating the content page."; request.setAttribute("notice", notice); request.setAttribute("page", page); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_page.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete_page")) { int id = Integer.parseInt(request.getParameter("id")); Page page = new Page(); if (page.deletePage(id)) { notice = "Content page (and sub pages) deleted successfully."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the content page(s)."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("list_residencies")) { Residency residency = new Residency(); dbResultSet = residency.getResidencies(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list_residencies.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("delete_residency")) { int job_id = Integer.parseInt(request.getParameter("id")); Residency residency = new Residency(); if (residency.deleteResidency(job_id)) { notice = "Residency has been successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("edit_residency")) { int job_id = Integer.parseInt(request.getParameter("id")); Residency residency = new Residency(); dbResultSet = residency.getResidency(job_id); if (dbResultSet != null) { try { int hId = dbResultSet.getInt("hospital_id"); String hName = residency.getHospitalName(hId); request.setAttribute("hName", hName); dbResultSet.beforeFirst(); } catch (SQLException e) { error = "There was an error retreiving the residency."; session.setAttribute("error", error); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.jsp"); dispatcher.forward(request, response); return; } request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/edit_residency.jsp"); dispatcher.forward(request, response); return; } else { notice = "There was an error in locating the residency you selected."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("new_residency")) { Residency residency = new Residency(); dbResultSet = residency.getHospitals(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/add_residency.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("add_residency")) { Person person = (Person) session.getAttribute("person"); if (person.isAdmin()) { String hName = request.getParameter("hName"); String title = request.getParameter("title"); String description = request.getParameter("description"); String start_month = request.getParameter("startDateMonth"); String start_day = request.getParameter("startDateDay"); String start_year = request.getParameter("startDateYear"); String start_date = start_year + start_month + start_day; String end_month = request.getParameter("endDateMonth"); String end_day = request.getParameter("endDateDay"); String end_year = request.getParameter("endDateYear"); String end_date = end_year + end_month + end_day; String deadline_month = request.getParameter("deadlineDateMonth"); String deadline_day = request.getParameter("deadlineDateDay"); String deadline_year = request.getParameter("deadlineDateYear"); String deadline_date = deadline_year + deadline_month + deadline_day; int hId = Integer.parseInt(request.getParameter("hId")); Residency residency = new Residency(title, start_date, end_date, deadline_date, description, hId); if (residency.saveResidency()) { notice = "Residency has been successfully saved."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error saving the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("update_residency")) { Person person = (Person) session.getAttribute("person"); int job_id = Integer.parseInt(request.getParameter("job_id")); if (person.isAdmin()) { String hName = request.getParameter("hName"); String title = request.getParameter("title"); String description = request.getParameter("description"); String start_month = request.getParameter("startDateMonth"); String start_day = request.getParameter("startDateDay"); String start_year = request.getParameter("startDateYear"); String start_date = start_year + start_month + start_day; String end_month = request.getParameter("endDateMonth"); String end_day = request.getParameter("endDateDay"); String end_year = request.getParameter("endDateYear"); String end_date = end_year + end_month + end_day; String deadline_month = request.getParameter("deadlineDateMonth"); String deadline_day = request.getParameter("deadlineDateDay"); String deadline_year = request.getParameter("deadlineDateYear"); String deadline_date = deadline_year + deadline_month + deadline_day; int hId = Integer.parseInt(request.getParameter("hId")); Residency residency = new Residency(job_id, title, start_date, end_date, deadline_date, description); if (residency.updateResidency(job_id)) { notice = "Residency has been successfully saved."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=list_residencies"); dispatcher.forward(request, response); return; } else { notice = "Error saving the residency."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("add_hospital")) { Person person = (Person) session.getAttribute("person"); if (person.isAdmin()) { String name = request.getParameter("name"); String url = request.getParameter("url"); String address1 = request.getParameter("address1"); String address2 = request.getParameter("address2"); String city = request.getParameter("city"); String state = request.getParameter("state"); String zip = request.getParameter("zip"); String phone = request.getParameter("phone"); String lname = request.getParameter("name"); Hospital hospital = new Hospital(lname, address1, address2, city, state, zip, name, phone, url); if (!hospital.saveHospitalAdmin()) { notice = "There was an error saving your information. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=new_residency"); dispatcher.forward(request, response); return; } else { notice = "Unknown request. Please try again."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Get Admin News List")) { News news = new News(); if (news.getNewsList() != null) { dbResultSet = news.getNewsList(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news list."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Get News List")) { News news = new News(); if (news.getNewsList() != null) { dbResultSet = news.getNewsList(); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_list.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news list."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/gsu_fhce/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("detail")) { String id = request.getParameter("id"); News news = new News(); if (news.getNewsDetail(id) != null) { dbResultSet = news.getNewsDetail(id); request.setAttribute("result", dbResultSet); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_detail.jsp"); dispatcher.forward(request, response); return; } else { notice = "Could not get news detail."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("delete")) { int id = 0; id = Integer.parseInt(request.getParameter("id")); News news = new News(); if (news.deleteNews(id)) { notice = "News successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } } else if (action.equals("edit")) { int id = Integer.parseInt(request.getParameter("id")); News news = new News(); news = news.getNews(id); if (news != null) { request.setAttribute("news", news); request.setAttribute("id", Integer.toString(id)); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/news_update.jsp"); dispatcher.forward(request, response); return; } else { notice = "Error retrieving news from the database."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("Update News")) { String title = request.getParameter("title"); String date = (request.getParameter("year")) + (request.getParameter("month")) + (request.getParameter("day")); String content = request.getParameter("content"); int id = Integer.parseInt(request.getParameter("newsid")); News news = new News(title, date, content); if (news.updateNews(id)) { notice = "News successfully updated."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Could not update news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } } else if (action.equals("Add News")) { String id = ""; String title = request.getParameter("title"); String date = request.getParameter("year") + "-" + request.getParameter("month") + "-" + request.getParameter("day"); String content = request.getParameter("content"); News news = new News(title, date, content); if (news.addNews()) { notice = "News successfully added."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=Get Admin News List"); dispatcher.forward(request, response); return; } else { notice = "Could not add news."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("admin/index.jsp"); dispatcher.forward(request, response); return; } } else if (action.equals("manage_mship")) { Mentor mentor = new Mentor(); dbResultSet = mentor.getMentorships(); if (dbResultSet != null) { request.setAttribute("result", dbResultSet); } else { notice = "There are no current mentorships."; request.setAttribute("notice", notice); } RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/list_mentorships.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("delete_mship")) { int mentorship_id = Integer.parseInt(request.getParameter("id")); Mentor mentor = new Mentor(); if (mentor.delMentorship(mentorship_id)) { notice = "Mentorship successfully deleted."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } else { notice = "Error deleting the mentorship."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } } else if (action.equals("new_mship")) { Mentor mentor = new Mentor(); ResultSet alumnis = null; ResultSet students = null; alumnis = mentor.getAlumnis(); students = mentor.getStudents(); request.setAttribute("alumni_result", alumnis); request.setAttribute("student_result", students); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/create_mship.jsp"); dispatcher.forward(request, response); return; } else if (action.equals("create_mship")) { int student_id = Integer.parseInt(request.getParameter("student_id")); int alumni_id = Integer.parseInt(request.getParameter("alumni_id")); Mentor mentor = new Mentor(); if (mentor.addMentorship(student_id, alumni_id)) { notice = "Mentorship successfully created."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin?action=manage_mship"); dispatcher.forward(request, response); return; } else { notice = "There was an error creating the mentorship."; request.setAttribute("notice", notice); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/admin/create_mship.jsp"); dispatcher.forward(request, response); return; } } }
633
0
public void aprovarCandidato(Atividade atividade) throws SQLException { Connection conn = null; String insert = "update Atividade_has_recurso_humano set ativo='true' " + "where atividade_idatividade=" + atividade.getIdAtividade() + " and " + " usuario_idusuario=" + atividade.getRecursoHumano().getIdUsuario(); try { conn = connectionFactory.getConnection(true); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); Integer result = stmt.executeUpdate(insert); conn.commit(); } catch (SQLException e) { conn.rollback(); throw e; } finally { conn.close(); } }
public void sorter() { String inputLine1, inputLine2; String epiNames[] = new String[1000]; String epiEpisodes[] = new String[1000]; int lineCounter = 0; try { String pluginDir = pluginInterface.getPluginDirectoryName(); String eplist_file = pluginDir + System.getProperty("file.separator") + "EpisodeList.txt"; File episodeList = new File(eplist_file); if (!episodeList.isFile()) { episodeList.createNewFile(); } final BufferedReader in = new BufferedReader(new FileReader(episodeList)); while ((inputLine1 = in.readLine()) != null) { if ((inputLine2 = in.readLine()) != null) { epiNames[lineCounter] = inputLine1; epiEpisodes[lineCounter] = inputLine2; lineCounter++; } } in.close(); int epiLength = epiNames.length; for (int i = 0; i < (lineCounter); i++) { for (int j = 0; j < (lineCounter - 1); j++) { if (epiNames[j].compareToIgnoreCase(epiNames[j + 1]) > 0) { String temp = epiNames[j]; epiNames[j] = epiNames[j + 1]; epiNames[j + 1] = temp; String temp2 = epiEpisodes[j]; epiEpisodes[j] = epiEpisodes[j + 1]; epiEpisodes[j + 1] = temp2; } } } File episodeList2 = new File(eplist_file); BufferedWriter bufWriter = new BufferedWriter(new FileWriter(episodeList2)); for (int i = 0; i <= lineCounter; i++) { if (epiNames[i] == null) { break; } bufWriter.write(epiNames[i] + "\n"); bufWriter.write(epiEpisodes[i] + "\n"); } bufWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
634
1
public static void decoupe(String input_file_path) { final int BUFFER_SIZE = 2000000; try { FileInputStream fr = new FileInputStream(input_file_path); byte[] cbuf = new byte[BUFFER_SIZE]; int n_read = 0; int i = 0; boolean bContinue = true; while (bContinue) { n_read = fr.read(cbuf, 0, BUFFER_SIZE); if (n_read == -1) break; FileOutputStream fo = new FileOutputStream("f_" + ++i); fo.write(cbuf, 0, n_read); fo.close(); } fr.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void Copy() throws IOException { if (!FileDestination.exists()) { FileDestination.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(FileSource).getChannel(); destination = new FileOutputStream(FileDestination).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if (source != null) { source.close(); } if (destination != null) { destination.close(); } } }
635
0
public static boolean checkVersion(String vers) throws IOException { try { String tmp = ""; URL url = new URL("http://rbmsoft.com.br/apis/ql/index.php?url=null&versao=" + vers); BufferedInputStream buf = new BufferedInputStream(url.openStream()); int dado = 0; char letra; while ((dado = buf.read()) != -1) { letra = (char) dado; tmp += letra; } if (tmp.contains("FALSE")) { return false; } else if (tmp.contains("TRUE")) { new UpdateCheck().updateDialog(); return true; } } catch (MalformedURLException e) { e.printStackTrace(); } return false; }
private static String readURL(URL url) { String s = ""; try { BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s += str; } in.close(); } catch (Exception e) { s = null; } return s; }
636
1
private static void ftpTest() { FTPClient f = new FTPClient(); try { f.connect("oscomak.net"); System.out.print(f.getReplyString()); f.setFileType(FTPClient.BINARY_FILE_TYPE); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String password = JOptionPane.showInputDialog("Enter password"); if (password == null || password.equals("")) { System.out.println("No password"); return; } try { f.login("oscomak_pointrel", password); System.out.print(f.getReplyString()); } catch (IOException e) { e.printStackTrace(); } try { String workingDirectory = f.printWorkingDirectory(); System.out.println("Working directory: " + workingDirectory); System.out.print(f.getReplyString()); } catch (IOException e1) { e1.printStackTrace(); } try { f.enterLocalPassiveMode(); System.out.print(f.getReplyString()); System.out.println("Trying to list files"); String[] fileNames = f.listNames(); System.out.print(f.getReplyString()); System.out.println("Got file list fileNames: " + fileNames.length); for (String fileName : fileNames) { System.out.println("File: " + fileName); } System.out.println(); System.out.println("done reading stream"); System.out.println("trying alterative way to read stream"); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); f.retrieveFile(fileNames[0], outputStream); System.out.println("size: " + outputStream.size()); System.out.println(outputStream.toString()); System.out.println("done with alternative"); System.out.println("Trying to store file back"); ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); boolean storeResult = f.storeFile("test.txt", inputStream); System.out.println("Done storing " + storeResult); f.disconnect(); System.out.print(f.getReplyString()); System.out.println("disconnected"); } catch (IOException e) { e.printStackTrace(); } }
public int extractDocumentsInternal(DocumentHolder holder, DocumentFactory docFactory) { FTPClient client = new FTPClient(); try { client.connect(site, port == 0 ? 21 : port); client.login(user, password); visitDirectory(client, "", path, holder, docFactory); client.disconnect(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { } return fileCount; }
637
0
public String get(String question) { try { System.out.println(url + question); URL urlonlineserver = new URL(url + question); BufferedReader in = new BufferedReader(new InputStreamReader(urlonlineserver.openStream())); String inputLine; String returnstring = ""; while ((inputLine = in.readLine()) != null) returnstring += inputLine; in.close(); return returnstring; } catch (IOException e) { return ""; } }
public VersionInfo getVersionInfo(String url) { try { XmlContentHandler handler = new XmlContentHandler(); XMLReader myReader = XMLReaderFactory.createXMLReader(); myReader.setContentHandler(handler); myReader.parse(new InputSource(new URL(url).openStream())); return handler.getVersionInfo(); } catch (SAXException e) { if (debug) { println("SAXException was thrown!"); e.printStackTrace(); } } catch (MalformedURLException e) { if (debug) { println("MalformedURLException was thrown!"); e.printStackTrace(); } } catch (IOException e) { if (debug) { println("IOException was thrown!"); e.printStackTrace(); } } return null; }
638
1
public static void copyFile(File sourceFile, File destFile) throws IOException { FileChannel inputFileChannel = new FileInputStream(sourceFile).getChannel(); FileChannel outputFileChannel = new FileOutputStream(destFile).getChannel(); long offset = 0L; long length = inputFileChannel.size(); final long MAXTRANSFERBUFFERLENGTH = 1024 * 1024; try { for (; offset < length; ) { offset += inputFileChannel.transferTo(offset, MAXTRANSFERBUFFERLENGTH, outputFileChannel); inputFileChannel.position(offset); } } finally { try { outputFileChannel.close(); } catch (Exception ignore) { } try { inputFileChannel.close(); } catch (IOException ignore) { } } }
public static Checksum checksum(File file, Checksum checksum) throws IOException { if (file.isDirectory()) { throw new IllegalArgumentException("Checksums can't be computed on directories"); } InputStream in = null; try { in = new CheckedInputStream(new FileInputStream(file), checksum); IOUtils.copy(in, new NullOutputStream()); } finally { IOUtils.closeQuietly(in); } return checksum; }
639
0
public AddressType[] getAdressFromCRSCoordinate(Point3d crs_position) { AddressType[] result = null; String postRequest = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n" + "<xls:XLS xmlns:xls=\"http://www.opengis.net/xls\" xmlns:sch=\"http://www.ascc.net/xml/schematron\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/xls \n" + " http://gdi3d.giub.uni-bonn.de/lus/schemas/LocationUtilityService.xsd\" version=\"1.1\"> \n" + " <xls:RequestHeader srsName=\"EPSG:" + Navigator.getEpsg_code() + "\"/> \n" + " <xls:Request methodName=\"ReverseGeocodeRequest\" requestID=\"123456789\" version=\"1.1\"> \n" + " <xls:ReverseGeocodeRequest> \n" + " <xls:Position> \n" + " <gml:Point srsName=\"" + Navigator.getEpsg_code() + "\"> \n" + " <gml:pos>" + crs_position.x + " " + crs_position.y + "</gml:pos> \n" + " </gml:Point> \n" + " </xls:Position> \n" + " <xls:ReverseGeocodePreference>StreetAddress</xls:ReverseGeocodePreference> \n" + " </xls:ReverseGeocodeRequest> \n" + " </xls:Request> \n" + "</xls:XLS> \n"; try { if (Navigator.isVerbose()) { System.out.println("contacting " + serviceEndPoint + ":\n" + postRequest); } URL u = new URL(serviceEndPoint); HttpURLConnection urlc = (HttpURLConnection) u.openConnection(); urlc.setReadTimeout(Navigator.TIME_OUT); urlc.setAllowUserInteraction(false); urlc.setRequestMethod("POST"); urlc.setRequestProperty("Content-Type", "application/xml"); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); PrintWriter xmlOut = null; xmlOut = new java.io.PrintWriter(urlc.getOutputStream()); xmlOut.write(postRequest); xmlOut.flush(); xmlOut.close(); InputStream is = urlc.getInputStream(); XLSDocument xlsResponse = XLSDocument.Factory.parse(is); is.close(); XLSType xlsTypeResponse = xlsResponse.getXLS(); AbstractBodyType abBodyResponse[] = xlsTypeResponse.getBodyArray(); ResponseType response = (ResponseType) abBodyResponse[0].changeType(ResponseType.type); AbstractResponseParametersType respParam = response.getResponseParameters(); if (respParam == null) { return null; } ReverseGeocodeResponseType drResp = (ReverseGeocodeResponseType) respParam.changeType(ReverseGeocodeResponseType.type); net.opengis.xls.ReverseGeocodedLocationType[] types = drResp.getReverseGeocodedLocationArray(); int num = types.length; if (num > 2) { return null; } result = new AddressType[num]; for (int i = 0; i < num; i++) { String addressDescription = "<b>"; net.opengis.xls.ReverseGeocodedLocationType type = types[i]; result[i] = type.getAddress(); } } catch (java.net.ConnectException ce) { JOptionPane.showMessageDialog(null, "no connection to reverse geocoder", "Connection Error", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { e.printStackTrace(); } return result; }
@Override public Collection<IAuthor> doImport() throws Exception { progress.initialize(2, "Ściągam autorów amerykańskich"); String url = "http://pl.wikipedia.org/wiki/Kategoria:Ameryka%C5%84scy_autorzy_fantastyki"; UrlResource resource = new UrlResource(url); InputStream urlInputStream = resource.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(urlInputStream, writer); progress.advance("Parsuję autorów amerykańskich"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String httpDoc = writer.toString(); httpDoc = httpDoc.replaceFirst("(?s)<!DOCTYPE.+?>\\n", ""); httpDoc = httpDoc.replaceAll("(?s)<script.+?</script>", ""); httpDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" + httpDoc; ByteArrayInputStream byteInputStream = new ByteArrayInputStream(httpDoc.getBytes("UTF-8")); Document doc = builder.parse(byteInputStream); ArrayList<String> authorNames = new ArrayList<String>(); ArrayList<IAuthor> authors = new ArrayList<IAuthor>(); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList list = (NodeList) xpath.evaluate("//ul/li/div/div/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } list = (NodeList) xpath.evaluate("//td/ul/li/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } for (String name : authorNames) { int idx = name.lastIndexOf(' '); String fname = name.substring(0, idx).trim(); String lname = name.substring(idx + 1).trim(); authors.add(new Author(fname, lname)); } progress.advance("Wykonano"); return authors; }
640
0
public static void main(String[] args) throws Exception { if (args.length < 3) { usage(System.out); System.exit(1); } final File tmpFile = File.createTempFile("sej", null); tmpFile.deleteOnExit(); final FileOutputStream destination = new FileOutputStream(tmpFile); final String mainClass = args[1]; final Collection jars = new LinkedList(); for (int i = 2; i < args.length; i++) { String arg = args[i]; jars.add(arg); } JarInterpretted interpretted = new JarInterpretted(destination); JarCat rowr = new JarCat(destination, createManifest(mainClass), jars); interpretted.write(); rowr.write(); destination.close(); final File finalDestinationFile = new File(args[0]); final FileOutputStream finalDestination = new FileOutputStream(finalDestinationFile); IOUtils.copy(new FileInputStream(tmpFile), finalDestination); finalDestination.close(); Chmod chmod = new Chmod("a+rx", new File[] { finalDestinationFile }); chmod.invoke(); }
public ResponseStatus nowPlaying(String artist, String track, String album, int length, int tracknumber) throws IOException { if (sessionId == null) throw new IllegalStateException("Perform successful handshake first."); String b = album != null ? encode(album) : ""; String l = length == -1 ? "" : String.valueOf(length); String n = tracknumber == -1 ? "" : String.valueOf(tracknumber); String body = String.format("s=%s&a=%s&t=%s&b=%s&l=%s&n=%s&m=", sessionId, encode(artist), encode(track), b, l, n); if (Caller.getInstance().isDebugMode()) System.out.println("now playing: " + body); Proxy proxy = Caller.getInstance().getProxy(); HttpURLConnection urlConnection = Caller.getInstance().openConnection(nowPlayingUrl); urlConnection.setRequestMethod("POST"); urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream)); writer.write(body); writer.close(); InputStream is = urlConnection.getInputStream(); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String status = r.readLine(); r.close(); return new ResponseStatus(ResponseStatus.codeForStatus(status)); }
641
0
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()); }
private static String hashPassword(String password, String customsalt) throws NoSuchAlgorithmException, UnsupportedEncodingException { password = SALT1 + password; MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(password.getBytes(), 0, password.length()); password += convertToHex(md5.digest()) + SALT2 + customsalt; MessageDigest md = MessageDigest.getInstance("SHA-512"); byte[] sha1hash = new byte[40]; md.update(password.getBytes("UTF-8"), 0, password.length()); sha1hash = md.digest(); return convertToHex(sha1hash) + "|" + customsalt; }
642
0
public void delete(String fileToDelete) throws IOException { FTPClient ftp = new FTPClient(); try { int reply = 0; ftp.connect(this.endpointURL, this.endpointPort); reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); throw new IOException("Ftp delete server refused connection."); } if (!ftp.login("anonymous", "")) { ftp.logout(); throw new IOException("FTP: server wrong passwd"); } ftp.enterLocalPassiveMode(); log.debug("Deleted: " + ftp.deleteFile(fileToDelete)); ftp.logout(); } catch (Exception e) { throw new IOException(e.getMessage()); } }
public static String getResourceFromURL(URL url, String acceptHeader) throws java.io.IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Accept", acceptHeader); urlConnection.setInstanceFollowRedirects(true); BufferedReader input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String content = ""; String line; while ((line = input.readLine()) != null) { content += line; } input.close(); return content; }
643
1
public boolean copy(File fromFile) throws IOException { FileUtility toFile = this; if (!fromFile.exists()) { abort("FileUtility: no such source file: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.isFile()) { abort("FileUtility: can't copy directory: " + fromFile.getAbsolutePath()); return false; } if (!fromFile.canRead()) { abort("FileUtility: source file is unreadable: " + fromFile.getAbsolutePath()); return false; } if (this.isDirectory()) toFile = (FileUtility) (new File(this, fromFile.getName())); if (toFile.exists()) { if (!toFile.canWrite()) { abort("FileUtility: destination file is unwriteable: " + pathName); return false; } } else { String parent = toFile.getParent(); File dir = new File(parent); if (!dir.exists()) { abort("FileUtility: destination directory doesn't exist: " + parent); return false; } if (dir.isFile()) { abort("FileUtility: destination is not a directory: " + parent); return false; } if (!dir.canWrite()) { abort("FileUtility: destination directory is unwriteable: " + parent); return false; } } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } return true; }
public void actionPerformed(java.awt.event.ActionEvent e) { JFileChooser fc = new JFileChooser(); fc.addChoosableFileFilter(new ImageFilter()); fc.setAccessory(new ImagePreview(fc)); int returnVal = fc.showDialog(AdministracionResorces.this, Messages.getString("gui.AdministracionResorces.8")); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String rutaGlobal = System.getProperty("user.dir") + "/" + rutaDatos + "imagenes/" + file.getName(); String rutaRelativa = rutaDatos + "imagenes/" + file.getName(); try { FileInputStream fis = new FileInputStream(file); FileOutputStream fos = new FileOutputStream(rutaGlobal, true); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); imagen.setImagenURL(rutaRelativa); gui.getEntrenamientoIzquierdaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesIzquierda().getSelectedItem()).getImagenURL())); gui.getEntrenamientoDerechaLabel().setIcon(gui.getProcesadorDatos().escalaImageIcon(((Imagen) gui.getComboBoxImagenesDerecha().getSelectedItem()).getImagenURL())); buttonImagen.setIcon(new ImageIcon(getClass().getResource("/es/unizar/cps/tecnoDiscap/data/icons/view_sidetreeOK.png"))); labelImagenPreview.setIcon(gui.getProcesadorDatos().escalaImageIcon(imagen.getImagenURL())); } catch (IOException ex) { ex.printStackTrace(); } } else { } }
644
0
protected InputStream makeSignedRequestAndGetJSONData(String url) { try { if (consumer == null) loginOAuth(); } catch (Exception e) { consumer = null; e.printStackTrace(); } DefaultHttpClient httpClient = new DefaultHttpClient(); URI uri; InputStream data = null; try { uri = new URI(url); HttpGet method = new HttpGet(uri); consumer.sign(method); HttpResponse response = httpClient.execute(method); data = response.getEntity().getContent(); } catch (Exception e) { e.printStackTrace(); } return data; }
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; }
645
1
protected void truncate(File file) { LogLog.debug("Compression of file: " + file.getAbsolutePath() + " started."); if (FileUtils.isFileOlder(file, ManagementFactory.getRuntimeMXBean().getStartTime())) { File backupRoot = new File(getBackupDir()); if (!backupRoot.exists() && !backupRoot.mkdirs()) { throw new AppenderInitializationError("Can't create backup dir for backup storage"); } SimpleDateFormat df; try { df = new SimpleDateFormat(getBackupDateFormat()); } catch (Exception e) { throw new AppenderInitializationError("Invalid date formate for backup files: " + getBackupDateFormat(), e); } String date = df.format(new Date(file.lastModified())); File zipFile = new File(backupRoot, file.getName() + "." + date + ".zip"); ZipOutputStream zos = null; FileInputStream fis = null; try { zos = new ZipOutputStream(new FileOutputStream(zipFile)); ZipEntry entry = new ZipEntry(file.getName()); entry.setMethod(ZipEntry.DEFLATED); entry.setCrc(FileUtils.checksumCRC32(file)); zos.putNextEntry(entry); fis = FileUtils.openInputStream(file); byte[] buffer = new byte[1024]; int readed; while ((readed = fis.read(buffer)) != -1) { zos.write(buffer, 0, readed); } } catch (Exception e) { throw new AppenderInitializationError("Can't create zip file", e); } finally { if (zos != null) { try { zos.close(); } catch (IOException e) { LogLog.warn("Can't close zip file", e); } } if (fis != null) { try { fis.close(); } catch (IOException e) { LogLog.warn("Can't close zipped file", e); } } } if (!file.delete()) { throw new AppenderInitializationError("Can't delete old log file " + file.getAbsolutePath()); } } }
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(); }
646
0
private static void writeOneAttachment(Context context, Writer writer, OutputStream out, Attachment attachment) throws IOException, MessagingException { writeHeader(writer, "Content-Type", attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\""); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writeHeader(writer, "Content-Disposition", "attachment;" + "\n filename=\"" + attachment.mFileName + "\";" + "\n size=" + Long.toString(attachment.mSize)); writeHeader(writer, "Content-ID", attachment.mContentId); writer.append("\r\n"); InputStream inStream = null; try { Uri fileUri = Uri.parse(attachment.mContentUri); inStream = context.getContentResolver().openInputStream(fileUri); writer.flush(); Base64OutputStream base64Out = new Base64OutputStream(out); IOUtils.copy(inStream, base64Out); base64Out.close(); } catch (FileNotFoundException fnfe) { } catch (IOException ioe) { throw new MessagingException("Invalid attachment.", ioe); } }
private Properties loadProperties(final String propertiesName) throws IOException { Properties bundle = null; final ClassLoader loader = Thread.currentThread().getContextClassLoader(); final URL url = loader.getResource(propertiesName); if (url == null) { throw new IOException("Properties file " + propertiesName + " not found"); } final InputStream is = url.openStream(); if (is != null) { bundle = new Properties(); bundle.load(is); } else { throw new IOException("Properties file " + propertiesName + " not avilable"); } return bundle; }
647
0
private void loadDBpediaOntology() { try { URL url = new URL("http://downloads.dbpedia.org/3.6/dbpedia_3.6.owl.bz2"); InputStream is = new BufferedInputStream(url.openStream()); CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is); dbPediaOntology = OWLManager.createOWLOntologyManager().loadOntologyFromOntologyDocument(in); reasoner = PelletReasonerFactory.getInstance().createNonBufferingReasoner(dbPediaOntology); reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (CompressorException e) { e.printStackTrace(); } catch (OWLOntologyCreationException e) { e.printStackTrace(); } }
public int[] do_it(final int[] x) { int temp = 0; int j = x.length; while (j > 0) { for (int i = 0; i < j - 1; i++) { if (x[i] > x[i + 1]) { temp = x[i]; x[i] = x[i + 1]; x[i + 1] = temp; } ; } ; j--; } ; return x; }
648
1
public void copy(String pathFileIn, String pathFileOut) { try { File inputFile = new File(pathFileIn); File outputFile = new File(pathFileOut); FileReader in = new FileReader(inputFile); File outDir = new File(DirOut); if (!outDir.exists()) outDir.mkdirs(); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); this.printColumn(inputFile.getName(), outputFile.getPath()); } catch (Exception e) { e.printStackTrace(); } }
public static void copy(File src, File dest, boolean overwrite) throws IOException { if (!src.exists()) throw new IOException("File source does not exists"); if (dest.exists()) { if (!overwrite) throw new IOException("File destination already exists"); dest.delete(); } else { dest.createNewFile(); } InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dest); byte[] buffer = new byte[1024 * 4]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } os.close(); is.close(); }
649
1
public static String generateDigest(String message, String DigestAlgorithm) { try { MessageDigest md = MessageDigest.getInstance(DigestAlgorithm); md.update(message.getBytes(), 0, message.length()); return new BigInteger(1, md.digest()).toString(16); } catch (NoSuchAlgorithmException nsae) { return null; } }
public String md5Encode(String pass) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } md.update(pass.getBytes()); byte[] result = md.digest(); return new String(result); }
650
1
private String MD5Sum(String input) { String hashtext = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.reset(); md.update(input.getBytes()); byte[] digest = md.digest(); BigInteger bigInt = new BigInteger(1, digest); hashtext = bigInt.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashtext; }
private String md5(String... args) throws FlickrException { try { StringBuilder sb = new StringBuilder(); for (String str : args) { sb.append(str); } MessageDigest md = MessageDigest.getInstance("MD5"); md.update(sb.toString().getBytes()); byte[] bytes = md.digest(); StringBuilder result = new StringBuilder(); for (byte b : bytes) { String hx = Integer.toHexString(0xFF & b); if (hx.length() == 1) { hx = "0" + hx; } result.append(hx); } return result.toString(); } catch (Exception ex) { throw new FlickrException(ex); } }
651
1
public boolean copy(File src, File dest, byte[] b) { if (src.isDirectory()) { String[] ss = src.list(); for (int i = 0; i < ss.length; i++) if (!copy(new File(src, ss[i]), new File(dest, ss[i]), b)) return false; return true; } delete(dest); dest.getParentFile().mkdirs(); try { FileInputStream fis = new FileInputStream(src); try { FileOutputStream fos = new FileOutputStream(dest); try { int read; while ((read = fis.read(b)) != -1) fos.write(b, 0, read); } finally { try { fos.close(); } catch (IOException ignore) { } register(dest); } } finally { fis.close(); } if (log.isDebugEnabled()) log.debug("Success: M-COPY " + src + " -> " + dest); return true; } catch (IOException e) { log.error("Failed: M-COPY " + src + " -> " + dest, e); return false; } }
public static void fileCopy(final File src, final File dest, final boolean overwrite) throws IOException { if (!dest.exists() || (dest.exists() && overwrite)) { final FileChannel srcChannel = new FileInputStream(src).getChannel(); final FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } }
652
1
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
private void invokeTest(String queryfile, String target) { try { String query = IOUtils.toString(XPathMarkBenchmarkTest.class.getResourceAsStream(queryfile)).trim(); String args = EXEC_CMD + " \"" + query + "\" \"" + target + '"'; System.out.println("Invoke command: \n " + args); Process proc = Runtime.getRuntime().exec(args, null, benchmarkDir); InputStream is = proc.getInputStream(); File outFile = new File(outDir, queryfile + ".result"); IOUtils.copy(is, new FileOutputStream(outFile)); is.close(); int ret = proc.waitFor(); if (ret != 0) { System.out.println("process exited with value : " + ret); } } catch (IOException ioe) { throw new IllegalStateException(ioe); } catch (InterruptedException irre) { throw new IllegalStateException(irre); } }
653
1
public static void copyFile(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); try { FileChannel destinationChannel = new FileOutputStream(out).getChannel(); try { sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); } finally { destinationChannel.close(); } } finally { sourceChannel.close(); } }
public void loadXML(URL flux, int status, File file) { try { SAXBuilder sbx = new SAXBuilder(); try { if (file.exists()) { file.delete(); } if (!file.exists()) { URLConnection conn = flux.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(10000); InputStream is = conn.getInputStream(); OutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = is.read(buf)) > 0) out.write(buf, 0, len); out.close(); is.close(); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "Exeption retrieving XML", e); } try { document = sbx.build(new FileInputStream(file)); } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "xml error ", e); } } catch (Exception e) { Log.e(Constants.PROJECT_TAG, "TsukiQueryError", e); } if (document != null) { root = document.getRootElement(); PopulateDatabase(root, status); } }
654
1
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
@Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final String url = req.getParameter("url"); if (!isAllowed(url)) { resp.setStatus(HttpServletResponse.SC_FORBIDDEN); return; } final HttpClient client = new HttpClient(); client.getParams().setVersion(HttpVersion.HTTP_1_0); final PostMethod method = new PostMethod(url); method.getParams().setVersion(HttpVersion.HTTP_1_0); method.setFollowRedirects(false); final RequestEntity entity = new InputStreamRequestEntity(req.getInputStream()); method.setRequestEntity(entity); try { final int statusCode = client.executeMethod(method); if (statusCode != -1) { InputStream is = null; ServletOutputStream os = null; try { is = method.getResponseBodyAsStream(); try { os = resp.getOutputStream(); IOUtils.copy(is, os); } finally { if (os != null) { try { os.flush(); } catch (IOException ignored) { } } } } catch (IOException ioex) { final String message = ioex.getMessage(); if (!"chunked stream ended unexpectedly".equals(message)) { throw ioex; } } finally { IOUtils.closeQuietly(is); } } } finally { method.releaseConnection(); } }
655
0
@Before public void BeforeTheTest() throws Exception { URL url = ProfileParserTest.class.getClassLoader().getResource("ca/uhn/hl7v2/conf/parser/tests/example_ack.xml"); URLConnection conn = url.openConnection(); InputStream instream = conn.getInputStream(); if (instream == null) throw new Exception("can't find the xml file"); BufferedReader in = new BufferedReader(new InputStreamReader(instream)); int tmp = 0; StringBuffer buf = new StringBuffer(); while ((tmp = in.read()) != -1) { buf.append((char) tmp); } profileString = buf.toString(); }
public static void copy(File fromFile, File toFile) throws IOException { if (!fromFile.exists()) throw new IOException("FileCopy: " + "no such source file: " + fromFile.getCanonicalPath()); if (!fromFile.isFile()) throw new IOException("FileCopy: " + "can't copy directory: " + fromFile.getCanonicalPath()); if (!fromFile.canRead()) throw new IOException("FileCopy: " + "source file is unreadable: " + fromFile.getCanonicalPath()); if (toFile.isDirectory()) toFile = new File(toFile, fromFile.getName()); if (toFile.exists()) { if (!toFile.canWrite()) throw new IOException("FileCopy: " + "destination file is unwriteable: " + toFile.getCanonicalPath()); throw new IOException("FileCopy: " + "existing file was not overwritten."); } else { String parent = toFile.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent); if (dir.isFile()) throw new IOException("FileCopy: " + "destination is not a directory: " + parent); if (!dir.canWrite()) throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(fromFile); to = new FileOutputStream(toFile); byte[] buffer = new byte[1024 * 1024]; int bytesRead; while ((bytesRead = from.read(buffer)) != -1) to.write(buffer, 0, bytesRead); if (fromFile.isHidden()) { } toFile.setLastModified(fromFile.lastModified()); toFile.setExecutable(fromFile.canExecute()); toFile.setReadable(fromFile.canRead()); toFile.setWritable(toFile.canWrite()); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
656
1
public static String encodeFromFile(String filename) throws java.io.IOException, URISyntaxException { String encodedData = null; Base641.InputStream bis = null; File file; try { URL url = new URL(filename); URLConnection conn = url.openConnection(); file = new File("myfile.doc"); java.io.InputStream inputStream = (java.io.InputStream) conn.getInputStream(); FileOutputStream out = new FileOutputStream(file); byte buf[] = new byte[1024]; int len; while ((len = inputStream.read(buf)) > 0) out.write(buf, 0, len); out.close(); inputStream.close(); byte[] buffer = new byte[Math.max((int) (file.length() * 1.4), 40)]; int length = 0; int numBytes = 0; bis = new Base641.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(file)), Base641.ENCODE); while ((numBytes = bis.read(buffer, length, 4096)) >= 0) { length += numBytes; } encodedData = new String(buffer, 0, length, Base641.PREFERRED_ENCODING); } catch (java.io.IOException e) { throw e; } finally { try { bis.close(); } catch (Exception e) { } } return encodedData; }
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); } }
657
0
public static String getDocumentAsString(URL url) throws IOException { StringBuffer result = new StringBuffer(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8")); String line = ""; while (line != null) { result.append(line); line = in.readLine(); } return result.toString(); }
@Override public void onClick(View v) { username = textusername.getText().toString(); password = textpassword.getText().toString(); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new name_value("uname", username)); nameValuePairs.add(new name_value("upass", password)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://www.gotrackit.net/server/check_user.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection" + e.toString()); } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line = "0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } if (result.contains("reject")) { Context context = getApplicationContext(); int duration = Toast.LENGTH_SHORT; String wrong = "Invalid Username or Password"; Toast toast = Toast.makeText(context, wrong, duration); toast.show(); } else { MyApp uid = (MyApp) getApplicationContext(); uid.setStringValue(result); Intent myintent = new Intent(v.getContext(), UserMap.class); startActivityForResult(myintent, 0); } }
658
1
private String copyTutorial() throws IOException { File inputFile = new File(getFilenameForOriginalTutorial()); File outputFile = new File(getFilenameForCopiedTutorial()); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); return getFilenameForCopiedTutorial(); }
public static boolean copy(File src, FileSystem dstFS, Path dst, boolean deleteSource, Configuration conf) throws IOException { dst = checkDest(src.getName(), dstFS, dst, false); if (src.isDirectory()) { if (!dstFS.mkdirs(dst)) { return false; } File contents[] = src.listFiles(); for (int i = 0; i < contents.length; i++) { copy(contents[i], dstFS, new Path(dst, contents[i].getName()), deleteSource, conf); } } else if (src.isFile()) { InputStream in = null; OutputStream out = null; try { in = new FileInputStream(src); out = dstFS.create(dst); IOUtils.copyBytes(in, out, conf); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } if (deleteSource) { return FileUtil.fullyDelete(src); } else { return true; } }
659
0
public void deleteUser(String userID) throws XregistryException { try { userID = Utils.canonicalizeDN(userID); Connection connection = context.createConnection(); connection.setAutoCommit(false); try { PreparedStatement statement1 = connection.prepareStatement(DELETE_USER_SQL_MAIN); statement1.setString(1, userID); statement1.executeUpdate(); PreparedStatement statement2 = connection.prepareStatement(DELETE_USER_SQL_DEPEND); statement2.setString(1, userID); statement2.executeUpdate(); connection.commit(); Collection<Group> groupList = groups.values(); for (Group group : groupList) { group.removeUser(userID); } log.info("Delete User " + userID); } catch (SQLException e) { connection.rollback(); throw new XregistryException(e); } finally { context.closeConnection(connection); } } catch (SQLException e) { throw new XregistryException(e); } }
public static int doPost(String urlString, String username, String password, Map<String, String> parameters) throws IOException { PrintWriter out = null; try { URL url = new URL(urlString); URLConnection connection = url.openConnection(); if (username != null && password != null) { String encoding = base64Encode(username + ':' + password); connection.setRequestProperty("Authorization", "Basic " + encoding); } connection.setDoOutput(true); out = new PrintWriter(connection.getOutputStream()); boolean first = true; for (Map.Entry<String, String> entry : parameters.entrySet()) { if (first) { first = false; } else { out.print('&'); } out.print(entry.getKey()); out.print('='); out.print(URLEncoder.encode(entry.getValue(), "UTF-8")); } out.close(); connection.connect(); if (!(connection instanceof HttpURLConnection)) { throw new IOException(); } return ((HttpURLConnection) connection).getResponseCode(); } catch (IOException ex) { throw ex; } finally { if (out != null) { out.close(); } } }
660
1
public static boolean writeFileByChars(Reader pReader, File pFile, boolean pAppend) { boolean flag = false; try { FileWriter fw = new FileWriter(pFile, pAppend); IOUtils.copy(pReader, fw); fw.flush(); fw.close(); pReader.close(); flag = true; } catch (Exception e) { LOG.error("将字符流写入�?" + pFile.getName() + "出现异常�?", e); } return flag; }
public static void copyFile(File src, File dst) throws IOException { InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); }
661
0
@Test public void test_baseMaterialsForTypeID_StringInsteadOfID() throws Exception { URL url = new URL(baseUrl + "/baseMaterialsForTypeID/blah-blah"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json"); assertThat(connection.getResponseCode(), equalTo(400)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); assertThat(connection.getResponseCode(), equalTo(400)); }
private void processBasicContent() { String[] packageNames = sourceCollector.getPackageNames(); for (int i = 0; i < packageNames.length; i++) { XdcSource[] sources = sourceCollector.getXdcSources(packageNames[i]); File dir = new File(outputDir, packageNames[i]); dir.mkdirs(); Set pkgDirs = new HashSet(); for (int j = 0; j < sources.length; j++) { XdcSource source = sources[j]; Properties patterns = source.getPatterns(); if (patterns != null) { tables.put("patterns", patterns); } pkgDirs.add(source.getFile().getParentFile()); DialectHandler dialectHandler = source.getDialectHandler(); Writer out = null; try { String sourceFilePath = source.getFile().getAbsolutePath(); source.setProcessingProperties(baseProperties, j > 0 ? sources[j - 1].getFileName() : null, j < sources.length - 1 ? sources[j + 1].getFileName() : null); String rootComment = XslUtils.transformToString(sourceFilePath, XSL_PKG + "/source-header.xsl", tables); source.setRootComment(rootComment); Document htmlDoc = XslUtils.transform(sourceFilePath, encoding, dialectHandler.getXslResourcePath(), tables); if (LOG.isInfoEnabled()) { LOG.info("Processing source file " + sourceFilePath); } out = IOUtils.getWriter(new File(dir, source.getFile().getName() + ".html"), docencoding); XmlUtils.printHtml(out, htmlDoc); if (sourceProcessor != null) { sourceProcessor.processSource(source, encoding, docencoding); } XdcSource.clearProcessingProperties(baseProperties); } catch (XmlException e) { LOG.error(e.getMessage(), e); } catch (IOException e) { LOG.error(e.getMessage(), e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } for (Iterator iter = pkgDirs.iterator(); iter.hasNext(); ) { File docFilesDir = new File((File) iter.next(), "xdc-doc-files"); if (docFilesDir.exists() && docFilesDir.isDirectory()) { File targetDir = new File(dir, "xdc-doc-files"); targetDir.mkdirs(); try { IOUtils.copyTree(docFilesDir, targetDir); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } }
662
1
private String extractFileFromZip(ZipFile zip, String fileName) throws IOException { String contents = null; ZipEntry entry = zip.getEntry(fileName); if (entry != null) { InputStream input = zip.getInputStream(entry); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); IOUtils.copyAndClose(input, buffer); contents = buffer.toString(); } return contents; }
public static void copyFile(final FileInputStream in, final File out) throws IOException { final FileChannel inChannel = in.getChannel(); final FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (final IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
663
0
private Response doLoad(URL url, URL referer, String postData) throws IOException { URLConnection connection = PROXY == null ? url.openConnection() : url.openConnection(PROXY); COOKIES.writeCookies(connection); connection.setRequestProperty("User-Agent", USER_AGENT); if (referer != null) { connection.setRequestProperty("Referer", referer.toString()); } if (postData != null) { connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestProperty("CONTENT_LENGTH", "" + postData.length()); OutputStream os = connection.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(os); osw.write(postData); osw.flush(); osw.close(); } connection.connect(); COOKIES.readCookies(connection); previouseUrl = url; return responceInstance(url, connection.getInputStream(), connection.getContentType()); }
public List tree(String cat, int branch) { Pattern p = Pattern.compile("<a href=\"javascript:checkBranch\\(([0-9]+), 'true'\\)\">([^<]*)</a>"); Matcher m; List res = new ArrayList(); URL url; HttpURLConnection conn; System.out.println(); try { url = new URL("http://cri-srv-ade.insa-toulouse.fr:8080/ade/standard/gui/tree.jsp?category=trainee&expand=false&forceLoad=false&reload=false&scroll=0"); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Cookie", sessionId); BufferedReader i = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = i.readLine()) != null) { m = p.matcher(line); if (m.find()) { trainee.add(new Node(Integer.parseInt(m.group(1)), m.group(2))); System.out.println(m.group(1) + " - " + m.group(2)); } } } catch (Exception e2) { e2.printStackTrace(); } return res; }
664
0
@Override public void execute(JobExecutionContext context) throws JobExecutionException { super.execute(context); debug("Start execute job " + this.getClass().getName()); try { String name = "nixspam-ip.dump.gz"; String f = this.path_app_root + "/" + this.properties.get("dir") + "/"; try { org.apache.commons.io.FileUtils.forceMkdir(new File(f)); } catch (IOException ex) { fatal("IOException", ex); } f += "/" + name; String url = "http://www.dnsbl.manitu.net/download/" + name; debug("(1) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); com.utils.IOUtil.unzip(f, f.replace(".gz", "")); File file_to_read = new File(f.replaceAll(".gz", "")); BigFile lines = null; try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Excpetion", e); return; } try { Statement stat = conn_url.createStatement(); stat.executeUpdate(properties.get("query_delete")); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } boolean ok = true; int i = 0; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.substring(line.indexOf(" ")); line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } boolean del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); name = "spam-ip.com_" + DateTimeUtil.getNowWithFormat("MM-dd-yyyy") + ".csv"; f = this.path_app_root + "/" + this.properties.get("dir") + "/"; org.apache.commons.io.FileUtils.forceMkdir(new File(f)); f += "/" + name; url = "http://spam-ip.com/csv_dump/" + name; debug("(2) - start download: " + url); com.utils.HttpUtil.downloadData(url, f); file_to_read = new File(f); try { lines = new BigFile(file_to_read.toString()); } catch (Exception e) { fatal("Exception", e); return; } try { conn_url.setAutoCommit(false); } catch (SQLException e) { fatal("SQLException", e); } ok = true; for (String line : lines) { if (StringUtil.isEmpty(line) || line.indexOf(" ") == -1) { continue; } try { line = line.split(",")[1]; line = line.trim(); if (getIPException(line)) { continue; } Statement stat = this.conn_url.createStatement(); stat.executeUpdate("insert into blacklist(url) values('" + line + "')"); stat.close(); i++; } catch (SQLException e) { fatal("SQLException", e); try { conn_url.rollback(); } catch (SQLException ex) { fatal("SQLException", ex); } ok = false; break; } } del = file_to_read.delete(); debug("File " + file_to_read + " del:" + del); if (ok) { debug("Import della BlackList Concluso tot righe: " + i); try { conn_url.commit(); } catch (SQLException e) { fatal("SQLException", e); } } else { fatal("Problemi con la Blacklist"); } try { conn_url.setAutoCommit(true); } catch (SQLException e) { fatal("SQLException", e); } try { Statement stat = this.conn_url.createStatement(); stat.executeUpdate("VACUUM"); stat.close(); } catch (SQLException e) { fatal("SQLException", e); } } catch (IOException ex) { fatal("IOException", ex); } debug("End execute job " + this.getClass().getName()); }
private boolean serverOK(String serverAddress, String serverPort) { boolean status = false; String serverString = serverAddress + ":" + serverPort + MolConvertInNodeModel.SERVER_WSDL_PATH; System.out.println("connecting to " + serverString + "..."); try { java.net.URL url = new java.net.URL(serverString); try { java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); status = readContents(connection); if (status) { JOptionPane.showMessageDialog(this.getPanel(), "Connection to Server is OK"); } } catch (Exception connEx) { JOptionPane.showMessageDialog(this.getPanel(), connEx.getMessage()); logger.error(connEx.getMessage()); } } catch (java.net.MalformedURLException urlEx) { JOptionPane.showMessageDialog(this.getPanel(), urlEx.getMessage()); logger.error(urlEx.getMessage()); } return status; }
665
1
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
private String GetStringFromURL(String URL) { InputStream in = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; String outstring = ""; try { java.net.URL url = new java.net.URL(URL); in = url.openStream(); inputStreamReader = new InputStreamReader(in); bufferedReader = new BufferedReader(inputStreamReader); StringBuffer out = new StringBuffer(""); String nextLine; String newline = System.getProperty("line.separator"); while ((nextLine = bufferedReader.readLine()) != null) { out.append(nextLine); out.append(newline); } outstring = new String(out); } catch (IOException e) { System.out.println("Failed to read from " + URL); outstring = ""; } finally { try { bufferedReader.close(); inputStreamReader.close(); } catch (Exception e) { } } return outstring; }
666
1
private File uploadFile(InputStream inputStream, File file) { FileOutputStream fileOutputStream = null; try { File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } FileUtils.touch(file); fileOutputStream = new FileOutputStream(file); IOUtils.copy(inputStream, fileOutputStream); } catch (IOException e) { throw new FileOperationException("Failed to save uploaded image", e); } finally { try { if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { LOGGER.warn("Failed to close resources on uploaded file", e); } } return file; }
public BufferedWriter createOutputStream(String inFile, String outFile) throws IOException { int k_blockSize = 1024; int byteCount; char[] buf = new char[k_blockSize]; File ofp = new File(outFile); ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(ofp)); zos.setMethod(ZipOutputStream.DEFLATED); OutputStreamWriter osw = new OutputStreamWriter(zos, "ISO-8859-1"); BufferedWriter bw = new BufferedWriter(osw); ZipEntry zot = null; File ifp = new File(inFile); ZipInputStream zis = new ZipInputStream(new FileInputStream(ifp)); InputStreamReader isr = new InputStreamReader(zis, "ISO-8859-1"); BufferedReader br = new BufferedReader(isr); ZipEntry zit = null; while ((zit = zis.getNextEntry()) != null) { if (zit.getName().equals("content.xml")) { continue; } zot = new ZipEntry(zit.getName()); zos.putNextEntry(zot); while ((byteCount = br.read(buf, 0, k_blockSize)) >= 0) bw.write(buf, 0, byteCount); bw.flush(); zos.closeEntry(); } zos.putNextEntry(new ZipEntry("content.xml")); bw.flush(); osw = new OutputStreamWriter(zos, "UTF8"); bw = new BufferedWriter(osw); return bw; }
667
1
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { String name = metadata.get(Metadata.RESOURCE_NAME_KEY); if (name != null && wanted.containsKey(name)) { FileOutputStream out = new FileOutputStream(wanted.get(name)); IOUtils.copy(stream, out); out.close(); } else { if (downstreamParser != null) { downstreamParser.parse(stream, handler, metadata, context); } } }
@Override public Collection<IAuthor> doImport() throws Exception { progress.initialize(2, "Ściągam autorów amerykańskich"); String url = "http://pl.wikipedia.org/wiki/Kategoria:Ameryka%C5%84scy_autorzy_fantastyki"; UrlResource resource = new UrlResource(url); InputStream urlInputStream = resource.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(urlInputStream, writer); progress.advance("Parsuję autorów amerykańskich"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String httpDoc = writer.toString(); httpDoc = httpDoc.replaceFirst("(?s)<!DOCTYPE.+?>\\n", ""); httpDoc = httpDoc.replaceAll("(?s)<script.+?</script>", ""); httpDoc = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" + httpDoc; ByteArrayInputStream byteInputStream = new ByteArrayInputStream(httpDoc.getBytes("UTF-8")); Document doc = builder.parse(byteInputStream); ArrayList<String> authorNames = new ArrayList<String>(); ArrayList<IAuthor> authors = new ArrayList<IAuthor>(); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); NodeList list = (NodeList) xpath.evaluate("//ul/li/div/div/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } list = (NodeList) xpath.evaluate("//td/ul/li/a", doc, XPathConstants.NODESET); for (int i = 0; i < list.getLength(); i++) { String name = list.item(i).getTextContent(); if (StringUtils.isNotBlank(name)) { authorNames.add(name); } } for (String name : authorNames) { int idx = name.lastIndexOf(' '); String fname = name.substring(0, idx).trim(); String lname = name.substring(idx + 1).trim(); authors.add(new Author(fname, lname)); } progress.advance("Wykonano"); return authors; }
668
0
public User createUser(Map userData) throws HamboFatalException { DBConnection con = null; try { con = DBServiceManager.allocateConnection(); con.setAutoCommit(false); String userId = (String) userData.get(HamboUser.USER_ID); String sql = "insert into user_UserAccount " + "(userid,firstname,lastname,street,zipcode,city," + "province,country,email,cellph,gender,password," + "language,timezn,birthday,datecreated,lastlogin," + "disabled,wapsigned,ldapInSync,offerings,firstcb) " + "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, userId); ps.setString(2, (String) userData.get(HamboUser.FIRST_NAME)); ps.setString(3, (String) userData.get(HamboUser.LAST_NAME)); ps.setString(4, (String) userData.get(HamboUser.STREET_ADDRESS)); ps.setString(5, (String) userData.get(HamboUser.ZIP_CODE)); ps.setString(6, (String) userData.get(HamboUser.CITY)); ps.setString(7, (String) userData.get(HamboUser.STATE)); ps.setString(8, (String) userData.get(HamboUser.COUNTRY)); ps.setString(9, (String) userData.get(HamboUser.EXTERNAL_EMAIL_ADDRESS)); ps.setString(10, (String) userData.get(HamboUser.MOBILE_NUMBER)); ps.setString(11, (String) userData.get(HamboUser.GENDER)); ps.setString(12, (String) userData.get(HamboUser.PASSWORD)); ps.setString(13, (String) userData.get(HamboUser.LANGUAGE)); ps.setString(14, (String) userData.get(HamboUser.TIME_ZONE)); java.sql.Date date = (java.sql.Date) userData.get(HamboUser.BIRTHDAY); if (date != null) ps.setDate(15, date); else ps.setNull(15, Types.DATE); date = (java.sql.Date) userData.get(HamboUser.CREATED); if (date != null) ps.setDate(16, date); else ps.setNull(16, Types.DATE); date = (java.sql.Date) userData.get(HamboUser.LAST_LOGIN); if (date != null) ps.setDate(17, date); else ps.setNull(17, Types.DATE); Boolean bool = (Boolean) userData.get(HamboUser.DISABLED); if (bool != null) ps.setBoolean(18, bool.booleanValue()); else ps.setBoolean(18, UserAccountInfo.DEFAULT_DISABLED); bool = (Boolean) userData.get(HamboUser.WAP_ACCOUNT); if (bool != null) ps.setBoolean(19, bool.booleanValue()); else ps.setBoolean(19, UserAccountInfo.DEFAULT_WAP_ACCOUNT); bool = (Boolean) userData.get(HamboUser.LDAP_IN_SYNC); if (bool != null) ps.setBoolean(20, bool.booleanValue()); else ps.setBoolean(20, UserAccountInfo.DEFAULT_LDAP_IN_SYNC); bool = (Boolean) userData.get(HamboUser.OFFERINGS); if (bool != null) ps.setBoolean(21, bool.booleanValue()); else ps.setBoolean(21, UserAccountInfo.DEFAULT_OFFERINGS); ps.setString(22, (String) userData.get(HamboUser.COBRANDING_ID)); con.executeUpdate(ps, null); ps = con.prepareStatement(DBUtil.getQueryCurrentOID(con, "user_UserAccount", "newoid")); ResultSet rs = con.executeQuery(ps, null); if (rs.next()) { OID newOID = new OID(rs.getBigDecimal("newoid").doubleValue()); userData.put(HamboUser.OID, newOID); } con.commit(); } catch (Exception ex) { if (con != null) try { con.rollback(); } catch (SQLException sqlex) { } throw new HamboFatalException(MSG_INSERT_FAILED, ex); } finally { if (con != null) try { con.reset(); } catch (SQLException ex) { } if (con != null) con.release(); } return buildUser(userData); }
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(); }
669
1
public void xtest1() throws Exception { InputStream input = new FileInputStream("C:/Documentos/j931_01.pdf"); InputStream tmp = new ITextManager().cut(input, 3, 8); FileOutputStream output = new FileOutputStream("C:/temp/split.pdf"); IOUtils.copy(tmp, output); input.close(); tmp.close(); output.close(); }
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileOutputStream fos = new FileOutputStream(out); FileChannel outChannel = fos.getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); fos.flush(); fos.close(); } }
670
0
private static void zip(ZipOutputStream aOutputStream, final File[] aFiles, final String sArchive, final URI aRootURI, final String sFilter) throws FileError { boolean closeStream = false; if (aOutputStream == null) try { aOutputStream = new ZipOutputStream(new FileOutputStream(sArchive)); closeStream = true; } catch (final FileNotFoundException e) { throw new FileError("Can't create ODF file!", e); } try { try { for (final File curFile : aFiles) { aOutputStream.putNextEntry(new ZipEntry(URLDecoder.decode(aRootURI.relativize(curFile.toURI()).toASCIIString(), "UTF-8"))); if (curFile.isDirectory()) { aOutputStream.closeEntry(); FileUtils.zip(aOutputStream, FileUtils.getFiles(curFile, sFilter), sArchive, aRootURI, sFilter); continue; } final FileInputStream inputStream = new FileInputStream(curFile); for (int i; (i = inputStream.read(FileUtils.BUFFER)) != -1; ) aOutputStream.write(FileUtils.BUFFER, 0, i); inputStream.close(); aOutputStream.closeEntry(); } } finally { if (closeStream && aOutputStream != null) aOutputStream.close(); } } catch (final IOException e) { throw new FileError("Can't zip file to archive!", e); } if (closeStream) DocumentController.getStaticLogger().fine(aFiles.length + " files and folders zipped as " + sArchive); }
public static String harvestForUser(Node userNode, String alias, Boolean all) { FTPClient client = new FTPClient(); OutputStream outStream = null; Calendar filterCal = Calendar.getInstance(); filterCal.set(Calendar.DAY_OF_MONTH, filterCal.get(Calendar.DAY_OF_MONTH) - 1); Date aDayAgo = filterCal.getTime(); String outputRecord = ""; try { Session session = CustomSystemSession.create(r); client.connect(ftpHostname); client.login(ftpUsername, ftpPassword); FTPFile[] users = client.listFiles(); if (users != null) { for (FTPFile user : users) { String userName = user.getName(); if (alias.equals(userName)) { outputRecord += "Found account " + userName + ".\n"; client.changeWorkingDirectory("/" + userName + "/"); FTPFile[] experiments = client.listFiles(); if (experiments != null && userNode != null) { for (FTPFile experiment : experiments) { String experimentName = experiment.getName(); outputRecord += "Exploring " + userName + "/" + experimentName + ".\n"; client.changeWorkingDirectory("/" + userName + "/" + experimentName + "/"); FTPFile[] datasets = client.listFiles(); if (datasets != null) { for (FTPFile dataset : datasets) { String datasetName = dataset.getName(); outputRecord += "Exploring " + userName + "/" + experimentName + "/" + datasetName + ".\n"; client.changeWorkingDirectory("/" + userName + "/" + experimentName + "/" + datasetName + "/"); Date collectionDate = dataset.getTimestamp().getTime(); if (collectionDate.after(aDayAgo) || all) { FTPFile[] images = client.listFiles(); if (images != null) { for (FTPFile image : images) { outputRecord += processImage(userName, experimentName, datasetName, collectionDate, image, client, userNode, session); } } } } } } } } } } client.logout(); } catch (IOException ioe) { log.info("Error communicating with FTP server."); log.error("Error communicating with FTP server.", ioe); ioe.printStackTrace(); } catch (RepositoryException ioe) { log.info("Error communicating with repository."); log.error("Error communicating with repository.", ioe); ioe.printStackTrace(); } finally { IOUtils.closeQuietly(outStream); try { client.disconnect(); } catch (IOException e) { log.error("Problem disconnecting from FTP server", e); } } return outputRecord; }
671
0
@Test(expected = GadgetException.class) public void malformedGadgetSpecThrows() throws Exception { HttpRequest request = createIgnoreCacheRequest(); expect(pipeline.execute(request)).andReturn(new HttpResponse("malformed junk")); replay(pipeline); specFactory.getGadgetSpec(createContext(SPEC_URL, true)); }
public Configuration(URL url) { InputStream in = null; try { load(in = url.openStream()); } catch (Exception e) { throw new RuntimeException("Could not load configuration from " + url, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
672
0
public Vector decode(final URL url) throws IOException { LineNumberReader reader; if (owner != null) { reader = new LineNumberReader(new InputStreamReader(new ProgressMonitorInputStream(owner, "Loading " + url, url.openStream()))); } else { reader = new LineNumberReader(new InputStreamReader(url.openStream())); } Vector v = new Vector(); String line; Vector events; try { while ((line = reader.readLine()) != null) { StringBuffer buffer = new StringBuffer(line); for (int i = 0; i < 1000; i++) { buffer.append(reader.readLine()).append("\n"); } events = decodeEvents(buffer.toString()); if (events != null) { v.addAll(events); } } } finally { partialEvent = null; try { if (reader != null) { reader.close(); } } catch (Exception e) { e.printStackTrace(); } } return v; }
public void loadScripts() { org.apache.batik.script.Window window = null; NodeList scripts = document.getElementsByTagNameNS(SVGConstants.SVG_NAMESPACE_URI, SVGConstants.SVG_SCRIPT_TAG); int len = scripts.getLength(); if (len == 0) { return; } for (int i = 0; i < len; i++) { Element script = (Element) scripts.item(i); String type = script.getAttributeNS(null, SVGConstants.SVG_TYPE_ATTRIBUTE); if (type.length() == 0) { type = SVGConstants.SVG_SCRIPT_TYPE_DEFAULT_VALUE; } if (type.equals(SVGConstants.SVG_SCRIPT_TYPE_JAVA)) { try { String href = XLinkSupport.getXLinkHref(script); ParsedURL purl = new ParsedURL(XMLBaseSupport.getCascadedXMLBase(script), href); checkCompatibleScriptURL(type, purl); DocumentJarClassLoader cll; URL docURL = null; try { docURL = new URL(docPURL.toString()); } catch (MalformedURLException mue) { } cll = new DocumentJarClassLoader(new URL(purl.toString()), docURL); URL url = cll.findResource("META-INF/MANIFEST.MF"); if (url == null) { continue; } Manifest man = new Manifest(url.openStream()); String sh; sh = man.getMainAttributes().getValue("Script-Handler"); if (sh != null) { ScriptHandler h; h = (ScriptHandler) cll.loadClass(sh).newInstance(); if (window == null) { window = createWindow(); } h.run(document, window); } sh = man.getMainAttributes().getValue("SVG-Handler-Class"); if (sh != null) { EventListenerInitializer initializer; initializer = (EventListenerInitializer) cll.loadClass(sh).newInstance(); if (window == null) { window = createWindow(); } initializer.initializeEventListeners((SVGDocument) document); } } catch (Exception e) { if (userAgent != null) { userAgent.displayError(e); } } continue; } Interpreter interpreter = getInterpreter(type); if (interpreter == null) continue; try { String href = XLinkSupport.getXLinkHref(script); String desc = null; Reader reader; if (href.length() > 0) { desc = href; ParsedURL purl = new ParsedURL(XMLBaseSupport.getCascadedXMLBase(script), href); checkCompatibleScriptURL(type, purl); reader = new InputStreamReader(purl.openStream()); } else { checkCompatibleScriptURL(type, docPURL); DocumentLoader dl = bridgeContext.getDocumentLoader(); Element e = script; SVGDocument d = (SVGDocument) e.getOwnerDocument(); int line = dl.getLineNumber(script); desc = Messages.formatMessage(INLINE_SCRIPT_DESCRIPTION, new Object[] { d.getURL(), "<" + script.getNodeName() + ">", new Integer(line) }); Node n = script.getFirstChild(); if (n != null) { StringBuffer sb = new StringBuffer(); while (n != null) { if (n.getNodeType() == Node.CDATA_SECTION_NODE || n.getNodeType() == Node.TEXT_NODE) sb.append(n.getNodeValue()); n = n.getNextSibling(); } reader = new StringReader(sb.toString()); } else { continue; } } interpreter.evaluate(reader, desc); } catch (IOException e) { if (userAgent != null) { userAgent.displayError(e); } return; } catch (InterpreterException e) { System.err.println("InterpExcept: " + e); handleInterpreterException(e); return; } catch (SecurityException e) { if (userAgent != null) { userAgent.displayError(e); } } } }
673
1
private void getImage(String filename) throws MalformedURLException, IOException, SAXException, FileNotFoundException { String url = Constants.STRATEGICDOMINATION_URL + "/images/gameimages/" + filename; WebRequest req = new GetMethodWebRequest(url); SiteResponse response = getSiteResponse(req); File file = new File("etc/images/" + filename); FileOutputStream outputStream = new FileOutputStream(file); IOUtils.copy(response.getInputStream(), outputStream); }
public void overwriteFileTest() throws Exception { File filefrom = new File("/tmp/from.txt"); File fileto = new File("/tmp/to.txt"); InputStream from = null; OutputStream to = null; try { from = new FileInputStream(filefrom); to = new FileOutputStream(fileto); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } } finally { if (from != null) { from.close(); } if (to != null) { to.close(); } } }
674
1
public static void doVersionCheck(View view) { view.showWaitCursor(); try { URL url = new URL(jEdit.getProperty("version-check.url")); InputStream in = url.openStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; String develBuild = null; String stableBuild = null; while ((line = bin.readLine()) != null) { if (line.startsWith(".build")) develBuild = line.substring(6).trim(); else if (line.startsWith(".stablebuild")) stableBuild = line.substring(12).trim(); } bin.close(); if (develBuild != null && stableBuild != null) { doVersionCheck(view, stableBuild, develBuild); } } catch (IOException e) { String[] args = { jEdit.getProperty("version-check.url"), e.toString() }; GUIUtilities.error(view, "read-error", args); } view.hideWaitCursor(); }
public static void test(String args[]) { int trace; int bytes_read = 0; int last_contentLenght = 0; try { BufferedReader reader; URL url; url = new URL(args[0]); URLConnection istream = url.openConnection(); last_contentLenght = istream.getContentLength(); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); System.out.println(url.toString()); String line; trace = t2pNewTrace(); while ((line = reader.readLine()) != null) { bytes_read = bytes_read + line.length() + 1; t2pProcessLine(trace, line); } t2pHandleEventPairs(trace); t2pSort(trace, 0); t2pExportTrace(trace, new String("pngtest2.png"), 1000, 700, (float) 0, (float) 33); t2pExportTrace(trace, new String("pngtest3.png"), 1000, 700, (float) 2.3, (float) 2.44); System.out.println("Press any key to contiune read from stream !!!"); System.out.println(t2pGetProcessName(trace, 0)); System.in.read(); istream = url.openConnection(); if (last_contentLenght != istream.getContentLength()) { istream = url.openConnection(); istream.setRequestProperty("Range", "bytes=" + Integer.toString(bytes_read) + "-"); System.out.println(Integer.toString(istream.getContentLength())); reader = new BufferedReader(new InputStreamReader(istream.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); t2pProcessLine(trace, line); } } else System.out.println("File not changed !"); t2pDeleteTrace(trace); } catch (MalformedURLException e) { System.out.println("MalformedURLException !!!"); } catch (IOException e) { System.out.println("File not found " + args[0]); } ; }
675
1
public static void copyFile(File srcFile, File desFile) throws IOException { AssertUtility.notNull(srcFile); AssertUtility.notNull(desFile); FileInputStream fis = new FileInputStream(srcFile); FileOutputStream fos = new FileOutputStream(desFile); try { FileChannel srcChannel = fis.getChannel(); FileChannel dstChannel = fos.getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } finally { fis.close(); fos.close(); } }
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; }
676
0
public boolean config(URL url, boolean throwsException) throws IllegalArgumentException { try { final MetaRoot conf = UjoManagerXML.getInstance().parseXML(new BufferedInputStream(url.openStream()), MetaRoot.class, this); config(conf); return true; } catch (Exception e) { if (throwsException) { throw new IllegalArgumentException("Configuration file is not valid ", e); } else { return false; } } }
public static String generate(String username, String password) throws PersistenceException { String output = null; try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.reset(); md.update(username.getBytes()); md.update(password.getBytes()); byte[] rawhash = md.digest(); output = byteToBase64(rawhash); } catch (Exception e) { throw new PersistenceException("error, could not generate password"); } return output; }
677
1
public static void copy(String a, String b) throws IOException { File inputFile = new File(a); File outputFile = new File(b); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }
private void handleUpload(CommonsMultipartFile file, String newFileName, String uploadDir) throws IOException, FileNotFoundException { File dirPath = new File(uploadDir); if (!dirPath.exists()) { dirPath.mkdirs(); } InputStream stream = file.getInputStream(); OutputStream bos = new FileOutputStream(uploadDir + newFileName); IOUtils.copy(stream, bos); }
678
1
public JSONObject getTargetGraph(HttpSession session, JSONObject json) throws JSONException { StringBuffer out = new StringBuffer(); Graph tgt = null; MappingManager manager = (MappingManager) session.getAttribute(RuncibleConstants.MAPPING_MANAGER.key()); try { tgt = manager.getTargetGraph(); if (tgt != null) { FlexGraphViewFactory factory = new FlexGraphViewFactory(); factory.setColorScheme(ColorSchemes.ORANGES); factory.visit(tgt); GraphView view = factory.getGraphView(); GraphViewRenderer renderer = new FlexGraphViewRenderer(); renderer.setGraphView(view); InputStream xmlStream = renderer.renderGraphView(); StringWriter writer = new StringWriter(); IOUtils.copy(xmlStream, writer); writer.close(); System.out.println(writer.toString()); out.append(writer.toString()); } else { out.append("No target graph loaded."); } } catch (Exception e) { return JSONUtils.SimpleJSONError("Cannot load target graph: " + e.getMessage()); } return JSONUtils.SimpleJSONResponse(out.toString()); }
public byte[] getFile(final String file) throws IOException { if (this.files.contains(file)) { ZipInputStream input = new ZipInputStream(new ByteArrayInputStream(this.bytes)); ZipEntry entry = input.getNextEntry(); while (entry != null) { entry = input.getNextEntry(); if ((entry.getName().equals(file)) && (!entry.isDirectory())) { ByteArrayOutputStream output = new ByteArrayOutputStream(); IOUtils.copy(input, output); output.close(); input.close(); return output.toByteArray(); } } input.close(); } return null; }
679
0
public static String getMD5Hash(String hashthis) throws NoSuchAlgorithmException { byte[] key = "PATIENTISAUTHENTICATION".getBytes(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(hashthis.getBytes()); return new String(HashUtility.base64Encode(md5.digest(key))); }
public HttpResponse execute(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("Client connection may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } try { HttpResponse response = doSendRequest(request, conn, context); if (response == null) { response = doReceiveResponse(request, conn, context); } return response; } catch (IOException ex) { conn.close(); throw ex; } catch (HttpException ex) { conn.close(); throw ex; } catch (RuntimeException ex) { conn.close(); throw ex; } }
680
1
static void copy(String src, String dest) throws IOException { File ifp = new File(src); File ofp = new File(dest); if (ifp.exists() == false) { throw new IOException("file '" + src + "' does not exist"); } FileInputStream fis = new FileInputStream(ifp); FileOutputStream fos = new FileOutputStream(ofp); byte[] b = new byte[1024]; while (fis.read(b) > 0) fos.write(b); fis.close(); fos.close(); }
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(); } }
681
1
public void extractImage(String input, OutputStream os, DjatokaDecodeParam params, IWriter w) throws DjatokaException { File in = null; if (input.equals(STDIN)) { try { in = File.createTempFile("tmp", ".jp2"); input = in.getAbsolutePath(); in.deleteOnExit(); IOUtils.copyFile(new File(STDIN), in); } catch (IOException e) { logger.error("Unable to process image from " + STDIN + ": " + e.getMessage()); throw new DjatokaException(e); } } BufferedImage bi = extractImpl.process(input, params); if (bi != null) { if (params.getScalingFactor() != 1.0 || params.getScalingDimensions() != null) bi = applyScaling(bi, params); if (params.getTransform() != null) bi = params.getTransform().run(bi); w.write(bi, os); } if (in != null) in.delete(); }
public SpreadSheetFrame(FileManager owner, File file, Delimiter delim) { super(owner, file.getPath()); JPanel pane = new JPanel(new BorderLayout()); super.contentPane.add(pane); this.tableModel = new BigTableModel(file, delim); this.table = new JTable(tableModel); this.table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); this.tableModel.setTable(this.table); pane.add(new JScrollPane(this.table)); addInternalFrameListener(new InternalFrameAdapter() { @Override public void internalFrameClosed(InternalFrameEvent e) { tableModel.close(); } }); JMenu menu = new JMenu("Tools"); getJMenuBar().add(menu); menu.add(new AbstractAction("NCBI") { @Override public void actionPerformed(ActionEvent e) { try { Pattern delim = Pattern.compile("[ ]"); BufferedReader r = new BufferedReader(new InputStreamReader(new GZIPInputStream(new FileInputStream("/home/lindenb/jeter.txt.gz")))); String line = null; URL url = new URL("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write("db=snp&retmode=xml"); while ((line = r.readLine()) != null) { String tokens[] = delim.split(line, 2); if (!tokens[0].startsWith("rs")) continue; wr.write("&id=" + tokens[0].substring(2).trim()); } wr.flush(); r.close(); InputStream in = conn.getInputStream(); IOUtils.copyTo(in, System.err); in.close(); wr.close(); } catch (IOException err) { err.printStackTrace(); } } }); }
682
1
private void initUserExtensions(SeleniumConfiguration seleniumConfiguration) throws IOException { StringBuilder contents = new StringBuilder(); StringOutputStream s = new StringOutputStream(); IOUtils.copy(SeleniumConfiguration.class.getResourceAsStream("default-user-extensions.js"), s); contents.append(s.toString()); File providedUserExtensions = seleniumConfiguration.getFile(ConfigurationPropertyKeys.SELENIUM_USER_EXTENSIONS, seleniumConfiguration.getDirectoryConfiguration().getInput(), false); if (providedUserExtensions != null) { contents.append(FileUtils.readFileToString(providedUserExtensions, null)); } seleniumUserExtensions = new File(seleniumConfiguration.getDirectoryConfiguration().getInput(), "user-extensions.js"); FileUtils.forceMkdir(seleniumUserExtensions.getParentFile()); FileUtils.writeStringToFile(seleniumUserExtensions, contents.toString(), null); }
private void write(File src, File dst, byte id3v1Tag[], byte id3v2HeadTag[], byte id3v2TailTag[]) throws IOException { if (src == null || !src.exists()) throw new IOException(Debug.getDebug("missing src", src)); if (!src.getName().toLowerCase().endsWith(".mp3")) throw new IOException(Debug.getDebug("src not mp3", src)); if (dst == null) throw new IOException(Debug.getDebug("missing dst", dst)); if (dst.exists()) { dst.delete(); if (dst.exists()) throw new IOException(Debug.getDebug("could not delete dst", dst)); } boolean hasId3v1 = new MyID3v1().hasID3v1(src); long id3v1Length = hasId3v1 ? ID3_V1_TAG_LENGTH : 0; long id3v2HeadLength = new MyID3v2().findID3v2HeadLength(src); long id3v2TailLength = new MyID3v2().findID3v2TailLength(src, hasId3v1); OutputStream os = null; InputStream is = null; try { dst.getParentFile().mkdirs(); os = new FileOutputStream(dst); os = new BufferedOutputStream(os); if (!skipId3v2Head && !skipId3v2 && id3v2HeadTag != null) os.write(id3v2HeadTag); is = new FileInputStream(src); is = new BufferedInputStream(is); is.skip(id3v2HeadLength); long total_to_read = src.length(); total_to_read -= id3v1Length; total_to_read -= id3v2HeadLength; total_to_read -= id3v2TailLength; byte buffer[] = new byte[1024]; long total_read = 0; while (total_read < total_to_read) { int remainder = (int) (total_to_read - total_read); int readSize = Math.min(buffer.length, remainder); int read = is.read(buffer, 0, readSize); if (read <= 0) throw new IOException("unexpected EOF"); os.write(buffer, 0, read); total_read += read; } if (!skipId3v2Tail && !skipId3v2 && id3v2TailTag != null) os.write(id3v2TailTag); if (!skipId3v1 && id3v1Tag != null) os.write(id3v1Tag); } finally { try { if (is != null) is.close(); } catch (Throwable e) { Debug.debug(e); } try { if (os != null) os.close(); } catch (Throwable e) { Debug.debug(e); } } }
683
1
public static synchronized String getPageContent(String pageUrl) { URL url = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; String line = null; StringBuilder page = null; if (pageUrl == null || pageUrl.trim().length() == 0) { return null; } else { try { url = new URL(pageUrl); inputStreamReader = new InputStreamReader(url.openStream()); bufferedReader = new BufferedReader(inputStreamReader); page = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { page.append(line); page.append("\n"); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } finally { try { if (bufferedReader != null) { bufferedReader.close(); } if (inputStreamReader != null) { inputStreamReader.close(); } } catch (IOException e) { logger.error("IOException", e); } catch (Exception e) { logger.error("Exception", e); } } } if (page == null) { return null; } else { return page.toString(); } }
public void access() { Authenticator.setDefault(new MyAuthenticator()); try { URL url = new URL("http://localhost/ws/test"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } }
684
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(); } } }
protected void copyFile(String from, String to, String workingDirectory) throws Exception { URL monitorCallShellScriptUrl = Thread.currentThread().getContextClassLoader().getResource(from); File f = new File(monitorCallShellScriptUrl.getFile()); String directoryPath = f.getAbsolutePath(); String fileName = from; InputStream in = null; if (directoryPath.indexOf(".jar!") > -1) { URL urlJar = new URL(directoryPath.substring(directoryPath.indexOf("file:"), directoryPath.indexOf('!'))); JarFile jf = new JarFile(urlJar.getFile()); JarEntry je = jf.getJarEntry(from); fileName = je.getName(); in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); } else { in = new FileInputStream(f); } File outScriptFile = new File(to); FileOutputStream fos = new FileOutputStream(outScriptFile); int nextChar; while ((nextChar = in.read()) != -1) fos.write(nextChar); fos.flush(); fos.close(); try { LinuxCommandExecutor cmdExecutor = new LinuxCommandExecutor(); cmdExecutor.setWorkingDirectory(workingDirectory); cmdExecutor.runCommand("chmod 777 " + to); } catch (Exception e) { throw e; } }
685
1
public static final String encryptSHA(String decrypted) { try { MessageDigest sha = MessageDigest.getInstance("SHA-1"); sha.reset(); sha.update(decrypted.getBytes()); byte hash[] = sha.digest(); sha.reset(); return hashToHex(hash); } catch (NoSuchAlgorithmException _ex) { return null; } }
public Attributes getAttributes() throws SchemaViolationException, NoSuchAlgorithmException, UnsupportedEncodingException { BasicAttributes outAttrs = new BasicAttributes(true); BasicAttribute oc = new BasicAttribute("objectclass", "inetOrgPerson"); oc.add("organizationalPerson"); oc.add("person"); outAttrs.put(oc); if (lastName != null && firstName != null) { outAttrs.put("sn", lastName); outAttrs.put("givenName", firstName); outAttrs.put("cn", firstName + " " + lastName); } else { throw new SchemaViolationException("user must have surname"); } if (password != null) { MessageDigest sha = MessageDigest.getInstance("md5"); sha.reset(); sha.update(password.getBytes("utf-8")); byte[] digest = sha.digest(); String hash = Base64.encodeBase64String(digest); outAttrs.put("userPassword", "{MD5}" + hash); } if (email != null) { outAttrs.put("mail", email); } return (Attributes) outAttrs; }
686
0
public boolean sendMail(MailObject mail, boolean backup) throws NetworkException, ContentException { HttpClient client = HttpConfig.newInstance(); HttpPost post = new HttpPost(HttpConfig.bbsURL() + HttpConfig.BBS_MAIL_SEND); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(HttpConfig.BBS_MAIL_SEND_REF_PARAM_NAME, "pstmail")); nvps.add(new BasicNameValuePair(HttpConfig.BBS_MAIL_SEND_RECV_PARAM_NAME, mail.getSender())); nvps.add(new BasicNameValuePair(HttpConfig.BBS_MAIL_SEND_TITLE_PARAM_NAME, mail.getTitle())); nvps.add(new BasicNameValuePair(HttpConfig.BBS_MAIL_SEND_CONTENT_PARAM_NAME, mail.getContent())); if (backup) nvps.add(new BasicNameValuePair(HttpConfig.BBS_MAIL_SEND_BACKUP_PARAM_NAME, "backup")); try { post.setEntity(new UrlEncodedFormEntity(nvps, BBSBodyParseHelper.BBS_CHARSET)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); if (HTTPUtil.isHttp200(response)) { HTTPUtil.consume(response.getEntity()); return true; } else { String msg = BBSBodyParseHelper.parseFailMsg(entity); throw new ContentException(msg); } } catch (ClientProtocolException e) { e.printStackTrace(); throw new NetworkException(e); } catch (IOException e) { e.printStackTrace(); throw new NetworkException(e); } }
private void save() { int[] selection = list.getSelectionIndices(); String dir = System.getProperty("user.dir"); for (int i = 0; i < selection.length; i++) { File src = files[selection[i]]; FileDialog dialog = new FileDialog(shell, SWT.SAVE); dialog.setFilterPath(dir); dialog.setFileName(src.getName()); String destination = dialog.open(); if (destination != null) { File dest = new File(destination); try { dest.createNewFile(); FileChannel srcC = new FileInputStream(src).getChannel(); FileChannel destC = new FileOutputStream(dest).getChannel(); destC.transferFrom(srcC, 0, srcC.size()); destC.close(); srcC.close(); updateSaved(selection[i], true); files[selection[i]] = dest; } catch (FileNotFoundException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } catch (IOException e) { IVC.showError("Error!", "" + e.getMessage(), ""); } } } }
687
0
public <E extends Exception> void doWithConnection(String httpAddress, ICallableWithParameter<Void, URLConnection, E> toDo) throws E, ConnectionException { URLConnection connection; try { URL url = new URL(httpAddress); connection = url.openConnection(); } catch (MalformedURLException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } catch (IOException e) { throw new ConnectionException("Connecting to " + httpAddress + " got", e); } authenticationHandler.doWithProxyAuthentication(connection, toDo); }
public static String md5(String input) { byte[] temp; try { MessageDigest messageDigest; messageDigest = MessageDigest.getInstance("MD5"); messageDigest.update(input.getBytes()); temp = messageDigest.digest(); } catch (Exception e) { return null; } return MyUtils.byte2HexStr(temp); }
688
1
public static void unzipAndRemove(final String file) { String destination = file.substring(0, file.length() - 3); InputStream is = null; OutputStream os = null; try { is = new GZIPInputStream(new FileInputStream(file)); os = new FileOutputStream(destination); byte[] buffer = new byte[8192]; for (int length; (length = is.read(buffer)) != -1; ) os.write(buffer, 0, length); } catch (IOException e) { System.err.println("Fehler: Kann nicht entpacken " + file); } finally { if (os != null) try { os.close(); } catch (IOException e) { } if (is != null) try { is.close(); } catch (IOException e) { } } deleteFile(file); }
private void putAlgosFromJar(File jarfile, AlgoDir dir, Model model) throws FileNotFoundException, IOException { URLClassLoader urlLoader = new URLClassLoader(new URL[] { jarfile.toURI().toURL() }); JarInputStream jis = new JarInputStream(new FileInputStream(jarfile)); JarEntry entry = jis.getNextJarEntry(); String name = null; String tmpdir = System.getProperty("user.dir") + File.separator + Application.getProperty("dir.tmp") + File.separator; byte[] buffer = new byte[1000]; while (entry != null) { name = entry.getName(); if (name.endsWith(".class")) { name = name.substring(0, name.length() - 6); name = name.replace('/', '.'); try { Class<?> cls = urlLoader.loadClass(name); if (IAlgorithm.class.isAssignableFrom(cls) && !cls.isInterface() && ((cls.getModifiers() & Modifier.ABSTRACT) == 0)) { dir.addAlgorithm(cls); model.putClass(cls.getName(), cls); } else if (ISerializable.class.isAssignableFrom(cls)) { model.putClass(cls.getName(), cls); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } else if (Constants.isAllowedImageType(name)) { int lastSep = name.lastIndexOf("/"); if (lastSep != -1) { String dirs = tmpdir + name.substring(0, lastSep); File d = new File(dirs); if (!d.exists()) d.mkdirs(); } String filename = tmpdir + name; File f = new File(filename); if (!f.exists()) { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); int read = -1; while ((read = jis.read(buffer)) != -1) { fos.write(buffer, 0, read); } fos.close(); } } entry = jis.getNextJarEntry(); } }
689
0
protected String md5sum(String toCompute) throws Exception { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toCompute.getBytes()); java.math.BigInteger hash = new java.math.BigInteger(1, md.digest()); return hash.toString(16); }
private static byte[] tryLoadFile(String path) throws IOException { InputStream in = new FileInputStream(path); ByteArrayOutputStream out = new ByteArrayOutputStream(); IOUtils.copy(in, out); in.close(); out.close(); return out.toByteArray(); }
690
0
public void testCodingFromFileSmaller() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); WritableByteChannel channel = newChannel(baos); HttpParams params = new BasicHttpParams(); SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(channel, outbuf, metrics, 16); File tmpFile = File.createTempFile("testFile", "txt"); FileOutputStream fout = new FileOutputStream(tmpFile); OutputStreamWriter wrtout = new OutputStreamWriter(fout); wrtout.write("stuff;"); wrtout.write("more stuff;"); wrtout.flush(); wrtout.close(); FileChannel fchannel = new FileInputStream(tmpFile).getChannel(); encoder.transfer(fchannel, 0, 20); String s = baos.toString("US-ASCII"); assertTrue(encoder.isCompleted()); assertEquals("stuff;more stuff", s); tmpFile.delete(); }
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(); }
691
1
public void convert(File src, File dest) throws IOException { InputStream in = new BufferedInputStream(new FileInputStream(src)); DcmParser p = pfact.newDcmParser(in); Dataset ds = fact.newDataset(); p.setDcmHandler(ds.getDcmHandler()); try { FileFormat format = p.detectFileFormat(); if (format != FileFormat.ACRNEMA_STREAM) { System.out.println("\n" + src + ": not an ACRNEMA stream!"); return; } p.parseDcmFile(format, Tags.PixelData); if (ds.contains(Tags.StudyInstanceUID) || ds.contains(Tags.SeriesInstanceUID) || ds.contains(Tags.SOPInstanceUID) || ds.contains(Tags.SOPClassUID)) { System.out.println("\n" + src + ": contains UIDs!" + " => probable already DICOM - do not convert"); return; } boolean hasPixelData = p.getReadTag() == Tags.PixelData; boolean inflate = hasPixelData && ds.getInt(Tags.BitsAllocated, 0) == 12; int pxlen = p.getReadLength(); if (hasPixelData) { if (inflate) { ds.putUS(Tags.BitsAllocated, 16); pxlen = pxlen * 4 / 3; } if (pxlen != (ds.getInt(Tags.BitsAllocated, 0) >>> 3) * ds.getInt(Tags.Rows, 0) * ds.getInt(Tags.Columns, 0) * ds.getInt(Tags.NumberOfFrames, 1) * ds.getInt(Tags.NumberOfSamples, 1)) { System.out.println("\n" + src + ": mismatch pixel data length!" + " => do not convert"); return; } } ds.putUI(Tags.StudyInstanceUID, uid(studyUID)); ds.putUI(Tags.SeriesInstanceUID, uid(seriesUID)); ds.putUI(Tags.SOPInstanceUID, uid(instUID)); ds.putUI(Tags.SOPClassUID, classUID); if (!ds.contains(Tags.NumberOfSamples)) { ds.putUS(Tags.NumberOfSamples, 1); } if (!ds.contains(Tags.PhotometricInterpretation)) { ds.putCS(Tags.PhotometricInterpretation, "MONOCHROME2"); } if (fmi) { ds.setFileMetaInfo(fact.newFileMetaInfo(ds, UIDs.ImplicitVRLittleEndian)); } OutputStream out = new BufferedOutputStream(new FileOutputStream(dest)); try { } finally { ds.writeFile(out, encodeParam()); if (hasPixelData) { if (!skipGroupLen) { out.write(PXDATA_GROUPLEN); int grlen = pxlen + 8; out.write((byte) grlen); out.write((byte) (grlen >> 8)); out.write((byte) (grlen >> 16)); out.write((byte) (grlen >> 24)); } out.write(PXDATA_TAG); out.write((byte) pxlen); out.write((byte) (pxlen >> 8)); out.write((byte) (pxlen >> 16)); out.write((byte) (pxlen >> 24)); } if (inflate) { int b2, b3; for (; pxlen > 0; pxlen -= 3) { out.write(in.read()); b2 = in.read(); b3 = in.read(); out.write(b2 & 0x0f); out.write(b2 >> 4 | ((b3 & 0x0f) << 4)); out.write(b3 >> 4); } } else { for (; pxlen > 0; --pxlen) { out.write(in.read()); } } out.close(); } System.out.print('.'); } finally { in.close(); } }
private static void main(String[] args) { try { File f = new File("test.txt"); if (f.exists()) { throw new IOException(f + " already exists. I don't want to overwrite it."); } StraightStreamReader in; char[] cbuf = new char[0x1000]; int read; int totRead; FileOutputStream out = new FileOutputStream(f); for (int i = 0x00; i < 0x100; i++) { out.write(i); } out.close(); in = new StraightStreamReader(new FileInputStream(f)); for (int i = 0x00; i < 0x100; i++) { read = in.read(); if (read != i) { System.err.println("Error: " + i + " read as " + read); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = in.read(cbuf); if (totRead != 0x100) { System.err.println("Simple buffered read did not read the full amount: 0x" + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 0x100 - totRead)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); in = new StraightStreamReader(new FileInputStream(f)); totRead = 0; while (totRead <= 0x100 && (read = in.read(cbuf, totRead + 0x123, 7)) > 0) { totRead += read; } if (totRead != 0x100) { System.err.println("Not enough read. Bytes read: " + Integer.toHexString(totRead)); } for (int i = 0x00; i < totRead; i++) { if (cbuf[i + 0x123] != i) { System.err.println("Error: 0x" + i + " read as 0x" + cbuf[i + 0x123]); } } in.close(); f.delete(); } catch (IOException x) { System.err.println(x.getMessage()); } }
692
0
private boolean hasPackageInfo(URL url) { if (url == null) return false; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = br.readLine()) != null) { if (line.startsWith("Specification-Title: ") || line.startsWith("Specification-Version: ") || line.startsWith("Specification-Vendor: ") || line.startsWith("Implementation-Title: ") || line.startsWith("Implementation-Version: ") || line.startsWith("Implementation-Vendor: ")) return true; } } catch (IOException ioe) { } finally { if (br != null) try { br.close(); } catch (IOException e) { } } return false; }
public static String readFromUrl(String url) { URL url_ = null; URLConnection uc = null; BufferedReader in = null; StringBuilder str = new StringBuilder(); try { url_ = new URL(url); uc = url_.openConnection(); in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) str.append(inputLine); in.close(); } catch (IOException e) { e.printStackTrace(); } return str.toString(); }
693
1
public static void main(String[] args) throws Exception { if (args.length != 2) { PrintUtil.prt("arguments: sourcefile, destfile"); System.exit(1); } FileChannel in = new FileInputStream(args[0]).getChannel(), out = new FileOutputStream(args[1]).getChannel(); in.transferTo(0, in.size(), out); }
public static void copyFile(File from, File to) throws Exception { if (!from.exists()) return; FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to); byte[] buffer = new byte[BUFFER_SIZE]; int bytes_read; while (true) { bytes_read = in.read(buffer); if (bytes_read == -1) break; out.write(buffer, 0, bytes_read); } out.flush(); out.close(); in.close(); }
694
0
private void backupOriginalFile(String myFile) { Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_S"); String datePortion = format.format(date); try { FileInputStream fis = new FileInputStream(myFile); FileOutputStream fos = new FileOutputStream(myFile + "-" + datePortion + "_UserID" + ".html"); FileChannel fcin = fis.getChannel(); FileChannel fcout = fos.getChannel(); fcin.transferTo(0, fcin.size(), fcout); fcin.close(); fcout.close(); fis.close(); fos.close(); System.out.println("**** Backup of file made."); } catch (Exception e) { System.out.println(e); } }
private String getData(String method, String arg) { try { URL url; String str; StringBuilder strBuilder; BufferedReader stream; url = new URL(API_BASE_URL + "/2.1/" + method + "/en/xml/" + API_KEY + "/" + URLEncoder.encode(arg, "UTF-8")); stream = new BufferedReader(new InputStreamReader(url.openStream())); strBuilder = new StringBuilder(); while ((str = stream.readLine()) != null) { strBuilder.append(str); } stream.close(); return strBuilder.toString(); } catch (MalformedURLException e) { return null; } catch (IOException e) { return null; } }
695
0
protected static boolean checkVersion(String address) { Scanner scanner = null; try { URL url = new URL(address); InputStream iS = url.openStream(); scanner = new Scanner(iS); if (scanner == null && DEBUG) System.out.println("SCANNER NULL"); String firstLine = scanner.nextLine(); double latestVersion = Double.valueOf(firstLine.trim()); double thisVersion = JCards.VERSION; if (thisVersion >= latestVersion) { JCards.latestVersion = true; } else { displaySimpleAlert(null, JCards.VERSION_PREFIX + latestVersion + " is available online!\n" + "Look under the file menu for a link to the download site."); } } catch (Exception e) { if (VERBOSE || DEBUG) { System.out.println("Can't decide latest version"); e.printStackTrace(); } return false; } return true; }
public static String submitURLRequest(String url) throws HttpException, IOException, URISyntaxException { HttpClient httpclient = new DefaultHttpClient(); InputStream stream = null; user_agents = new LinkedList<String>(); user_agents.add("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2"); String response_text = ""; URI uri = new URI(url); HttpGet post = new HttpGet(uri); int MAX = user_agents.size() - 1; int index = (int) Math.round(((double) Math.random() * (MAX))); String agent = user_agents.get(index); httpclient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, agent); httpclient.getParams().setParameter("User-Agent", agent); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.ACCEPT_NONE); HttpResponse response = httpclient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { stream = entity.getContent(); response_text = convertStreamToString(stream); } httpclient.getConnectionManager().shutdown(); if (stream != null) { stream.close(); } return response_text; }
696
1
public static String hexMD5(String value) { try { MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(value.getBytes("utf-8")); byte[] digest = messageDigest.digest(); return byteToHexString(digest); } catch (Exception ex) { throw new UnexpectedException(ex); } }
public String hash(String senha) { String result = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(senha.getBytes()); byte[] hashMd5 = md.digest(); for (int i = 0; i < hashMd5.length; i++) result += Integer.toHexString((((hashMd5[i] >> 4) & 0xf) << 4) | (hashMd5[i] & 0xf)); } catch (NoSuchAlgorithmException ex) { Logger.getInstancia().log(TipoLog.ERRO, ex); } return result; }
697
0
public void delete(DeleteInterceptorChain chain, DistinguishedName dn, LDAPConstraints constraints) throws LDAPException { Connection con = (Connection) chain.getRequest().get(JdbcInsert.MYVD_DB_CON + this.dbInsertName); if (con == null) { throw new LDAPException("Operations Error", LDAPException.OPERATIONS_ERROR, "No Database Connection"); } try { con.setAutoCommit(false); String uid = ((RDN) dn.getDN().getRDNs().get(0)).getValue(); PreparedStatement ps = con.prepareStatement(this.deleteSQL); ps.setString(1, uid); ps.executeUpdate(); con.commit(); } catch (SQLException e) { try { con.rollback(); } catch (SQLException e1) { throw new LDAPException("Could not delete entry or rollback transaction", LDAPException.OPERATIONS_ERROR, e.toString(), e); } throw new LDAPException("Could not delete entry", LDAPException.OPERATIONS_ERROR, e.toString(), e); } }
private void update() { if (VERSION.contains("dev")) return; System.out.println(updateURL_s); try { URL updateURL = new URL(updateURL_s); InputStream uis = updateURL.openStream(); InputStreamReader uisr = new InputStreamReader(uis); BufferedReader ubr = new BufferedReader(uisr); String header = ubr.readLine(); if (header.equals("GENREMANUPDATEPAGE")) { String cver = ubr.readLine(); String cdl = ubr.readLine(); if (!cver.equals(VERSION)) { System.out.println("Update available!"); int i = JOptionPane.showConfirmDialog(this, Language.get("UPDATE_AVAILABLE_MSG").replaceAll("%o", VERSION).replaceAll("%c", cver), Language.get("UPDATE_AVAILABLE_TITLE"), JOptionPane.YES_NO_OPTION); if (i == 0) { URL url = new URL(cdl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); if (connection.getResponseCode() / 100 != 2) { throw new Exception("Server error! Response code: " + connection.getResponseCode()); } int contentLength = connection.getContentLength(); if (contentLength < 1) { throw new Exception("Invalid content length!"); } int size = contentLength; File tempfile = File.createTempFile("genreman_update", ".zip"); tempfile.deleteOnExit(); RandomAccessFile file = new RandomAccessFile(tempfile, "rw"); InputStream stream = connection.getInputStream(); int downloaded = 0; ProgressWindow pwin = new ProgressWindow(this, "Downloading"); pwin.setVisible(true); pwin.setProgress(0); pwin.setText("Connecting..."); while (downloaded < size) { byte buffer[]; if (size - downloaded > 1024) { buffer = new byte[1024]; } else { buffer = new byte[size - downloaded]; } int read = stream.read(buffer); if (read == -1) break; file.write(buffer, 0, read); downloaded += read; pwin.setProgress(downloaded / size); } file.close(); System.out.println("Downloaded file to " + tempfile.getAbsolutePath()); pwin.setVisible(false); pwin.dispose(); pwin = null; ZipInputStream zin = new ZipInputStream(new FileInputStream(tempfile)); ZipEntry entry; while ((entry = zin.getNextEntry()) != null) { File outf = new File(entry.getName()); System.out.println(outf.getAbsoluteFile()); if (outf.exists()) outf.delete(); OutputStream out = new FileOutputStream(outf); byte[] buf = new byte[1024]; int len; while ((len = zin.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); } JOptionPane.showMessageDialog(this, Language.get("UPDATE_SUCCESS_MSG"), Language.get("UPDATE_SUCCESS_TITLE"), JOptionPane.INFORMATION_MESSAGE); setVisible(false); if (System.getProperty("os.name").indexOf("Windows") != -1) { Runtime.getRuntime().exec("iTunesGenreArtManager.exe"); } else { Runtime.getRuntime().exec("java -jar \"iTunes Genre Art Manager.app/Contents/Resources/Java/iTunes_Genre_Art_Manager.jar\""); } System.exit(0); } else { } } ubr.close(); uisr.close(); uis.close(); } else { while (ubr.ready()) { System.out.println(ubr.readLine()); } ubr.close(); uisr.close(); uis.close(); throw new Exception("Update page had invalid header: " + header); } } catch (Exception ex) { JOptionPane.showMessageDialog(this, Language.get("UPDATE_ERROR_MSG"), Language.get("UPDATE_ERROR_TITLE"), JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } }
698
0
public void createZip(File zipFileName, Vector<File> selected) { try { byte[] buffer = new byte[4096]; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFileName), 8096)); out.setLevel(Deflater.BEST_COMPRESSION); out.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < selected.size(); i++) { FileInputStream in = new FileInputStream(selected.get(i)); String file = selected.get(i).getPath(); if (file.indexOf("\\") != -1) file = file.substring(file.lastIndexOf(Options.fs) + 1, file.length()); ZipEntry ze = new ZipEntry(file); out.putNextEntry(ze); int len; while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len); out.closeEntry(); in.close(); selected.get(i).delete(); } out.close(); } catch (IllegalArgumentException iae) { iae.printStackTrace(); } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } }
public void populateDefaultIcons() { DomainNameTree defaultmap = this.getDefaultIconMap(); DomainNameTree newmap = new DomainNameTree(); File iconDir = new File(this.usrIconDir); if (!(iconDir.exists() && iconDir.isDirectory())) { int s = JOptionPane.showConfirmDialog(null, "Create icon directory " + this.usrIconDir + "?", "Icon directory does not exist!", JOptionPane.YES_NO_CANCEL_OPTION); if (s == JOptionPane.YES_OPTION) { iconDir.mkdir(); } else { return; } } Set domains = defaultmap.domainSet(); Iterator iter = domains.iterator(); while (iter.hasNext()) { String dname = (String) iter.next(); String fname = defaultmap.getImageFile(dname); if (fname != null) { System.out.println("Attempting to populate with:" + fname); if (!fname.equals("null")) { File file = new File(fname); String newname = this.usrIconDir.concat(File.separator).concat(file.getName()); File newfile = new File(newname); URL url = this.getClass().getResource(fname); if (url != null) { InputStream from = null; FileOutputStream to = null; try { byte[] buffer = new byte[4096]; from = url.openStream(); to = new FileOutputStream(newfile); int bytes_read = 0; while ((bytes_read = from.read(buffer)) != -1) { to.write(buffer, 0, bytes_read); } newmap.insert(new DomainNameNode(dname, newname)); } catch (Exception err) { throw new RuntimeException("Problem saving image to file.", err); } finally { if (from != null) { try { from.close(); } catch (IOException err) { throw new RuntimeException("Problem closing URL input stream."); } } if (to != null) { try { to.close(); } catch (IOException err) { throw new RuntimeException("Problem closing file output stream."); } } } } else { throw new RuntimeException("Trying to copy the default icon " + fname + " from " + this.getClass().getPackage() + " but it does not exist."); } } } } int s = JOptionPane.showConfirmDialog(null, "Save default mappings in " + this.usrConfigFile + "?", "Icon directory populated...", JOptionPane.YES_NO_CANCEL_OPTION); if (s == JOptionPane.YES_OPTION) { saveToRegistry(newmap); } }
699