label
int64
0
1
func1
stringlengths
173
53.1k
func2
stringlengths
173
53.1k
id
int64
0
901k
0
private File unzipArchive(File zipArchive, File outDir, String nameInZipArchive) throws IOException { File mainFile = null; ZipEntry entry = null; ZipInputStream zis = new ZipInputStream(new FileInputStream((zipArchive))); FileOutputStream fos = null; byte buffer[] = new byte[4096]; int bytesRead; while ((entry = zis.getNextEntry()) != null) { File outFile = new File(outDir, entry.getName()); if (entry.getName().equals(nameInZipArchive)) mainFile = outFile; fos = new FileOutputStream(outFile); while ((bytesRead = zis.read(buffer)) != -1) fos.write(buffer, 0, bytesRead); fos.close(); } zis.close(); return mainFile; }
private List<Intrebare> citesteIntrebari() throws IOException { ArrayList<Intrebare> intrebari = new ArrayList<Intrebare>(); try { URL url = new URL(getCodeBase(), "../intrebari.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader((url.openStream()))); String intrebare; while ((intrebare = reader.readLine()) != null) { Collection<String> raspunsuri = new ArrayList<String>(); Collection<String> predicate = new ArrayList<String>(); String raspuns = ""; while (!"".equals(raspuns = reader.readLine())) { raspunsuri.add(raspuns); predicate.add(reader.readLine()); } Intrebare i = new Intrebare(intrebare, raspunsuri.toArray(new String[raspunsuri.size()]), predicate.toArray(new String[predicate.size()])); intrebari.add(i); } } catch (ArgumentExcetpion e) { e.printStackTrace(); } return intrebari; }
100
0
void startzm() { URL myzzurl; InputStream myzstream; byte zmemimage[]; boolean joined; zmemimage = null; try { System.err.println(zcodefile); myzzurl = new URL(zcodefile); myzstream = myzzurl.openStream(); zmemimage = suckstream(myzstream); } catch (MalformedURLException booga) { try { myzstream = new FileInputStream(zcodefile); zmemimage = suckstream(myzstream); } catch (IOException booga2) { add("North", new Label("Malformed URL")); failed = true; } } catch (IOException booga) { add("North", new Label("I/O Error")); } if (zmemimage != null) { switch(zmemimage[0]) { case 3: zm = new ZMachine3(screen, status_line, zmemimage); break; case 5: remove(status_line); zm = new ZMachine5(screen, zmemimage); break; case 8: remove(status_line); zm = new ZMachine8(screen, zmemimage); break; default: add("North", new Label("Not a valid V3,V5, or V8 story file")); } if (zm != null) zm.start(); } joined = false; if (zmemimage != null) { while (!joined) { try { zm.join(); joined = true; } catch (InterruptedException booga) { } } } System.exit(0); }
public static ArrayList<String> remoteCall(Map<String, String> dataDict) { ArrayList<String> result = new ArrayList<String>(); String encodedData = ""; for (String key : dataDict.keySet()) { String encodedSegment = ""; String value = dataDict.get(key); if (value == null) continue; try { encodedSegment = key + "=" + URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (encodedData.length() > 0) { encodedData += "&"; } encodedData += encodedSegment; } try { URL url = new URL(baseURL + encodedData); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = reader.readLine()) != null) { result.add(line); System.out.println("GOT: " + line); } reader.close(); result.remove(0); if (result.size() != 0) { if (!result.get(result.size() - 1).equals("DONE")) { result.clear(); } else { result.remove(result.size() - 1); } } } catch (MalformedURLException e) { } catch (IOException e) { } return result; }
101
1
private static <OS extends OutputStream> OS getUnzipAndDecodeOutputStream(InputStream inputStream, final OS outputStream) { final PipedOutputStream pipedOutputStream = new PipedOutputStream(); final List<Throwable> ungzipThreadThrowableList = new LinkedList<Throwable>(); Writer decoderWriter = null; Thread ungzipThread = null; try { final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream); ungzipThread = new Thread(new Runnable() { public void run() { GZIPInputStream gzipInputStream = null; try { gzipInputStream = new GZIPInputStream(pipedInputStream); IOUtils.copy(gzipInputStream, outputStream); } catch (Throwable t) { ungzipThreadThrowableList.add(t); } finally { IOUtils.closeQuietly(gzipInputStream); IOUtils.closeQuietly(pipedInputStream); } } }); decoderWriter = Base64.newDecoder(pipedOutputStream); ungzipThread.start(); IOUtils.copy(inputStream, decoderWriter, DVK_MESSAGE_CHARSET); decoderWriter.flush(); pipedOutputStream.flush(); } catch (IOException e) { throw new RuntimeException("failed to unzip and decode input", e); } finally { IOUtils.closeQuietly(decoderWriter); IOUtils.closeQuietly(pipedOutputStream); if (ungzipThread != null) { try { ungzipThread.join(); } catch (InterruptedException ie) { throw new RuntimeException("thread interrupted while for ungzip thread to finish", ie); } } } if (!ungzipThreadThrowableList.isEmpty()) { throw new RuntimeException("ungzip failed", ungzipThreadThrowableList.get(0)); } return outputStream; }
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
102
0
public void bubbleSort(int[] arr) { boolean swapped = true; int j = 0; int tmp; while (swapped) { swapped = false; j++; for (int i = 0; i < arr.length - j; i++) { if (arr[i] > arr[i + 1]) { tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; swapped = true; } } } }
public int getHttpStatus(ProxyInfo proxyInfo, String sUrl, String cookie, String host) { HttpURLConnection connection = null; try { if (proxyInfo == null) { URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(); } else { InetSocketAddress addr = new InetSocketAddress(proxyInfo.getPxIp(), proxyInfo.getPxPort()); Proxy proxy = new Proxy(Proxy.Type.HTTP, addr); URL url = new URL(sUrl); connection = (HttpURLConnection) url.openConnection(proxy); } if (!isStringNull(host)) setHttpInfo(connection, cookie, host, ""); connection.setConnectTimeout(90 * 1000); connection.setReadTimeout(90 * 1000); connection.connect(); connection.getInputStream(); return connection.getResponseCode(); } catch (IOException e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } catch (Exception e) { log.info(proxyInfo + " getHTTPConent Error "); return 0; } }
103
0
private void createIDocPluginProject(IProgressMonitor monitor, String sourceFileName, String pluginName, String pluginNameJCo) throws CoreException, IOException { monitor.subTask(MessageFormat.format(Messages.ProjectGenerator_CreatePluginTaskDescription, pluginName)); final Map<String, byte[]> files = readArchiveFile(sourceFileName); monitor.worked(10); IProject project = workspaceRoot.getProject(pluginName); if (project.exists()) { project.delete(true, true, new SubProgressMonitor(monitor, 5)); } else { monitor.worked(5); } project.create(new SubProgressMonitor(monitor, 5)); project.open(new SubProgressMonitor(monitor, 5)); IProjectDescription description = project.getDescription(); description.setNatureIds(new String[] { JavaCore.NATURE_ID, PLUGIN_NATURE_ID }); project.setDescription(description, new SubProgressMonitor(monitor, 5)); IJavaProject javaProject = JavaCore.create(project); IFolder binDir = project.getFolder("bin"); IPath binPath = binDir.getFullPath(); javaProject.setOutputLocation(binPath, new SubProgressMonitor(monitor, 5)); project.getFile("sapidoc3.jar").create(new ByteArrayInputStream(files.get("sapidoc3.jar")), true, new SubProgressMonitor(monitor, 15)); IFolder metaInfFolder = project.getFolder("META-INF"); metaInfFolder.create(true, true, new SubProgressMonitor(monitor, 5)); StringBuilder manifest = new StringBuilder(); manifest.append("Manifest-Version: 1.0\n"); manifest.append("Bundle-ManifestVersion: 2\n"); manifest.append("Bundle-Name: SAP IDoc Library v3\n"); manifest.append(MessageFormat.format("Bundle-SymbolicName: {0}\n", pluginName)); manifest.append("Bundle-Version: 7.11.0\n"); manifest.append("Bundle-ClassPath: bin/,\n"); manifest.append(" sapidoc3.jar\n"); manifest.append("Bundle-Vendor: SAP AG, Walldorf (packaged using RCER)\n"); manifest.append("Bundle-RequiredExecutionEnvironment: J2SE-1.5\n"); manifest.append("Export-Package: com.sap.conn.idoc,\n"); manifest.append(" com.sap.conn.idoc.jco,\n"); manifest.append(" com.sap.conn.idoc.rt.cp,\n"); manifest.append(" com.sap.conn.idoc.rt.record,\n"); manifest.append(" com.sap.conn.idoc.rt.record.impl,\n"); manifest.append(" com.sap.conn.idoc.rt.trace,\n"); manifest.append(" com.sap.conn.idoc.rt.util,\n"); manifest.append(" com.sap.conn.idoc.rt.xml\n"); manifest.append("Bundle-ActivationPolicy: lazy\n"); manifest.append(MessageFormat.format("Require-Bundle: {0}\n", pluginNameJCo)); writeTextFile(monitor, manifest, metaInfFolder.getFile("MANIFEST.MF")); final IPath jcoPath = new Path(MessageFormat.format("/{0}/sapidoc3.jar", pluginName)); IClasspathEntry jcoEntry = JavaCore.newLibraryEntry(jcoPath, Path.EMPTY, Path.EMPTY, true); javaProject.setRawClasspath(new IClasspathEntry[] { jcoEntry }, new SubProgressMonitor(monitor, 5)); StringBuilder buildProperties = new StringBuilder(); buildProperties.append("bin.includes = META-INF/,\\\n"); buildProperties.append(" sapidoc3.jar,\\\n"); buildProperties.append(" .\n"); writeTextFile(monitor, buildProperties, project.getFile("build.properties")); exportableBundles.add(modelManager.findModel(project)); }
public String hash(String password) { MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { log.info("No sha-256 available"); try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.fatal("sha-1 is not available", e); throw new RuntimeException("Couldn't get a hash algorithm from Java"); } } try { digest.reset(); digest.update((salt + password).getBytes("UTF-8")); byte hash[] = digest.digest(); return new String(Base64.encodeBase64(hash, false)); } catch (Throwable t) { throw new RuntimeException("Couldn't hash password"); } }
104
0
public int create(BusinessObject o) throws DAOException { int insert = 0; int id = 0; Contact contact = (Contact) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("INSERT_CONTACT")); pst.setString(1, contact.getName()); pst.setString(2, contact.getFirstname()); pst.setString(3, contact.getPhone()); pst.setString(4, contact.getEmail()); if (contact.getAccount() == 0) { pst.setNull(5, java.sql.Types.INTEGER); } else { pst.setInt(5, contact.getAccount()); } insert = pst.executeUpdate(); if (insert <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (insert > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } Statement st = connection.createStatement(); ResultSet rs = st.executeQuery("select max(id) from contact"); rs.next(); id = rs.getInt(1); connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return id; }
public static double[][] getCurrency() throws IOException { URL url = new URL("http://hk.finance.yahoo.com/currency"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "big5")); double currency[][] = new double[11][11]; while (true) { String line = in.readLine(); String reg = "<td\\s((align=\"right\"\\sclass=\"yfnc_tabledata1\")" + "|(class=\"yfnc_tabledata1\"\\salign=\"right\"))>" + "([\\d|\\.]+)</td>"; Matcher m = Pattern.compile(reg).matcher(line); int i = 0, j = 0; boolean isfound = false; while (m.find()) { isfound = true; currency[i][j] = Double.parseDouble(m.group(4)); if (j == 10) { j = 0; i++; } else j++; } if (isfound) break; } return currency; }
105
0
protected IRunnableWithProgress getProjectCreationRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { int remainingWorkUnits = 10; monitor.beginTask("New Modulo Project Creation", remainingWorkUnits); IWorkspace ws = ResourcesPlugin.getWorkspace(); newProject = fMainPage.getProjectHandle(); IProjectDescription description = ws.newProjectDescription(newProject.getName()); String[] natures = { JavaCore.NATURE_ID, ModuloLauncherPlugin.NATURE_ID }; description.setNatureIds(natures); ICommand command = description.newCommand(); command.setBuilderName(JavaCore.BUILDER_ID); ICommand[] commands = { command }; description.setBuildSpec(commands); IJavaProject jproject = JavaCore.create(newProject); ModuloProject modProj = new ModuloProject(); modProj.setJavaProject(jproject); try { newProject.create(description, new SubProgressMonitor(monitor, 1)); newProject.open(new SubProgressMonitor(monitor, 1)); IFolder srcFolder = newProject.getFolder("src"); IFolder javaFolder = srcFolder.getFolder("java"); IFolder buildFolder = newProject.getFolder("build"); IFolder classesFolder = buildFolder.getFolder("classes"); modProj.createFolder(srcFolder); modProj.createFolder(javaFolder); modProj.createFolder(buildFolder); modProj.createFolder(classesFolder); IPath buildPath = newProject.getFolder("build/classes").getFullPath(); jproject.setOutputLocation(buildPath, new SubProgressMonitor(monitor, 1)); IClasspathEntry[] entries = new IClasspathEntry[] { JavaCore.newSourceEntry(newProject.getFolder("src/java").getFullPath()), JavaCore.newContainerEntry(new Path(JavaRuntime.JRE_CONTAINER)), JavaCore.newContainerEntry(new Path(ModuloClasspathContainer.CONTAINER_ID)) }; jproject.setRawClasspath(entries, new SubProgressMonitor(monitor, 1)); ModuleDefinition definition = new ModuleDefinition(); definition.setId(fModuloPage.getPackageName()); definition.setVersion(new VersionNumber(1, 0, 0)); definition.setMetaName(fModuloPage.getModuleName()); definition.setMetaDescription("The " + fModuloPage.getModuleName() + " Module."); definition.setModuleClassName(fModuloPage.getPackageName() + "." + fModuloPage.getModuleClassName()); if (fModuloPage.isConfigSelectioned()) definition.setConfigurationClassName(fModuloPage.getPackageName() + "." + fModuloPage.getConfigClassName()); if (fModuloPage.isStatSelectioned()) definition.setStatisticsClassName(fModuloPage.getPackageName() + "." + fModuloPage.getStatClassName()); modProj.setDefinition(definition); modProj.createPackage(); modProj.createModuleXML(); modProj.createMainClass(); if (fModuloPage.isConfigSelectioned()) modProj.createConfigClass(); if (fModuloPage.isStatSelectioned()) modProj.createStatClass(); modProj.createModuleProperties(); modProj.createMessagesProperties(); IFolder binFolder = newProject.getFolder("bin"); binFolder.delete(true, new SubProgressMonitor(monitor, 1)); } catch (CoreException e) { e.printStackTrace(); } finally { monitor.done(); } } }; }
@Override public void saveStructure(long userId, TreeStructureInfo info, List<TreeStructureNode> structure) throws DatabaseException { if (info == null) throw new NullPointerException("info"); if (structure == null) throw new NullPointerException("structure"); try { getConnection().setAutoCommit(false); } catch (SQLException e) { LOGGER.warn("Unable to set autocommit off", e); } PreparedStatement insertInfoSt = null, insSt = null; try { insertInfoSt = getConnection().prepareStatement(INSERT_INFO); insertInfoSt.setLong(1, userId); insertInfoSt.setString(2, info.getDescription() != null ? info.getDescription() : ""); insertInfoSt.setString(3, info.getBarcode()); insertInfoSt.setString(4, info.getName()); insertInfoSt.setString(5, info.getInputPath()); insertInfoSt.setString(6, info.getModel()); insertInfoSt.executeUpdate(); PreparedStatement seqSt = getConnection().prepareStatement(INFO_VALUE); ResultSet rs = seqSt.executeQuery(); int key = -1; while (rs.next()) { key = rs.getInt(1); } if (key == -1) { getConnection().rollback(); throw new DatabaseException("Unable to obtain new id from DB when executing query: " + insertInfoSt); } int total = 0; for (TreeStructureNode node : structure) { insSt = getConnection().prepareStatement(INSERT_NODE); insSt.setLong(1, key); insSt.setString(2, node.getPropId()); insSt.setString(3, node.getPropParent()); insSt.setString(4, node.getPropName()); insSt.setString(5, node.getPropPicture()); insSt.setString(6, node.getPropType()); insSt.setString(7, node.getPropTypeId()); insSt.setString(8, node.getPropPageType()); insSt.setString(9, node.getPropDateIssued()); insSt.setString(10, node.getPropAltoPath()); insSt.setString(11, node.getPropOcrPath()); insSt.setBoolean(12, node.getPropExist()); total += insSt.executeUpdate(); } if (total != structure.size()) { getConnection().rollback(); throw new DatabaseException("Unable to insert _ALL_ nodes: " + total + " nodes were inserted of " + structure.size()); } getConnection().commit(); } catch (SQLException e) { LOGGER.error("Queries: \"" + insertInfoSt + "\" and \"" + insSt + "\"", e); } finally { closeConnection(); } }
106
0
private InputStream connectURL(String aurl) throws IOException { InputStream in = null; int response = -1; URL url = new URL(aurl); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection."); HttpURLConnection httpConn = (HttpURLConnection) conn; response = getResponse(httpConn); if (response == HttpURLConnection.HTTP_OK) { in = httpConn.getInputStream(); } else throw new IOException("Response Code: " + response); return in; }
public String encrypt(String pwd) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); System.out.println("Error"); } try { md5.update(pwd.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); JOptionPane.showMessageDialog(null, "That is not a valid encrpytion type"); } byte raw[] = md5.digest(); String empty = ""; String hash = ""; for (byte b : raw) { String tmp = empty + Integer.toHexString(b & 0xff); if (tmp.length() == 1) { tmp = 0 + tmp; } hash += tmp; } return hash; }
107
1
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
public void backupXML() { try { TimeStamp timeStamp = new TimeStamp(); String fnameIn = this.fnameXML(); String pathBackup = this.pathXML + "\\Backup\\"; String fnameOut = fnameIn.substring(fnameIn.indexOf(this.fname), fnameIn.length()); fnameOut = fnameOut.substring(0, fnameOut.indexOf("xml")); fnameOut = pathBackup + fnameOut + timeStamp.now("yyyyMMdd-kkmmss") + ".xml"; System.out.println("fnameIn: " + fnameIn); System.out.println("fnameOut: " + fnameOut); FileChannel in = new FileInputStream(fnameIn).getChannel(); FileChannel out = new FileOutputStream(fnameOut).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { central.inform("ORM.backupXML: " + e.toString()); } }
108
0
public static void copyFile(File dst, File src, boolean append) throws FileNotFoundException, IOException { dst.createNewFile(); FileChannel in = new FileInputStream(src).getChannel(); FileChannel out = new FileOutputStream(dst).getChannel(); long startAt = 0; if (append) startAt = out.size(); in.transferTo(startAt, in.size(), out); out.close(); in.close(); }
public static String md5encrypt(String toEncrypt) { if (toEncrypt == null) { throw new IllegalArgumentException("null is not a valid password to encrypt"); } try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(toEncrypt.getBytes()); byte[] hash = md.digest(); return new String(dumpBytes(hash)); } catch (NoSuchAlgorithmException nsae) { return toEncrypt; } }
109
0
public void retrieveChallenge() throws MalformedURLException, IOException, FBConnectionException, FBErrorException { URL url = new URL(getHost() + getPath()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestProperty("X-FB-User", getUser()); conn.setRequestProperty("X-FB-Mode", "GetChallenge"); conn.connect(); Element fbresponse; try { fbresponse = readXML(conn); } catch (FBConnectionException fbce) { error = true; throw fbce; } catch (FBErrorException fbee) { error = true; throw fbee; } catch (Exception e) { error = true; FBConnectionException fbce = new FBConnectionException("XML parsing failed"); fbce.attachSubException(e); throw fbce; } NodeList nl = fbresponse.getElementsByTagName("GetChallengeResponse"); for (int i = 0; i < nl.getLength(); i++) { if (nl.item(i) instanceof Element && hasError((Element) nl.item(i))) { error = true; FBErrorException e = new FBErrorException(); e.setErrorCode(errorcode); e.setErrorText(errortext); throw e; } } NodeList challenge = fbresponse.getElementsByTagName("Challenge"); for (int i = 0; i < challenge.getLength(); i++) { NodeList children = challenge.item(i).getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j) instanceof Text) { challenges.offer(children.item(j).getNodeValue()); } } } }
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType(s_contentType); response.setHeader("Cache-control", "no-cache"); InputStream graphStream = getGraphStream(request); OutputStream out = getOutputStream(response); IOUtils.copy(graphStream, out); out.flush(); }
110
0
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
public void initGet() throws Exception { cl = new DefaultHttpClient(); GetAuthPromter hp = new GetAuthPromter(); cl.setCredentialsProvider(hp); get = new HttpGet(getURL()); get.setHeader("User-Agent", "test"); get.setHeader("Accept", "*/*"); get.setHeader("Range", "bytes=" + getPosition() + "-" + getRangeEnd()); HttpResponse resp = cl.execute(get); ent = resp.getEntity(); setInputStream(ent.getContent()); }
111
1
public String getHash(String str) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(str.getBytes()); byte[] toChapter1Digest = md.digest(); return Keystore.hexEncode(toChapter1Digest); } catch (Exception e) { logger.error("Error in creating DN hash: " + e.getMessage()); return null; } }
public static String encripta(String senha) throws GCIException { LOGGER.debug(INICIANDO_METODO + "encripta(String)"); try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(senha.getBytes()); BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(digest.digest()); } catch (NoSuchAlgorithmException e) { LOGGER.fatal(e.getMessage(), e); throw new GCIException(e); } finally { LOGGER.debug(FINALIZANDO_METODO + "encripta(String)"); } }
112
1
private void checkLogin(String email, String password) throws JspTagException { String cryptedPassword; try { MessageDigest crypt = MessageDigest.getInstance("MD5"); crypt.update(password.getBytes()); byte digest[] = crypt.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { hexString.append(hexDigit(digest[i])); } cryptedPassword = hexString.toString(); crypt.reset(); InitialContext context = new InitialContext(); java.lang.Object homeRef = context.lookup("java:comp/env/ejb/Value"); ValueHome valueHome = (ValueHome) PortableRemoteObject.narrow(homeRef, ValueHome.class); Value value = valueHome.findByPasswordCheck(email, cryptedPassword); pageContext.setAttribute("validLogin", new Boolean(true)); HttpSession session = pageContext.getSession(); session.setAttribute("jspShop.userID", value.getObjectID()); } catch (NoSuchAlgorithmException e) { System.err.println("jspShop: Could not get instance of MD5 algorithm. Please fix this!" + e.getMessage()); e.printStackTrace(); throw new JspTagException("Error crypting password!: " + e.getMessage()); } catch (ObjectNotFoundException e) { pageContext.setAttribute("validLogin", new Boolean(false)); } catch (NamingException e) { System.err.println("jspShop: Could not initialise context in LoginTag"); e.printStackTrace(); } catch (RemoteException e) { System.err.println("jspShop: Could not connect to container in LoginTag"); } catch (FinderException e) { System.err.println("jspShop: Error using finderQuery in LoginTag"); } }
@edu.umd.cs.findbugs.annotations.SuppressWarnings({ "DLS", "REC" }) public static String md5Encode(String val) { String output = null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(val.getBytes()); byte[] digest = md.digest(); output = base64Encode(digest); } catch (Exception e) { } return output; }
113
1
private String[] verifyConnection(Socket clientConnection) throws Exception { List<String> requestLines = new ArrayList<String>(); InputStream is = clientConnection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); StringTokenizer st = new StringTokenizer(in.readLine()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no method token in this connection"); } String method = st.nextToken(); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no URI token in this connection"); } String uri = decodePercent(st.nextToken()); if (!st.hasMoreTokens()) { throw new IllegalArgumentException("There's no version token in this connection"); } String version = st.nextToken(); Properties parms = new Properties(); int qmi = uri.indexOf('?'); if (qmi >= 0) { decodeParms(uri.substring(qmi + 1), parms); uri = decodePercent(uri.substring(0, qmi)); } String params = ""; if (parms.size() > 0) { params = "?"; for (Object key : parms.keySet()) { params = params + key + "=" + parms.getProperty(((String) key)) + "&"; } params = params.substring(0, params.length() - 1).replace(" ", "%20"); } logger.debug("HTTP Request: " + method + " " + uri + params + " " + version); requestLines.add(method + " " + uri + params + " " + version); Properties headerVars = new Properties(); String line; String currentBoundary = null; Stack<String> boundaryStack = new Stack<String>(); boolean readingBoundary = false; String additionalData = ""; while (in.ready() && (line = in.readLine()) != null) { if (line.equals("") && (headerVars.get("Content-Type") == null || headerVars.get("Content-Length") == null)) { break; } logger.debug("HTTP Request Header: " + line); if (line.contains(": ")) { String vals[] = line.split(": "); headerVars.put(vals[0].trim(), vals[1].trim()); } if (!readingBoundary && line.contains(": ")) { if (line.contains("boundary=")) { currentBoundary = line.split("boundary=")[1].trim(); boundaryStack.push("--" + currentBoundary); } continue; } else if (line.equals("") && boundaryStack.isEmpty()) { int val = Integer.parseInt((String) headerVars.get("Content-Length")); if (headerVars.getProperty("Content-Type").contains("x-www-form-urlencoded")) { char buf[] = new char[val]; int read = in.read(buf); line = String.valueOf(buf, 0, read); additionalData = line; logger.debug("HTTP Request Header Form Parameters: " + line); } } else if (line.equals(boundaryStack.peek()) && !readingBoundary) { readingBoundary = true; } else if (line.equals(boundaryStack.peek()) && readingBoundary) { readingBoundary = false; } else if (line.contains(": ") && readingBoundary) { if (method.equalsIgnoreCase("PUT")) { if (line.contains("form-data; ")) { String formValues = line.split("form-data; ")[1]; for (String varValue : formValues.replace("\"", "").split("; ")) { String[] vV = varValue.split("="); vV[0] = decodePercent(vV[0]); vV[1] = decodePercent(vV[1]); headerVars.put(vV[0], vV[1]); } } } } else if (line.contains("") && readingBoundary && !boundaryStack.isEmpty() && headerVars.get("filename") != null) { int length = Integer.parseInt(headerVars.getProperty("Content-Length")); if (headerVars.getProperty("Content-Transfer-Encoding").contains("binary")) { File uploadFilePath = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory")); if (!uploadFilePath.exists()) { logger.error("Temporaty dir does not exist: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.isDirectory()) { logger.error("Temporary dir is not a directory: " + uploadFilePath.getCanonicalPath()); } if (!uploadFilePath.canWrite()) { logger.error("VOctopus Webserver doesn't have permissions to write on temporary dir: " + uploadFilePath.getCanonicalPath()); } FileOutputStream out = null; try { String putUploadPath = uploadFilePath.getAbsolutePath() + "/" + headerVars.getProperty("filename"); out = new FileOutputStream(putUploadPath); OutputStream outf = new BufferedOutputStream(out); int c; while (in.ready() && (c = in.read()) != -1 && length-- > 0) { outf.write(c); } } finally { if (out != null) { out.close(); } } File copied = new File(VOctopusConfigurationManager.getInstance().getDocumentRootPath() + uri + headerVars.get("filename")); File tempFile = new File(VOctopusConfigurationManager.WebServerProperties.HTTPD_CONF.getPropertyValue("TempDirectory") + "/" + headerVars.get("filename")); FileChannel ic = new FileInputStream(tempFile.getAbsolutePath()).getChannel(); FileChannel oc = new FileOutputStream(copied.getAbsolutePath()).getChannel(); ic.transferTo(0, ic.size(), oc); ic.close(); oc.close(); } } } for (Object var : headerVars.keySet()) { requestLines.add(var + ": " + headerVars.get(var)); } if (!additionalData.equals("")) { requestLines.add("ADDITIONAL" + additionalData); } return requestLines.toArray(new String[requestLines.size()]); }
private static void convertToOnline(final String filePath, final DocuBean docuBean) throws Exception { File source = new File(filePath + File.separator + docuBean.getFileName()); File dir = new File(filePath + File.separator + docuBean.getId()); if (!dir.exists()) { dir.mkdir(); } File in = source; boolean isSpace = false; if (source.getName().indexOf(" ") != -1) { in = new File(StringUtils.replace(source.getName(), " ", "")); try { IOUtils.copyFile(source, in); } catch (IOException e) { e.printStackTrace(); } isSpace = true; } File finalPdf = null; try { String outPath = dir.getAbsolutePath(); final File pdf = DocViewerConverter.toPDF(in, outPath); convertToSwf(pdf, outPath, docuBean); finalPdf = new File(outPath + File.separator + FileUtils.getFilePrefix(StringUtils.replace(source.getName(), " ", "")) + "_decrypted.pdf"); if (!finalPdf.exists()) { finalPdf = pdf; } pdfByFirstPageToJpeg(finalPdf, outPath, docuBean); if (docuBean.getSuccess() == 2 && dir.listFiles().length < 2) { docuBean.setSuccess(3); } } catch (Exception e) { throw e; } finally { if (isSpace) { IOUtils.delete(in); } } }
114
1
public String getData() throws ValueFormatException, RepositoryException, IOException { InputStream is = getStream(); StringWriter sw = new StringWriter(); IOUtils.copy(is, sw, "UTF-8"); IOUtils.closeQuietly(is); return sw.toString(); }
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); } }
115
0
public static String makeMD5(String pin) { try { MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); digest.update(pin.getBytes()); byte[] hash = digest.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { hexString.append(Integer.toHexString(0xFF & hash[i])); } return hexString.toString(); } catch (Exception e) { return null; } }
public int delete(BusinessObject o) throws DAOException { int delete = 0; Contact contact = (Contact) o; try { PreparedStatement pst = connection.prepareStatement(XMLGetQuery.getQuery("DELETE_CONTACT")); pst.setInt(1, contact.getId()); delete = pst.executeUpdate(); if (delete <= 0) { connection.rollback(); throw new DAOException("Number of rows <= 0"); } else if (delete > 1) { connection.rollback(); throw new DAOException("Number of rows > 1"); } connection.commit(); } catch (SQLException e) { Log.write(e.getMessage()); throw new DAOException("A SQLException has occured"); } catch (NullPointerException npe) { Log.write(npe.getMessage()); throw new DAOException("Connection null"); } return delete; }
116
1
public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); writer = new PdfCopy(document, out); writer.setPdfVersion(PdfWriter.VERSION_1_3); writer.setFullCompression(); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STRENGTH128BITS, password, null, securityType); } final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } else if (base_url != null) { document.addTitle(base_url); } final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } else { document.addCreator(IHtmlToPdfTransformer.VERSION); } final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.addProducer(sproducer); } else { document.addProducer(IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer); } document.open(); } PdfImportedPage page; for (int j = 0; j < n; ) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } } document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext(); ) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i).replaceAll("<pagecount>", "" + n); final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } else { reader = new PdfReader(tmp2.getAbsolutePath()); } final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STRENGTH128BITS, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } if (reason != null) { sap.setReason(reason); } if (location != null) { sap.setLocation(location); } stp.close(); oldOut.flush(); } } catch (final Exception e) { throw new CConvertException("ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } finally { try { tmp.delete(); } catch (final Exception ignore) { } try { tmp2.delete(); } catch (final Exception ignore) { } } }
private void loadMap() { final String wordList = "vietwordlist.txt"; try { File dataFile = new File(supportDir, wordList); if (!dataFile.exists()) { final ReadableByteChannel input = Channels.newChannel(ClassLoader.getSystemResourceAsStream("dict/" + dataFile.getName())); final FileChannel output = new FileOutputStream(dataFile).getChannel(); output.transferFrom(input, 0, 1000000L); input.close(); output.close(); } long fileLastModified = dataFile.lastModified(); if (map == null) { map = new HashMap<String, String>(); } else { if (fileLastModified <= mapLastModified) { return; } map.clear(); } mapLastModified = fileLastModified; BufferedReader bs = new BufferedReader(new InputStreamReader(new FileInputStream(dataFile), "UTF-8")); String accented; while ((accented = bs.readLine()) != null) { String plain = VietUtilities.stripDiacritics(accented); map.put(plain.toLowerCase(), accented); } bs.close(); } catch (IOException e) { map = null; e.printStackTrace(); JOptionPane.showMessageDialog(this, myResources.getString("Cannot_find_\"") + wordList + myResources.getString("\"_in\n") + supportDir.toString(), VietPad.APP_NAME, JOptionPane.ERROR_MESSAGE); } }
117
0
public InlineImageChunk(URL url) { super(); this.url = url; try { URLConnection urlConn = url.openConnection(); urlConn.setReadTimeout(15000); ImageInputStream iis = ImageIO.createImageInputStream(urlConn.getInputStream()); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (readers.hasNext()) { ImageReader reader = readers.next(); reader.setInput(iis, true); this.width = reader.getWidth(0); this.ascent = reader.getHeight(0); this.descent = 0; reader.dispose(); } else System.err.println("cannot read width and height of image " + url + " - no suitable reader!"); } catch (Exception exc) { System.err.println("cannot read width and height of image " + url + " due to exception:"); System.err.println(exc); exc.printStackTrace(System.err); } }
private void readFromObjectInput(String filename) { try { URL url = new URL(getCodeBase(), filename); InputStream stream = url.openStream(); ObjectInput input = new ObjectInputStream(stream); fDrawing.release(); fDrawing = (Drawing) input.readObject(); view().setDrawing(fDrawing); } catch (IOException e) { initDrawing(); showStatus("Error: " + e); } catch (ClassNotFoundException e) { initDrawing(); showStatus("Class not found: " + e); } }
118
0
public String digestResponse() { String digest = null; if (null == nonce) return null; try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(username.getBytes()); md.update(":".getBytes()); md.update(realm.getBytes()); md.update(":".getBytes()); md.update(password.getBytes()); byte[] d = md.digest(); if (null != algorithm && -1 != (algorithm.toLowerCase()).indexOf("md5-sess")) { md = MessageDigest.getInstance("MD5"); md.update(d); md.update(":".getBytes()); md.update(nonce.getBytes()); md.update(":".getBytes()); md.update(cnonce.getBytes()); d = md.digest(); } byte[] a1 = bytesToHex(d); md = MessageDigest.getInstance("MD5"); md.update(method.getBytes()); md.update(":".getBytes()); md.update(uri.getBytes()); d = md.digest(); byte[] a2 = bytesToHex(d); md = MessageDigest.getInstance("MD5"); md.update(a1); md.update(":".getBytes()); md.update(nonce.getBytes()); md.update(":".getBytes()); if (null != qop) { md.update(nonceCount.getBytes()); md.update(":".getBytes()); md.update(cnonce.getBytes()); md.update(":".getBytes()); md.update(qop.getBytes()); md.update(":".getBytes()); } md.update(a2); d = md.digest(); byte[] r = bytesToHex(d); digest = new String(r); } catch (Exception e) { e.printStackTrace(); } return digest; }
public static void concatenateToDestFile(File sourceFile, File destFile) throws IOException { if (!destFile.exists()) { if (!destFile.createNewFile()) { throw new IllegalArgumentException("Could not create destination file:" + destFile.getName()); } } BufferedOutputStream bufferedOutputStream = null; BufferedInputStream bufferedInputStream = null; byte[] buffer = new byte[1024]; try { bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFile, true)); bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFile)); while (true) { int readByte = bufferedInputStream.read(buffer, 0, buffer.length); if (readByte == -1) { break; } bufferedOutputStream.write(buffer, 0, readByte); } } finally { if (bufferedOutputStream != null) { bufferedOutputStream.close(); } if (bufferedInputStream != null) { bufferedInputStream.close(); } } }
119
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!"); }
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!"); }
120
1
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
public boolean copier(String source, String nomFichierSource, java.io.File destination) { boolean resultat = false; OutputStream tmpOut; try { tmpOut = new BufferedOutputStream(new FileOutputStream(nomFichierSource + "001.tmp")); InputStream is = getClass().getResourceAsStream(source + nomFichierSource); int i; while ((i = is.read()) != -1) tmpOut.write(i); tmpOut.close(); is.close(); } catch (IOException ex) { ex.printStackTrace(); } FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(new File(nomFichierSource + "001.tmp")).getChannel(); out = new FileOutputStream(destination).getChannel(); in.transferTo(0, in.size(), out); resultat = true; } catch (java.io.FileNotFoundException f) { } catch (java.io.IOException e) { } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } new File(nomFichierSource + "001.tmp").delete(); return (resultat); }
121
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); }
@Override public void connect() throws IOException { URL url = getLocator().getURL(); if (url.getProtocol().equals("file")) { final String newUrlStr = URLUtils.createAbsoluteFileUrl(url.toExternalForm()); if (newUrlStr != null) { if (!newUrlStr.toString().equals(url.toExternalForm())) { logger.warning("Changing file URL to absolute for URL.openConnection, from " + url.toExternalForm() + " to " + newUrlStr); url = new URL(newUrlStr); } } } conn = url.openConnection(); if (!url.getProtocol().equals("ftp") && conn.getURL().getProtocol().equals("ftp")) { logger.warning("URL.openConnection() morphed " + url + " to " + conn.getURL()); throw new IOException("URL.openConnection() returned an FTP connection for a non-ftp url: " + url); } if (conn instanceof HttpURLConnection) { final HttpURLConnection huc = (HttpURLConnection) conn; huc.connect(); final int code = huc.getResponseCode(); if (!(code >= 200 && code < 300)) { huc.disconnect(); throw new IOException("HTTP response code: " + code); } logger.finer("URL: " + url); logger.finer("Response code: " + code); logger.finer("Full content type: " + conn.getContentType()); boolean contentTypeSet = false; if (stripTrailer(conn.getContentType()).equals("text/plain")) { final String ext = PathUtils.extractExtension(url.getPath()); if (ext != null) { final String result = MimeManager.getMimeType(ext); if (result != null) { contentTypeStr = ContentDescriptor.mimeTypeToPackageName(result); contentTypeSet = true; logger.fine("Received content type " + conn.getContentType() + "; overriding based on extension, to: " + result); } } } if (!contentTypeSet) contentTypeStr = ContentDescriptor.mimeTypeToPackageName(stripTrailer(conn.getContentType())); } else { conn.connect(); contentTypeStr = ContentDescriptor.mimeTypeToPackageName(conn.getContentType()); } contentType = new ContentDescriptor(contentTypeStr); sources = new URLSourceStream[1]; sources[0] = new URLSourceStream(); connected = true; }
122
1
public static void main(String[] args) throws IOException { String uri = "hdfs://localhost:8020/user/leeing/maxtemp/sample.txt"; Configuration conf = new Configuration(); FileSystem fs = FileSystem.get(URI.create(uri), conf); InputStream in = null; try { in = fs.open(new Path(uri)); IOUtils.copyBytes(in, System.out, 8192, false); } finally { IOUtils.closeStream(in); } }
public boolean backupLastAuditSchema(File lastAuditSchema) { boolean isBkupFileOK = false; String writeTimestamp = DateFormatUtils.format(new java.util.Date(), configFile.getTimestampPattern()); File target = new File(configFile.getAuditSchemaFileDir() + File.separator + configFile.getAuditSchemaFileName() + ".bkup_" + writeTimestamp); FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(lastAuditSchema).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size()); } catch (IOException e) { logger.log(Level.SEVERE, "IO exception occurred while copying file", e); } finally { if ((target != null) && (target.exists()) && (target.length() > 0)) { isBkupFileOK = true; } try { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } catch (IOException e) { logger.info("closing channels failed"); } } return isBkupFileOK; }
123
0
private static List<CountryEntry> retrieveCountries() throws IOException { URL url = new URL("http://" + ISO_3166_HOST + ISO_3166_TXT_FILE_PATH); BufferedReader input = new BufferedReader(new InputStreamReader(url.openStream())); List<CountryEntry> countries = new LinkedList<CountryEntry>(); boolean parsing = false; int trCount = 0; int tdCount = 0; CountryEntry current = new CountryEntry(); String nextLine = input.readLine(); while (nextLine != null) { if (nextLine.startsWith("<table")) { parsing = true; } if (nextLine.startsWith("</table>")) { break; } if (parsing) { if (nextLine.startsWith("<tr")) { trCount++; } else { if ((trCount > 1 && nextLine.startsWith("<td"))) { tdCount++; String data = pullData(nextLine); switch(tdCount) { case 1: current.setName(getCountryName(data)); break; case 2: current.setNumber(data); break; case 3: current.setAlpha3(data); break; case 4: current.setAlpha2(data); break; case 5: countries.add(current); current = new CountryEntry(); tdCount = 0; break; default: String msg = "Parsing error. Unexpected column: [" + data + "]"; throw new IllegalStateException(msg); } } } } nextLine = input.readLine(); } input.close(); return countries; }
public void runTask(HashMap pjobParms) throws Exception { FTPClient lftpClient = null; FileInputStream lfisSourceFile = null; JBJFPluginDefinition lpluginCipher = null; IJBJFPluginCipher theCipher = null; try { JBJFFTPDefinition lxmlFTP = null; if (getFTPDefinition() != null) { lxmlFTP = getFTPDefinition(); this.mstrSourceDirectory = lxmlFTP.getSourceDirectory(); this.mstrTargetDirectory = lxmlFTP.getTargetDirectory(); this.mstrFilename = lxmlFTP.getFilename(); this.mstrRemoteServer = lxmlFTP.getServer(); if (getResources().containsKey("plugin-cipher")) { lpluginCipher = (JBJFPluginDefinition) getResources().get("plugin-cipher"); } if (lpluginCipher != null) { theCipher = getTaskPlugins().getCipherPlugin(lpluginCipher.getPluginId()); } if (theCipher != null) { this.mstrServerUsr = theCipher.decryptString(lxmlFTP.getUser()); this.mstrServerPwd = theCipher.decryptString(lxmlFTP.getPass()); } else { this.mstrServerUsr = lxmlFTP.getUser(); this.mstrServerPwd = lxmlFTP.getPass(); } } else { throw new Exception("Work unit [ " + SHORT_NAME + " ] is missing an FTP Definition. Please check" + " your JBJF Batch Definition file an make sure" + " this work unit has a <resource> element added" + " within the <task> element."); } lfisSourceFile = new FileInputStream(mstrSourceDirectory + File.separator + mstrFilename); lftpClient = new FTPClient(); lftpClient.connect(mstrRemoteServer); lftpClient.setFileType(lxmlFTP.getFileTransferType()); if (!FTPReply.isPositiveCompletion(lftpClient.getReplyCode())) { throw new Exception("FTP server [ " + mstrRemoteServer + " ] refused connection."); } if (!lftpClient.login(mstrServerUsr, mstrServerPwd)) { throw new Exception("Unable to login to server [ " + mstrTargetDirectory + " ]."); } if (!lftpClient.changeWorkingDirectory(mstrTargetDirectory)) { throw new Exception("Unable to change to remote directory [ " + mstrTargetDirectory + "]"); } lftpClient.enterLocalPassiveMode(); if (!lftpClient.storeFile(mstrFilename, lfisSourceFile)) { throw new Exception("Unable to upload [ " + mstrSourceDirectory + "/" + mstrFilename + " ]" + " to " + mstrTargetDirectory + File.separator + mstrFilename + " to " + mstrRemoteServer); } lfisSourceFile.close(); lftpClient.logout(); } catch (Exception e) { throw e; } finally { if (lftpClient != null && lftpClient.isConnected()) { try { lftpClient.disconnect(); } catch (IOException ioe) { } } if (lfisSourceFile != null) { try { lfisSourceFile.close(); } catch (Exception e) { } } } }
124
0
public synchronized void download(URL url, File file) throws IOException { reset(); MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } InputStream in = url.openConnection(proxy).getInputStream(); byte[] buffer = new byte[2048]; BufferedOutputStream bos = file == null ? null : new BufferedOutputStream(new FileOutputStream(file), buffer.length); try { int size; while ((size = in.read(buffer, 0, buffer.length)) != -1) { if (this.isCancelled()) break; if (bos != null) bos.write(buffer, 0, size); if (size > 0) { digest.update(buffer, 0, size); this.length += size; progress(); } } } finally { if (bos != null) { bos.flush(); bos.close(); } } if (!cancelled) this.checkSum = CheckSum.toString(digest.digest()); }
public static String getWikiPage(String city) throws MalformedURLException, IOException, ParserConfigurationException, SAXException { String url = "http://api.geonames.org/wikipediaSearch?q=" + city + "&maxRows=1&lang=it&username=lorenzo.abram"; URLConnection conn = new URL(url).openConnection(); InputStream response = conn.getInputStream(); GeonamesHandler handler = new GeonamesHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); parser.parse(response, handler); return handler.getUrl(); }
125
0
@Override public String fetchURL(String urlString) throws ServiceException { try { URL url = new URL(urlString); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String content = ""; String line; while ((line = reader.readLine()) != null) { content += line + "\n"; } reader.close(); return content; } catch (MalformedURLException e) { throw new ServiceException(e.getMessage()); } catch (IOException e) { throw new ServiceException(e.getMessage()); } }
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(); } }
126
0
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 String getRandomGUID(final boolean secure) { MessageDigest md5 = null; final StringBuffer sbValueBeforeMD5 = new StringBuffer(); try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } try { final long time = System.currentTimeMillis(); final long rand; if (secure) { rand = mySecureRand.nextLong(); } else { rand = myRand.nextLong(); } sbValueBeforeMD5.append(id); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(time)); sbValueBeforeMD5.append(SEMI_COLON); sbValueBeforeMD5.append(Long.toString(rand)); valueBeforeMD5 = sbValueBeforeMD5.toString(); md5.update(valueBeforeMD5.getBytes()); final byte[] array = md5.digest(); final StringBuffer sb = new StringBuffer(); for (int j = 0; j < array.length; ++j) { final int bufferIndex = array[j] & SHIFT_SPACE; if (ZERO_TEST > bufferIndex) sb.append(CHAR_ZERO); sb.append(Integer.toHexString(bufferIndex)); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
127
0
public void loadFromFile() { if (filename == null) return; try { BufferedReader reader; try { File file = new File(filename); if (!file.exists()) return; reader = new BufferedReader(new FileReader(file)); } catch (java.security.AccessControlException e) { URL url = new URL(filename); reader = new BufferedReader(new InputStreamReader(url.openStream())); } String line; while (true) { line = reader.readLine(); if (line == null) break; String name = line.substring(0, line.indexOf("\t")); String rest1 = line.substring(line.indexOf("\t") + 1); String guiname = rest1.substring(0, rest1.indexOf("\t")); String rest2 = rest1.substring(rest1.indexOf("\t") + 1); String type = rest2.substring(0, rest2.indexOf("\t")); String value = rest2.substring(rest2.indexOf("\t") + 1); defineField(name, guiname, type); setField(name, value, true); } reader.close(); } catch (IOException e) { throw new JGameError("Error reading file '" + filename + "'.", false); } }
private static MyCookieData parseCookie(Cookie cookie) throws CookieException { String value = cookie.getValue(); System.out.println("original cookie: " + value); value = value.replace("%3A", ":"); value = value.replace("%40", "@"); System.out.println("cookie after replacement: " + value); String[] parts = value.split(":"); if (parts.length < 4) throw new CookieException("only " + parts.length + " parts in the cookie! " + value); String email = parts[0]; String nickname = parts[1]; boolean admin = Boolean.getBoolean(parts[2].toLowerCase()); String hsh = parts[3]; boolean valid_cookie = true; String cookie_secret = System.getProperty("COOKIE_SECRET"); if (cookie_secret == "") throw new CookieException("cookie secret is not set"); if (email.equals("")) { System.out.println("email is empty!"); nickname = ""; admin = false; } else { try { MessageDigest sha = MessageDigest.getInstance("SHA"); sha.update((email + nickname + admin + cookie_secret).getBytes()); StringBuilder builder = new StringBuilder(); for (byte b : sha.digest()) { byte tmphigh = (byte) (b >> 4); tmphigh = (byte) (tmphigh & 0xf); builder.append(hextab.charAt(tmphigh)); byte tmplow = (byte) (b & 0xf); builder.append(hextab.charAt(tmplow)); } System.out.println(); String vhsh = builder.toString(); if (!vhsh.equals(hsh)) { System.out.println("hash not same!"); System.out.println("hash passed in: " + hsh); System.out.println("hash generated: " + vhsh); valid_cookie = false; } else System.out.println("cookie match!"); } catch (NoSuchAlgorithmException ex) { } } return new MyCookieData(email, admin, nickname, valid_cookie); }
128
0
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { jButton1.setEnabled(false); for (int i = 0; i < max; i++) { Card crd = WLP.getSelectedCard(WLP.jTable1.getSelectedRows()[i]); String s, s2; s = ""; s2 = ""; try { URL url = new URL("http://www.m-w.com/dictionary/" + crd.getWord()); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { s = s + str; } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern = Pattern.compile("popWin\\('/cgi-bin/(.+?)'", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(s); if (matcher.find()) { String newurl = "http://m-w.com/cgi-bin/" + matcher.group(1); try { URL url2 = new URL(newurl); BufferedReader in2 = new BufferedReader(new InputStreamReader(url2.openStream())); String str; while ((str = in2.readLine()) != null) { s2 = s2 + str; } in2.close(); } catch (MalformedURLException e) { } catch (IOException e) { } Pattern pattern2 = Pattern.compile("<A HREF=\"http://(.+?)\">Click here to listen with your default audio player", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher2 = pattern2.matcher(s2); if (matcher2.find()) { getWave("http://" + matcher2.group(1), crd.getWord()); } int val = jProgressBar1.getValue(); val++; jProgressBar1.setValue(val); this.paintAll(this.getGraphics()); } } jButton1.setEnabled(true); }
public static List<ServerInfo> getStartedServers() { List<ServerInfo> infos = new ArrayList<ServerInfo>(); try { StringBuilder request = new StringBuilder(); request.append(url).append("/").append(displayServlet); request.append("?ingame=1"); URL objUrl = new URL(request.toString()); URLConnection urlConnect = objUrl.openConnection(); InputStream in = urlConnect.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); while (reader.ready()) { String name = reader.readLine(); String ip = reader.readLine(); int port = Integer.valueOf(reader.readLine()); ServerInfo server = new ServerInfo(name, ip, port); server.nbPlayers = Integer.valueOf(reader.readLine()); infos.add(server); } in.close(); return infos; } catch (Exception e) { return infos; } }
129
1
public static String getBiopaxId(Reaction reaction) { String id = null; if (reaction.getId() > Reaction.NO_ID_ASSIGNED) { id = reaction.getId().toString(); } else { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(reaction.getTextualRepresentation().getBytes()); byte[] digestBytes = md.digest(); StringBuilder digesterSb = new StringBuilder(32); for (int i = 0; i < digestBytes.length; i++) { int intValue = digestBytes[i] & 0xFF; if (intValue < 0x10) digesterSb.append('0'); digesterSb.append(Integer.toHexString(intValue)); } id = digesterSb.toString(); } catch (NoSuchAlgorithmException e) { } } return id; }
public String md5(String password) { MessageDigest m = null; try { m = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { } m.update(password.getBytes(), 0, password.length()); return new BigInteger(1, m.digest()).toString(16); }
130
1
protected static final void copyFile(String from, String to) throws SeleniumException { try { java.io.File fileFrom = new File(from); java.io.File fileTo = new File(to); FileReader in = new FileReader(fileFrom); FileWriter out = new FileWriter(fileTo); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); } catch (Exception e) { throw new SeleniumException("Failed to copy new file : " + from + " to : " + to, e); } }
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(); } }
131
0
static byte[] genDigest(String pad, byte[] passwd) throws NoSuchAlgorithmException { MessageDigest digest = MessageDigest.getInstance(DIGEST_ALGORITHM); digest.update(pad.getBytes()); digest.update(passwd); return digest.digest(); }
public static String readRss(String feed, int num) { InputStream stream = null; try { feed = appendParam(feed, "num", "" + num); System.out.println("feed=" + feed); URL url = new URL(feed); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", RSS_USER_AGENT); stream = connection.getInputStream(); return CFileHelper.readInputStream(stream); } catch (Exception e) { throw new CException(e); } finally { CFileHelper.closeStream(stream); } }
132
0
public void initFromXml(final String xmlFileName) throws java.net.MalformedURLException, ConfigurationException, IOException { if (xmlInitialized) { return; } templates = null; MergeTemplateWriter.setTokenList(getTokenProvider().getKnownTokens()); java.net.URL url = new FileFinder().getUrl(getTokenProvider().getClass(), xmlFileName); InputStreamReader xmlFileReader = new InputStreamReader(url.openStream()); KnownTemplates temps = MergeTemplateWriter.importFromXML(xmlFileReader); xmlFileReader.close(); KnownTemplates.setDefaultInstance(temps); setTemplates(temps); setInitialized(true); }
public static String calculatesMD5(String plainText) throws NoSuchAlgorithmException { MessageDigest mdAlgorithm = MessageDigest.getInstance("MD5"); mdAlgorithm.update(plainText.getBytes()); byte[] digest = mdAlgorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < digest.length; i++) { plainText = Integer.toHexString(0xFF & digest[i]); if (plainText.length() < 2) { plainText = "0" + plainText; } hexString.append(plainText); } return hexString.toString(); }
133
1
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } catch (IOException e) { throw e; } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
private void createWikiPages(WikiContext context) throws PluginException { OntologyWikiPageName owpn = new OntologyWikiPageName(omemo.getFormDataAlias().toUpperCase(), omemo.getFormDataVersionDate()); String wikiPageFullFileName = WikiPageName2FullFileName(context, owpn.toString()); String rdfFileNameWithPath = getWorkDir(context) + File.separator + owpn.toFileName(); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(wikiPageFullFileName); fis = new FileInputStream(rdfFileNameWithPath); InfoExtractor infoe = new InfoExtractor(fis, omemo.getFormDataNS(), omemo.getFormDataOntLang()); infoe.writePage(getWorkDir(context), owpn, Omemo.checksWikiPageName); fis.close(); fos.close(); } catch (Exception e) { log.error("Can not read local rdf file or can not write wiki page"); throw new PluginException("Error creating wiki pages. See logs"); } }
134
0
public void deploy(final File extension) { log.info("Deploying new extension from {}", extension.getPath()); RequestContextHolder.setRequestContext(new RequestContext(SZoneConfig.getDefaultZoneName(), SZoneConfig.getAdminUserName(SZoneConfig.getDefaultZoneName()), new BaseSessionContext())); RequestContextHolder.getRequestContext().resolve(); JarInputStream warIn; try { warIn = new JarInputStream(new FileInputStream(extension), true); } catch (IOException e) { log.warn("Unable to open extension WAR at " + extension.getPath(), e); return; } SAXReader reader = new SAXReader(false); reader.setIncludeExternalDTDDeclarations(false); String extensionPrefix = extension.getName().substring(0, extension.getName().lastIndexOf(".")); File extensionDir = new File(extensionBaseDir, extensionPrefix); extensionDir.mkdirs(); File extensionWebDir = new File(this.extensionWebDir, extensionPrefix); extensionWebDir.mkdirs(); try { for (JarEntry entry = warIn.getNextJarEntry(); entry != null; entry = warIn.getNextJarEntry()) { File inflated = new File(entry.getName().startsWith(infPrefix) ? extensionDir : extensionWebDir, entry.getName()); if (entry.isDirectory()) { log.debug("Creating directory at {}", inflated.getPath()); inflated.mkdirs(); continue; } inflated.getParentFile().mkdirs(); FileOutputStream entryOut = new FileOutputStream(inflated); if (!entry.getName().endsWith(configurationFileExtension)) { log.debug("Inflating file resource to {}", inflated.getPath()); IOUtils.copy(warIn, entryOut); entryOut.close(); continue; } try { final Document document = reader.read(new TeeInputStream(new CloseShieldInputStream(warIn), entryOut, true)); Attribute schema = document.getRootElement().attribute(schemaAttribute); if (schema == null || StringUtils.isBlank(schema.getText())) { log.debug("Inflating XML with unrecognized schema to {}", inflated.getPath()); continue; } if (schema.getText().contains(definitionsSchemaNamespace)) { log.debug("Inflating and registering definition from {}", inflated.getPath()); document.getRootElement().add(new AbstractAttribute() { private static final long serialVersionUID = -7880537136055718310L; public QName getQName() { return new QName(extensionAttr, document.getRootElement().getNamespace()); } public String getValue() { return extension.getName().substring(0, extension.getName().lastIndexOf(".")); } }); definitionModule.addDefinition(document, true); continue; } if (schema.getText().contains(templateSchemaNamespace)) { log.debug("Inflating and registering template from {}", inflated.getPath()); templateService.addTemplate(document, true, zoneModule.getDefaultZone()); continue; } } catch (DocumentException e) { log.warn("Malformed XML file in extension war at " + extension.getPath(), e); return; } } } catch (IOException e) { log.warn("Malformed extension war at " + extension.getPath(), e); return; } finally { try { warIn.close(); } catch (IOException e) { log.warn("Unable to close extension war at " + extension.getPath(), e); return; } RequestContextHolder.clear(); } log.info("Extension deployed successfully from {}", extension.getPath()); }
protected String getManualDownloadURL() { if (_newestVersionString.indexOf("weekly") > 0) { return "http://www.cs.rice.edu/~javaplt/drjavarice/weekly/"; } final String DRJAVA_FILES_PAGE = "http://sourceforge.net/project/showfiles.php?group_id=44253"; final String LINK_PREFIX = "<a href=\"/project/showfiles.php?group_id=44253"; final String LINK_SUFFIX = "\">"; BufferedReader br = null; try { URL url = new URL(DRJAVA_FILES_PAGE); InputStream urls = url.openStream(); InputStreamReader is = new InputStreamReader(urls); br = new BufferedReader(is); String line; int pos; while ((line = br.readLine()) != null) { if ((pos = line.indexOf(_newestVersionString)) >= 0) { int prePos = line.indexOf(LINK_PREFIX); if ((prePos >= 0) && (prePos < pos)) { int suffixPos = line.indexOf(LINK_SUFFIX, prePos); if ((suffixPos >= 0) && (suffixPos + LINK_SUFFIX.length() == pos)) { String versionLink = edu.rice.cs.plt.text.TextUtil.xmlUnescape(line.substring(prePos + LINK_PREFIX.length(), suffixPos)); return DRJAVA_FILES_PAGE + versionLink; } } } } ; } catch (IOException e) { return DRJAVA_FILES_PAGE; } finally { try { if (br != null) br.close(); } catch (IOException e) { } } return DRJAVA_FILES_PAGE; }
135
1
public static String digestString(String data, String algorithm) { String result = null; if (data != null) { try { MessageDigest _md = MessageDigest.getInstance(algorithm); _md.update(data.getBytes()); byte[] _digest = _md.digest(); String _ds; _ds = toHexString(_digest, 0, _digest.length); result = _ds; } catch (NoSuchAlgorithmException e) { result = null; } } return result; }
public static String encrypt(String text) throws NoSuchAlgorithmException { MessageDigest md; md = MessageDigest.getInstance("MD5"); byte[] md5hash = new byte[32]; try { md.update(text.getBytes("iso-8859-1"), 0, text.length()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } md5hash = md.digest(); return convertToHex(md5hash); }
136
1
private void writeToFile(Body b, File mime4jFile) throws FileNotFoundException, IOException { if (b instanceof TextBody) { String charset = CharsetUtil.toJavaCharset(b.getParent().getCharset()); if (charset == null) { charset = "ISO8859-1"; } OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((TextBody) b).getReader(), out, charset); } else { OutputStream out = new FileOutputStream(mime4jFile); IOUtils.copy(((BinaryBody) b).getInputStream(), out); } }
private void output(HttpServletResponse resp, InputStream is, long length, String fileName) throws Exception { resp.reset(); String mimeType = "image/jpeg"; resp.setContentType(mimeType); resp.setContentLength((int) length); resp.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\""); resp.setHeader("Cache-Control", "must-revalidate"); ServletOutputStream sout = resp.getOutputStream(); IOUtils.copy(is, sout); sout.flush(); resp.flushBuffer(); }
137
0
public static void putWithUserSettings(String from, String to, String renameTo, boolean binary, IProgressMonitor monitor) { if (monitor != null && monitor.isCanceled()) { return; } FTPHolder ftpHolder = new FTPHolder(from, to, renameTo, binary); synchedSet.add(ftpHolder); int ftpqueuesize = PrefPageOne.getIntValue(CONSTANTS.PREF_FTPQUEUE); if (synchedSet.size() >= ftpqueuesize) { JobHandler.aquireFTPLock(); try { ftpClient = new FTPClient(); ftpClient.setRemoteAddr(InetAddress.getByName(PrefPageOne.getValue(CONSTANTS.PREF_HOST))); ftpClient.setControlPort(PrefPageOne.getIntValue(CONSTANTS.PREF_FTPPORT)); ftpClient.connect(); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } ftpClient.login((PrefPageOne.getValue(CONSTANTS.PREF_USERNAME)), FTPUtils.decrypt(PrefPageOne.getValue(CONSTANTS.PREF_PASSWORD))); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (monitor != null && monitor.isCanceled()) { JobHandler.releaseFTPLock(); ftpClient.quit(); return; } synchronized (synchedSet) { for (Iterator iter = synchedSet.iterator(); iter.hasNext(); ) { if (monitor != null && monitor.isCanceled()) { JobHandler.releaseFTPLock(); ftpClient.quit(); return; } Thread.yield(); FTPHolder element = (FTPHolder) iter.next(); if (element.binary) { ftpClient.setType(FTPTransferType.BINARY); } else { ftpClient.setType(FTPTransferType.ASCII); } ftpClient.put(element.from, element.to); if (element.renameTo != null) { try { ftpClient.delete(element.renameTo); } catch (Exception e) { } ftpClient.rename(element.to, element.renameTo); log.info("RENAME: " + element.to + "To: " + element.renameTo); } } synchedSet.clear(); } JobHandler.releaseFTPLock(); ftpClient.quit(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (FTPException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
public static Image load(final InputStream input, String format, Point dimension) throws CoreException { MultiStatus status = new MultiStatus(GraphVizActivator.ID, 0, "Errors occurred while running Graphviz", null); File dotInput = null, dotOutput = null; ByteArrayOutputStream dotContents = new ByteArrayOutputStream(); try { dotInput = File.createTempFile(TMP_FILE_PREFIX, DOT_EXTENSION); dotOutput = File.createTempFile(TMP_FILE_PREFIX, "." + format); dotOutput.delete(); FileOutputStream tmpDotOutputStream = null; try { IOUtils.copy(input, dotContents); tmpDotOutputStream = new FileOutputStream(dotInput); IOUtils.copy(new ByteArrayInputStream(dotContents.toByteArray()), tmpDotOutputStream); } finally { IOUtils.closeQuietly(tmpDotOutputStream); } IStatus result = runDot(format, dimension, dotInput, dotOutput); status.add(result); status.add(logInput(dotContents)); if (dotOutput.isFile()) { if (!result.isOK() && Platform.inDebugMode()) LogUtils.log(status); ImageLoader loader = new ImageLoader(); ImageData[] imageData = loader.load(dotOutput.getAbsolutePath()); return new Image(Display.getDefault(), imageData[0]); } } catch (SWTException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } catch (IOException e) { status.add(new Status(IStatus.ERROR, GraphVizActivator.ID, "", e)); } finally { dotInput.delete(); dotOutput.delete(); IOUtils.closeQuietly(input); } throw new CoreException(status); }
138
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); }
public static void copyFile(File src, File dest) throws IOException { FileInputStream fIn; FileOutputStream fOut; FileChannel fIChan, fOChan; long fSize; MappedByteBuffer mBuf; fIn = new FileInputStream(src); fOut = new FileOutputStream(dest); fIChan = fIn.getChannel(); fOChan = fOut.getChannel(); fSize = fIChan.size(); mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize); fOChan.write(mBuf); fIChan.close(); fIn.close(); fOChan.close(); fOut.close(); }
139
0
protected InputStream makeRequestAndGetJSONData(String url) throws URISyntaxException, ClientProtocolException, IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); URI uri; InputStream data = null; uri = new URI(url); HttpGet method = new HttpGet(uri); HttpResponse response = httpClient.execute(method); data = response.getEntity().getContent(); return data; }
public static String getMd5Hash(String text) { StringBuffer result = new StringBuffer(32); try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(text.getBytes()); Formatter f = new Formatter(result); byte[] digest = md5.digest(); for (int i = 0; i < digest.length; i++) { f.format("%02x", new Object[] { new Byte(digest[i]) }); } } catch (NoSuchAlgorithmException ex) { ex.printStackTrace(); } return result.toString(); }
140
1
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("image/png"); OutputStream outStream; outStream = resp.getOutputStream(); InputStream is; String name = req.getParameter("name"); if (name == null) { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } else { ImageRecord imageRecord = imageBean.getFile(name); if (imageRecord != null) { is = new BufferedInputStream(new FileInputStream(imageRecord.getThumbnailFile())); } else { is = ImageServlet.class.getResourceAsStream("/com/actionbazaar/blank.png"); } } IOUtils.copy(is, outStream); outStream.close(); outStream.flush(); }
private void copy(File inputFile, File outputFile) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8")); while (reader.ready()) { writer.write(reader.readLine()); writer.write(System.getProperty("line.separator")); } } catch (IOException e) { } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); } catch (IOException e1) { } } }
141
1
public static String encryptPassword(String originalPassword) { if (!StringUtils.hasText(originalPassword)) { originalPassword = randomPassword(); } try { MessageDigest md5 = MessageDigest.getInstance(PASSWORD_ENCRYPTION_TYPE); md5.update(originalPassword.getBytes()); byte[] bytes = md5.digest(); int value; StringBuilder buf = new StringBuilder(); for (byte aByte : bytes) { value = aByte; if (value < 0) { value += 256; } if (value < 16) { buf.append("0"); } buf.append(Integer.toHexString(value)); } return buf.toString(); } catch (NoSuchAlgorithmException e) { log.debug("Do not encrypt password,use original password", e); return originalPassword; } }
private String getBytes(String in) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(in.getBytes()); byte[] passWordBytes = md5.digest(); String s = "["; for (int i = 0; i < passWordBytes.length; i++) s += passWordBytes[i] + ", "; s = s.substring(0, s.length() - 2); s += "]"; return s; }
142
0
public void testSetRequestProperty() throws Exception { MockHTTPServer httpServer = new MockHTTPServer("HTTP Server for User-Specified Request Property", 2); httpServer.start(); synchronized (bound) { if (!httpServer.started) { bound.wait(5000); } } HttpURLConnection urlConnection = (HttpURLConnection) new URL("http://localhost:" + httpServer.port()).openConnection(); assertEquals(0, urlConnection.getRequestProperties().size()); final String PROPERTY1 = "Accept"; final String PROPERTY2 = "Connection"; urlConnection.setRequestProperty(PROPERTY1, null); urlConnection.setRequestProperty(PROPERTY1, null); urlConnection.setRequestProperty(PROPERTY2, "keep-alive"); assertEquals(2, urlConnection.getRequestProperties().size()); assertNull(urlConnection.getRequestProperty(PROPERTY1)); assertEquals("keep-alive", urlConnection.getRequestProperty(PROPERTY2)); urlConnection.setRequestProperty(PROPERTY1, "/"); urlConnection.setRequestProperty(PROPERTY2, null); assertEquals("/", urlConnection.getRequestProperty(PROPERTY1)); assertNull(urlConnection.getRequestProperty(PROPERTY2)); }
public String generateKey(String className, String methodName, String text, String meaning) { if (text == null) { return null; } MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Error initializing MD5", e); } try { md5.update(text.getBytes("UTF-8")); if (meaning != null) { md5.update(meaning.getBytes("UTF-8")); } } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 unsupported", e); } return StringUtils.toHexString(md5.digest()); }
143
0
public static void executa(String arquivo, String filial, String ip) { String drive = arquivo.substring(0, 2); if (drive.indexOf(":") == -1) drive = ""; Properties p = Util.lerPropriedades(arquivo); String servidor = p.getProperty("servidor"); String impressora = p.getProperty("fila"); String arqRel = new String(drive + p.getProperty("arquivo")); String copias = p.getProperty("copias"); if (filial.equalsIgnoreCase(servidor)) { Socket s = null; int tentativas = 0; boolean conectado = false; while (!conectado) { try { tentativas++; System.out.println("Tentando conectar " + ip + " (" + tentativas + ")"); s = new Socket(ip, 7000); conectado = s.isConnected(); } catch (ConnectException ce) { System.err.println(ce.getMessage()); System.err.println(ce.getCause()); } catch (UnknownHostException uhe) { System.err.println(uhe.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } } FileInputStream in = null; BufferedOutputStream out = null; try { in = new FileInputStream(new File(arqRel)); out = new BufferedOutputStream(new GZIPOutputStream(s.getOutputStream())); } catch (FileNotFoundException e3) { e3.printStackTrace(); } catch (IOException e3) { e3.printStackTrace(); } String arqtr = arqRel.substring(2); System.out.println("Proximo arquivo: " + arqRel + " ->" + arqtr); while (arqtr.length() < 30) arqtr += " "; while (impressora.length() < 30) impressora += " "; byte aux[] = new byte[30]; byte cop[] = new byte[2]; try { aux = arqtr.getBytes("UTF8"); out.write(aux); aux = impressora.getBytes("UTF8"); out.write(aux); cop = copias.getBytes("UTF8"); out.write(cop); out.flush(); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } byte b[] = new byte[1024]; int nBytes; try { while ((nBytes = in.read(b)) != -1) out.write(b, 0, nBytes); out.flush(); out.close(); in.close(); s.close(); } catch (IOException e1) { e1.printStackTrace(); } System.out.println("Arquivo " + arqRel + " foi transmitido. \n\n"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } SimpleDateFormat dfArq = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat dfLog = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String arqLog = "log" + filial + dfArq.format(new Date()) + ".txt"; PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(arqLog, true)); } catch (IOException e) { e.printStackTrace(); } pw.println("Arquivo: " + arquivo + " " + dfLog.format(new Date())); pw.flush(); pw.close(); File f = new File(arquivo); while (!f.delete()) { System.out.println("Erro apagando " + arquivo); } } }
public void testDigest() { try { String myinfo = "我的测试信息"; MessageDigest alga = MessageDigest.getInstance("SHA-1"); alga.update(myinfo.getBytes()); byte[] digesta = alga.digest(); System.out.println("本信息摘要是:" + byte2hex(digesta)); MessageDigest algb = MessageDigest.getInstance("SHA-1"); algb.update(myinfo.getBytes()); if (MessageDigest.isEqual(digesta, algb.digest())) { System.out.println("信息检查正常"); } else { System.out.println("摘要不相同"); } } catch (NoSuchAlgorithmException ex) { System.out.println("非法摘要算法"); } }
144
1
public static void copyFile(File in, File out) throws IOException { try { FileReader inf = new FileReader(in); OutputStreamWriter outf = new OutputStreamWriter(new FileOutputStream(out), "UTF-8"); int c; while ((c = inf.read()) != -1) outf.write(c); inf.close(); outf.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public static void copy(File source, File dest) throws java.io.IOException { FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } finally { if (in != null) in.close(); if (out != null) out.close(); } }
145
1
public static Document convertHtmlToXml(final InputStream htmlInputStream, final String classpathXsltResource, final String encoding) { Parser p = new Parser(); javax.xml.parsers.DocumentBuilder db; try { db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("", e); throw new RuntimeException(); } Document document = db.newDocument(); InputStream is = htmlInputStream; if (log.isDebugEnabled()) { ByteArrayOutputStream baos; baos = new ByteArrayOutputStream(); try { IOUtils.copy(is, baos); } catch (IOException e) { log.error("Fail to make input stream copy.", e); } IOUtils.closeQuietly(is); ByteArrayInputStream byteArrayInputStream; byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray()); try { IOUtils.toString(new ByteArrayInputStream(baos.toByteArray()), "UTF-8"); } catch (IOException e) { log.error("", e); } IOUtils.closeQuietly(byteArrayInputStream); is = new ByteArrayInputStream(baos.toByteArray()); } try { InputSource iSource = new InputSource(is); iSource.setEncoding(encoding); Source transformerSource = new SAXSource(p, iSource); Result result = new DOMResult(document); Transformer xslTransformer = getTransformerByName(classpathXsltResource, false); try { xslTransformer.transform(transformerSource, result); } catch (TransformerException e) { throw new RuntimeException(e); } } finally { try { is.close(); } catch (Exception e) { log.warn("", e); } } return document; }
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
146
0
public static synchronized String encrypt(String plaintext) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = null; md = MessageDigest.getInstance("SHA"); md.update(plaintext.getBytes("UTF-8")); byte raw[] = md.digest(); String hash = (new BASE64Encoder()).encode(raw); return hash; }
@Override public synchronized void deletePersistenceEntityStatistics(Integer elementId, String contextName, String project, String name, Date dateFrom, Date dateTo) throws DatabaseException { final Connection connection = this.getConnection(); try { connection.setAutoCommit(false); String queryString = "DELETE " + this.getPersistenceEntityStatisticsSchemaAndTableName() + " FROM " + this.getPersistenceEntityStatisticsSchemaAndTableName() + " INNER JOIN " + this.getPersistenceEntityElementsSchemaAndTableName() + " ON " + this.getPersistenceEntityElementsSchemaAndTableName() + ".element_id = " + this.getPersistenceEntityStatisticsSchemaAndTableName() + ".element_id WHERE "; if (elementId != null) { queryString = queryString + " elementId = ? AND "; } if (contextName != null) { queryString = queryString + " context_name LIKE ? AND "; } if ((project != null)) { queryString = queryString + " project LIKE ? AND "; } if ((name != null)) { queryString = queryString + " name LIKE ? AND "; } if (dateFrom != null) { queryString = queryString + " start_timestamp >= ? AND "; } if (dateTo != null) { queryString = queryString + " start_timestamp <= ? AND "; } queryString = DefaultDatabaseHandler.removeOrphanWhereAndAndFromSelect(queryString); final PreparedStatement preparedStatement = DebugPreparedStatement.prepareStatement(connection, queryString); int indexCounter = 1; if (elementId != null) { preparedStatement.setLong(indexCounter, elementId.longValue()); indexCounter = indexCounter + 1; } if (contextName != null) { preparedStatement.setString(indexCounter, contextName); indexCounter = indexCounter + 1; } if ((project != null)) { preparedStatement.setString(indexCounter, project); indexCounter = indexCounter + 1; } if ((name != null)) { preparedStatement.setString(indexCounter, name); indexCounter = indexCounter + 1; } if (dateFrom != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateFrom.getTime())); indexCounter = indexCounter + 1; } if (dateTo != null) { preparedStatement.setTimestamp(indexCounter, new Timestamp(dateTo.getTime())); indexCounter = indexCounter + 1; } preparedStatement.executeUpdate(); preparedStatement.close(); connection.commit(); } catch (final SQLException e) { try { connection.rollback(); } catch (final SQLException ex) { JeeObserverServerContext.logger.log(Level.SEVERE, "Transaction rollback error.", ex); } JeeObserverServerContext.logger.log(Level.SEVERE, e.getMessage()); throw new DatabaseException("Error deleting persistence entity statistics.", e); } finally { this.releaseConnection(connection); } }
147
1
public static String getKeyWithRightLength(final String key, int keyLength) { if (keyLength > 0) { if (key.length() == keyLength) { return key; } else { MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { return ""; } md.update(key.getBytes()); byte[] hash = md.digest(); if (keyLength > 20) { byte nhash[] = new byte[keyLength]; for (int i = 0; i < keyLength; i++) { nhash[i] = hash[i % 20]; } hash = nhash; } return new String(hash).substring(0, keyLength); } } else { return key; } }
public static String digest(String password) { try { byte[] digest; synchronized (__md5Lock) { if (__md == null) { try { __md = MessageDigest.getInstance("MD5"); } catch (Exception e) { Log.warn(e); return null; } } __md.reset(); __md.update(password.getBytes(StringUtil.__ISO_8859_1)); digest = __md.digest(); } return __TYPE + TypeUtil.toString(digest, 16); } catch (Exception e) { Log.warn(e); return null; } }
148
1
private static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); File to_file = new File(to_name); if (!from_file.exists()) abort("�������� ���� �� ���������" + from_file); if (!from_file.isFile()) abort("���������� ����������� ��������" + from_file); if (!from_file.canRead()) abort("�������� ���� ���������� ��� ������" + from_file); if (from_file.isDirectory()) to_file = new File(to_file, from_file.getName()); if (to_file.exists()) { if (!to_file.canWrite()) abort("�������� ���� ���������� ��� ������" + to_file); System.out.println("������������ ������� ����?" + to_file.getName() + "?(Y/N):"); System.out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String response = in.readLine(); if (!response.equals("Y") && !response.equals("y")) abort("������������ ���� �� ��� �����������"); } else { String parent = to_file.getParent(); if (parent == null) parent = System.getProperty("user.dir"); File dir = new File(parent); if (!dir.exists()) abort("������� ���������� �� ���������" + parent); if (!dir.isFile()) abort("�� �������� ���������" + parent); if (!dir.canWrite()) abort("������ �� ������" + parent); } FileInputStream from = null; FileOutputStream to = null; try { from = new FileInputStream(from_file); to = new FileOutputStream(to_file); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = from.read(buffer)) != -1) to.write(buffer, 0, bytes_read); } finally { if (from != null) try { from.close(); } catch (IOException e) { ; } if (to != null) try { to.close(); } catch (IOException e) { ; } } }
JcrFile createBody(Part part) throws IOException, MessagingException { JcrFile body = new JcrFile(); body.setName("part"); ByteArrayOutputStream pout = new ByteArrayOutputStream(); IOUtils.copy(part.getInputStream(), pout); body.setDataProvider(new JcrDataProviderImpl(TYPE.BYTES, pout.toByteArray())); body.setMimeType(part.getContentType()); body.setLastModified(java.util.Calendar.getInstance()); return body; }
149
1
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); } }
private static void copyFile(File srcFile, File destFile, long chunkSize) throws IOException { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(srcFile); FileChannel iChannel = is.getChannel(); os = new FileOutputStream(destFile, false); FileChannel oChannel = os.getChannel(); long doneBytes = 0L; long todoBytes = srcFile.length(); while (todoBytes != 0L) { long iterationBytes = Math.min(todoBytes, chunkSize); long transferredLength = oChannel.transferFrom(iChannel, doneBytes, iterationBytes); if (iterationBytes != transferredLength) { throw new IOException("Error during file transfer: expected " + iterationBytes + " bytes, only " + transferredLength + " bytes copied."); } doneBytes += transferredLength; todoBytes -= transferredLength; } } finally { if (is != null) { is.close(); } if (os != null) { os.close(); } } boolean successTimestampOp = destFile.setLastModified(srcFile.lastModified()); if (!successTimestampOp) { log.warn("Could not change timestamp for {}. Index synchronization may be slow.", destFile); } }
150
0
public void saveProjectFile(File aFile) { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss"); File destDir = new File(theProjectsDirectory, sdf.format(Calendar.getInstance().getTime())); if (destDir.mkdirs()) { File outFile = new File(destDir, "project.xml"); try { FileChannel sourceChannel = new FileInputStream(aFile).getChannel(); FileChannel destinationChannel = new FileOutputStream(outFile).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); } catch (IOException e) { e.printStackTrace(); } finally { aFile.delete(); } } }
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) { } } } }
151
1
public void removeExifTag(File jpegImageFile, File dst) throws IOException, ImageReadException, ImageWriteException { OutputStream os = null; try { TiffOutputSet outputSet = null; IImageMetadata metadata = Sanselan.getMetadata(jpegImageFile); JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata; if (null != jpegMetadata) { TiffImageMetadata exif = jpegMetadata.getExif(); if (null != exif) { outputSet = exif.getOutputSet(); } } if (null == outputSet) { IOUtils.copyFileNio(jpegImageFile, dst); return; } { outputSet.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); TiffOutputDirectory exifDirectory = outputSet.getExifDirectory(); if (null != exifDirectory) exifDirectory.removeField(TiffConstants.EXIF_TAG_APERTURE_VALUE); } os = new FileOutputStream(dst); os = new BufferedOutputStream(os); new ExifRewriter().updateExifMetadataLossless(jpegImageFile, os, outputSet); os.close(); os = null; } finally { if (os != null) try { os.close(); } catch (IOException e) { } } }
public void copyFile(File s, File t) { try { FileChannel in = (new FileInputStream(s)).getChannel(); FileChannel out = (new FileOutputStream(t)).getChannel(); in.transferTo(0, s.length(), out); in.close(); out.close(); } catch (Exception e) { System.out.println(e); } }
152
0
public static final void copyFile(File argSource, File argDestination) throws IOException { FileChannel srcChannel = new FileInputStream(argSource).getChannel(); FileChannel dstChannel = new FileOutputStream(argDestination).getChannel(); try { dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); } finally { srcChannel.close(); dstChannel.close(); } }
void setURLString(String path, boolean forceLoad) { if (path != null) { if (this.url != null || inputStream != null) throw new IllegalArgumentException(Ding3dI18N.getString("MediaContainer5")); try { URL url = new URL(path); InputStream stream; stream = url.openStream(); stream.close(); } catch (Exception e) { throw new SoundException(javax.media.ding3d.Ding3dI18N.getString("MediaContainer0")); } } this.urlString = path; if (forceLoad) dispatchMessage(); }
153
1
public ODFSignatureService(TimeStampServiceValidator timeStampServiceValidator, RevocationDataService revocationDataService, SignatureFacet signatureFacet, InputStream documentInputStream, OutputStream documentOutputStream, TimeStampService timeStampService, String role, IdentityDTO identity, byte[] photo, DigestAlgo digestAlgo) throws Exception { super(digestAlgo); this.temporaryDataStorage = new HttpSessionTemporaryDataStorage(); this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".odf"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(signatureFacet); XAdESSignatureFacet xadesSignatureFacet = super.getXAdESSignatureFacet(); xadesSignatureFacet.setRole(role); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
@NotNull private Properties loadProperties() { File file = new File(homeLocator.getHomeDir(), configFilename); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { throw new RuntimeException("IOException while creating \"" + file.getAbsolutePath() + "\".", e); } } if (!file.canRead() || !file.canWrite()) { throw new RuntimeException("Cannot read and write from file: " + file.getAbsolutePath()); } if (lastModifiedByUs < file.lastModified()) { if (logger.isLoggable(Level.FINE)) { logger.fine("File \"" + file + "\" is newer on disk. Read it ..."); } Properties properties = new Properties(); try { FileInputStream in = new FileInputStream(file); try { properties.loadFromXML(in); } catch (InvalidPropertiesFormatException e) { FileOutputStream out = new FileOutputStream(file); try { properties.storeToXML(out, comment); } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { throw new RuntimeException("IOException while reading from \"" + file.getAbsolutePath() + "\".", e); } this.lastModifiedByUs = file.lastModified(); this.properties = properties; if (logger.isLoggable(Level.FINE)) { logger.fine("... read done."); } } assert this.properties != null; return this.properties; }
154
0
@Override protected void loadInternals(final File internDir, final ExecutionMonitor exec) throws IOException, CanceledExecutionException { List<String> taxa = new Vector<String>(); String domain = m_domain.getStringValue(); String id = ""; if (domain.equalsIgnoreCase("Eukaryota")) id = "eukaryota"; try { URL url = new URL("http://www.ebi.ac.uk/genomes/" + id + ".details.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream())); String link = ""; String key = ""; String name = ""; int counter = 0; String line = ""; while ((line = reader.readLine()) != null) { String[] st = line.split("\t"); ena_details ena = new ena_details(st[0], st[1], st[2], st[3], st[4]); ENADataHolder.instance().put(ena.desc, ena); taxa.add(ena.desc); } reader.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void save(File f, AudioFileFormat.Type t) throws IOException { if (t.getExtension().equals("raw")) { IOUtils.copy(makeInputStream(), new FileOutputStream(f)); } else { AudioSystem.write(makeStream(), t, f); } }
155
1
public static Set<Province> getProvincias(String pURL) { Set<Province> result = new HashSet<Province>(); String iniProv = "<prov>"; String finProv = "</prov>"; String iniNomProv = "<np>"; String finNomProv = "</np>"; String iniCodigo = "<cpine>"; String finCodigo = "</cpine>"; int ini, fin; try { URL url = new URL(pURL); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String str; Province provincia; while ((str = br.readLine()) != null) { if (str.contains(iniProv)) { provincia = new Province(); while ((str = br.readLine()) != null && !str.contains(finProv)) { if (str.contains(iniNomProv)) { ini = str.indexOf(iniNomProv) + iniNomProv.length(); fin = str.indexOf(finNomProv); provincia.setDescription(str.substring(ini, fin)); } if (str.contains(iniCodigo)) { ini = str.indexOf(iniCodigo) + iniCodigo.length(); fin = str.indexOf(finCodigo); provincia.setCodeProvince(Integer.parseInt(str.substring(ini, fin))); } } result.add(provincia); } } br.close(); } catch (Exception e) { System.err.println(e); } return result; }
@SuppressWarnings("unchecked") private List<String> getWordList() { IConfiguration config = Configurator.getDefaultConfigurator().getConfig(CONFIG_ID); List<String> wList = (List<String>) config.getObject("word_list"); if (wList == null) { wList = new ArrayList<String>(); InputStream resrc = null; try { resrc = new URL(list_url).openStream(); } catch (Exception e) { e.printStackTrace(); } if (resrc != null) { BufferedReader br = new BufferedReader(new InputStreamReader(resrc)); String line; try { while ((line = br.readLine()) != null) { line = line.trim(); if (line.length() != 0) { wList.add(line); } } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } } } return wList; }
156
1
public static Document convertHtmlToXml(final InputStream htmlInputStream, final String classpathXsltResource, final String encoding) { Parser p = new Parser(); javax.xml.parsers.DocumentBuilder db; try { db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException e) { log.error("", e); throw new RuntimeException(); } Document document = db.newDocument(); InputStream is = htmlInputStream; if (log.isDebugEnabled()) { ByteArrayOutputStream baos; baos = new ByteArrayOutputStream(); try { IOUtils.copy(is, baos); } catch (IOException e) { log.error("Fail to make input stream copy.", e); } IOUtils.closeQuietly(is); ByteArrayInputStream byteArrayInputStream; byteArrayInputStream = new ByteArrayInputStream(baos.toByteArray()); try { IOUtils.toString(new ByteArrayInputStream(baos.toByteArray()), "UTF-8"); } catch (IOException e) { log.error("", e); } IOUtils.closeQuietly(byteArrayInputStream); is = new ByteArrayInputStream(baos.toByteArray()); } try { InputSource iSource = new InputSource(is); iSource.setEncoding(encoding); Source transformerSource = new SAXSource(p, iSource); Result result = new DOMResult(document); Transformer xslTransformer = getTransformerByName(classpathXsltResource, false); try { xslTransformer.transform(transformerSource, result); } catch (TransformerException e) { throw new RuntimeException(e); } } finally { try { is.close(); } catch (Exception e) { log.warn("", e); } } return document; }
private void externalizeFiles(Document doc, File out) throws IOException { File[] files = doc.getImages(); if (files.length > 0) { File dir = new File(out.getParentFile(), out.getName() + ".images"); if (!dir.mkdirs()) throw new IOException("cannot create directory " + dir); if (dir.exists()) { for (int i = 0; i < files.length; i++) { File file = files[i]; File copy = new File(dir, file.getName()); FileChannel from = null, to = null; long count = -1; try { from = new FileInputStream(file).getChannel(); count = from.size(); to = new FileOutputStream(copy).getChannel(); from.transferTo(0, count, to); doc.setImage(file, dir.getName() + "/" + copy.getName()); } catch (Throwable t) { LOG.log(Level.WARNING, "Copying '" + file + "' to '" + copy + "' failed (size=" + count + ")", t); } finally { try { to.close(); } catch (Throwable t) { } try { from.close(); } catch (Throwable t) { } } } } } }
157
0
public static String encryptPassword(String password) { if (password == null) return null; MessageDigest digest = null; try { digest = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { log.error("Algorithm not found", e); return null; } digest.reset(); digest.update(password.getBytes()); return hexValue(digest.digest()); }
public void testJTLM_publish100() throws Exception { EXISchema corpus = EXISchemaFactoryTestUtil.getEXISchema("/JTLM/schemas/TLMComposite.xsd", getClass(), m_compilerErrors); Assert.assertEquals(0, m_compilerErrors.getTotalCount()); GrammarCache grammarCache = new GrammarCache(corpus, GrammarOptions.DEFAULT_OPTIONS); AlignmentType[] alignments = new AlignmentType[] { AlignmentType.bitPacked, AlignmentType.byteAligned, AlignmentType.preCompress, AlignmentType.compress }; for (AlignmentType alignment : alignments) { Transmogrifier encoder = new Transmogrifier(); EXIDecoder decoder = new EXIDecoder(999); Scanner scanner; InputSource inputSource; encoder.setAlignmentType(alignment); decoder.setAlignmentType(alignment); encoder.setEXISchema(grammarCache); ByteArrayOutputStream baos = new ByteArrayOutputStream(); encoder.setOutputStream(baos); URL url = resolveSystemIdAsURL("/JTLM/publish100.xml"); inputSource = new InputSource(url.toString()); inputSource.setByteStream(url.openStream()); byte[] bts; int n_events, n_texts; encoder.encode(inputSource); bts = baos.toByteArray(); decoder.setEXISchema(grammarCache); decoder.setInputStream(new ByteArrayInputStream(bts)); scanner = decoder.processHeader(); ArrayList<EXIEvent> exiEventList = new ArrayList<EXIEvent>(); EXIEvent exiEvent; n_events = 0; n_texts = 0; while ((exiEvent = scanner.nextEvent()) != null) { ++n_events; if (exiEvent.getEventVariety() == EXIEvent.EVENT_CH) { if (n_texts % 100 == 0) { final int n = n_texts / 100; Assert.assertEquals(publish100_centennials[n], exiEvent.getCharacters().makeString()); } ++n_texts; } exiEventList.add(exiEvent); } Assert.assertEquals(10610, n_events); } }
158
0
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; }
public TestReport runImpl() throws Exception { String parser = XMLResourceDescriptor.getXMLParserClassName(); DocumentFactory df = new SAXDocumentFactory(GenericDOMImplementation.getDOMImplementation(), parser); File f = (new File(testFileName)); URL url = f.toURL(); Document doc = df.createDocument(null, rootTag, url.toString(), url.openStream()); Element e = doc.getElementById(targetId); if (e == null) { DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(ERROR_GET_ELEMENT_BY_ID_FAILED); report.addDescriptionEntry(ENTRY_KEY_ID, targetId); report.setPassed(false); return report; } Document otherDocument = df.createDocument(null, rootTag, url.toString(), url.openStream()); DocumentFragment docFrag = otherDocument.createDocumentFragment(); try { docFrag.appendChild(doc.getDocumentElement()); } catch (DOMException ex) { return reportSuccess(); } DefaultTestReport report = new DefaultTestReport(this); report.setErrorCode(ERROR_EXCEPTION_NOT_THROWN); report.setPassed(false); return report; }
159
1
private byte[] streamToBytes(InputStream in) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { IOUtils.copy(in, out); } finally { IOUtils.closeQuietly(in); } return out.toByteArray(); }
public static void copyFile(File inputFile, File outputFile) throws IOException { FileChannel srcChannel = new FileInputStream(inputFile).getChannel(); FileChannel dstChannel = new FileOutputStream(outputFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
160
0
protected URLConnection openConnection(URL url) throws IOException { if (bundleEntry != null) return (new BundleURLConnection(url, bundleEntry)); String bidString = url.getHost(); if (bidString == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_ID, url.toExternalForm())); } AbstractBundle bundle = null; long bundleID; try { bundleID = Long.parseLong(bidString); } catch (NumberFormatException nfe) { throw new MalformedURLException(NLS.bind(AdaptorMsg.URL_INVALID_BUNDLE_ID, bidString)); } bundle = (AbstractBundle) context.getBundle(bundleID); if (!url.getAuthority().equals(SECURITY_AUTHORIZED)) { checkAdminPermission(bundle); } if (bundle == null) { throw new IOException(NLS.bind(AdaptorMsg.URL_NO_BUNDLE_FOUND, url.toExternalForm())); } return (new BundleURLConnection(url, findBundleEntry(url, bundle))); }
public static String MD5(String s) { try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(s.getBytes(), 0, s.length()); return new BigInteger(1, m.digest()).toString(16); } catch (NoSuchAlgorithmException ex) { return ""; } }
161
1
private void copy(String imgPath, String path) { try { File input = new File(imgPath); File output = new File(path, input.getName()); if (output.exists()) { if (!MessageDialog.openQuestion(getShell(), "Overwrite", "There is already an image file " + input.getName() + " under the package.\n Do you really want to overwrite it?")) return; } byte[] data = new byte[1024]; FileInputStream fis = new FileInputStream(imgPath); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output)); int length; while ((length = bis.read(data)) > 0) { bos.write(data, 0, length); bos.flush(); } bos.close(); fis.close(); IJavaProject ijp = VisualSwingPlugin.getCurrentProject(); if (ijp != null) { ijp.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); view.refresh(); view.expandAll(); } } catch (Exception e) { VisualSwingPlugin.getLogger().error(e); } }
public static void compress(final File zip, final Map<InputStream, String> entries) throws IOException { if (zip == null || entries == null || CollectionUtils.isEmpty(entries.keySet())) throw new IllegalArgumentException("One ore more parameters are empty!"); if (zip.exists()) zip.delete(); else if (!zip.getParentFile().exists()) zip.getParentFile().mkdirs(); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zip))); out.setLevel(Deflater.BEST_COMPRESSION); InputStream in = null; try { for (InputStream inputStream : entries.keySet()) { in = inputStream; ZipEntry zipEntry = new ZipEntry(skipBeginningSlash(entries.get(in))); out.putNextEntry(zipEntry); IOUtils.copy(in, out); out.closeEntry(); in.close(); } } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }
162
1
public static void copy(File src, File dest) throws IOException { OutputStream stream = new FileOutputStream(dest); FileInputStream fis = new FileInputStream(src); byte[] buffer = new byte[16384]; while (fis.available() != 0) { int read = fis.read(buffer); stream.write(buffer, 0, read); } stream.flush(); }
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
163
1
public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
private static void copy(File src, File dst) { try { FileChannel srcChannel = new FileInputStream(src).getChannel(); FileChannel dstChannel = new FileOutputStream(dst).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } }
164
1
static void conditionalCopyFile(File dst, File src) throws IOException { if (dst.equals(src)) return; if (!dst.isFile() || dst.lastModified() < src.lastModified()) { System.out.println("Copying " + src); InputStream is = new FileInputStream(src); OutputStream os = new FileOutputStream(dst); byte[] buf = new byte[8192]; int len; while ((len = is.read(buf)) > 0) os.write(buf, 0, len); os.close(); is.close(); } }
public static boolean decodeFileToFile(String infile, String outfile) { boolean success = false; java.io.InputStream in = null; java.io.OutputStream out = null; try { in = new Base64.InputStream(new java.io.BufferedInputStream(new java.io.FileInputStream(infile)), Base64.DECODE); out = new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile)); byte[] buffer = new byte[65536]; int read = -1; while ((read = in.read(buffer)) >= 0) { out.write(buffer, 0, read); } success = true; } catch (java.io.IOException exc) { exc.printStackTrace(); } finally { try { in.close(); } catch (Exception exc) { } try { out.close(); } catch (Exception exc) { } } return success; }
165
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!"); }
private String createDefaultRepoConf() throws IOException { InputStream confIn = getClass().getResourceAsStream(REPO_CONF_PATH); File tempConfFile = File.createTempFile("repository", "xml"); tempConfFile.deleteOnExit(); IOUtils.copy(confIn, new FileOutputStream(tempConfFile)); return tempConfFile.getAbsolutePath(); }
166
0
private static void copy(File source, File dest) throws FileNotFoundException, IOException { FileInputStream input = new FileInputStream(source); FileOutputStream output = new FileOutputStream(dest); System.out.println("Copying " + source + " to " + dest); IOUtils.copy(input, output); output.close(); input.close(); dest.setLastModified(source.lastModified()); }
public static void readDefault() { ClassLoader l = Skeleton.class.getClassLoader(); URL url = l.getResource("weka/core/parser/JFlex/skeleton.default"); if (url == null) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } try { InputStreamReader reader = new InputStreamReader(url.openStream()); readSkel(new BufferedReader(reader)); } catch (IOException e) { Out.error(ErrorMessages.SKEL_IO_ERROR_DEFAULT); throw new GeneratorException(); } }
167
1
public static void copyFile(File in, File out) throws IOException { FileChannel inChannel = new FileInputStream(in).getChannel(); FileChannel outChannel = new FileOutputStream(out).getChannel(); try { inChannel.transferTo(0, inChannel.size(), outChannel); } finally { if (inChannel != null) inChannel.close(); if (outChannel != null) outChannel.close(); } }
public static void copyFile(File sourceFile, File targetFile) throws IOException { if (sourceFile == null || targetFile == null) { throw new NullPointerException("Source file and target file must not be null"); } File directory = targetFile.getParentFile(); if (!directory.exists() && !directory.mkdirs()) { throw new IOException("Could not create directory '" + directory + "'"); } InputStream inputStream = null; OutputStream outputStream = null; try { inputStream = new BufferedInputStream(new FileInputStream(sourceFile)); outputStream = new BufferedOutputStream(new FileOutputStream(targetFile)); try { byte[] buffer = new byte[32768]; for (int readBytes = inputStream.read(buffer); readBytes > 0; readBytes = inputStream.read(buffer)) { outputStream.write(buffer, 0, readBytes); } } catch (IOException ex) { targetFile.delete(); throw ex; } } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException ex) { } } if (outputStream != null) { try { outputStream.close(); } catch (IOException ex) { } } } }
168
0
public static Bitmap loadPhotoBitmap(final String imageUrl, final String type) { InputStream imageStream = null; try { HttpGet httpRequest = new HttpGet(new URL(imageUrl).toURI()); HttpResponse response = (HttpResponse) new DefaultHttpClient().execute(httpRequest); httpRequest = null; BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(response.getEntity()); response = null; imageStream = bufHttpEntity.getContent(); bufHttpEntity = null; if (imageStream != null) { final BitmapFactory.Options options = new BitmapFactory.Options(); if (type.equals("image")) { options.inSampleSize = 2; } return BitmapFactory.decodeStream(imageStream, null, options); } else { } } catch (IOException e) { } catch (URISyntaxException e) { } finally { if (imageStream != null) closeStream(imageStream); } return null; }
public static String urlPost(Map<String, String> paraMap, String urlStr) throws IOException { String strParam = ""; for (Map.Entry<String, String> entry : paraMap.entrySet()) { strParam = strParam + (entry.getKey() + "=" + entry.getValue()) + "&"; } URL url = new URL(urlStr); URLConnection connection = url.openConnection(); connection.setDoOutput(true); OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8"); out.write(strParam); out.flush(); out.close(); String sCurrentLine; String sTotalString; sCurrentLine = ""; sTotalString = ""; InputStream l_urlStream; l_urlStream = connection.getInputStream(); BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream)); while ((sCurrentLine = l_reader.readLine()) != null) { sTotalString += sCurrentLine + "\r\n"; } System.out.println(sTotalString); return sTotalString; }
169
0
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; }
public void loadFromFile() { if (filename == null) return; try { BufferedReader reader; try { File file = new File(filename); if (!file.exists()) return; reader = new BufferedReader(new FileReader(file)); } catch (java.security.AccessControlException e) { URL url = new URL(filename); reader = new BufferedReader(new InputStreamReader(url.openStream())); } String line; while (true) { line = reader.readLine(); if (line == null) break; String name = line.substring(0, line.indexOf("\t")); String rest1 = line.substring(line.indexOf("\t") + 1); String guiname = rest1.substring(0, rest1.indexOf("\t")); String rest2 = rest1.substring(rest1.indexOf("\t") + 1); String type = rest2.substring(0, rest2.indexOf("\t")); String value = rest2.substring(rest2.indexOf("\t") + 1); defineField(name, guiname, type); setField(name, value, true); } reader.close(); } catch (IOException e) { throw new JGameError("Error reading file '" + filename + "'.", false); } }
170
1
public static void copyFile(File source, File dest) throws IOException { if (source.equals(dest)) throw new IOException("Source and destination cannot be the same file path"); FileChannel srcChannel = new FileInputStream(source).getChannel(); if (!dest.exists()) dest.createNewFile(); FileChannel dstChannel = new FileOutputStream(dest).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); }
public static void copyFile(String input, String output) { try { FileChannel srcChannel = new FileInputStream("srcFilename").getChannel(); FileChannel dstChannel = new FileOutputStream("dstFilename").getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException e) { } }
171
1
@Test public void testWriteAndReadBiggerUnbuffered() throws Exception { JCFSFileServer server = new JCFSFileServer(defaultTcpPort, defaultTcpAddress, defaultUdpPort, defaultUdpAddress, dir, 0, 0); JCFS.configureDiscovery(defaultUdpAddress, defaultUdpPort); try { server.start(); RFile file = new RFile("testreadwriteb.txt"); RFileOutputStream out = new RFileOutputStream(file); String body = ""; int size = 50 * 1024; for (int i = 0; i < size; i++) { body = body + "a"; } out.write(body.getBytes("utf-8")); out.close(); File expected = new File(dir, "testreadwriteb.txt"); assertTrue(expected.isFile()); assertEquals(body.length(), expected.length()); RFileInputStream in = new RFileInputStream(file); ByteArrayOutputStream tmp = new ByteArrayOutputStream(); int b = in.read(); while (b != -1) { tmp.write(b); b = in.read(); } byte[] buffer = tmp.toByteArray(); in.close(); assertEquals(body.length(), buffer.length); String resultRead = new String(buffer, "utf-8"); assertEquals(body, resultRead); } finally { server.stop(); } }
public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) { File srcFile = new File(srcFileName); if (!srcFile.exists()) { System.out.println("复制文件失败,源文件" + srcFileName + "不存在!"); return false; } else if (!srcFile.isFile()) { System.out.println("复制文件失败," + srcFileName + "不是一个文件!"); return false; } File descFile = new File(descFileName); if (descFile.exists()) { if (coverlay) { System.out.println("目标文件已存在,准备删除!"); if (!FileOperateUtils.delFile(descFileName)) { System.out.println("删除目标文件" + descFileName + "失败!"); return false; } } else { System.out.println("复制文件失败,目标文件" + descFileName + "已存在!"); return false; } } else { if (!descFile.getParentFile().exists()) { System.out.println("目标文件所在的目录不存在,创建目录!"); if (!descFile.getParentFile().mkdirs()) { System.out.println("创建目标文件所在的目录失败!"); return false; } } } int readByte = 0; InputStream ins = null; OutputStream outs = null; try { ins = new FileInputStream(srcFile); outs = new FileOutputStream(descFile); byte[] buf = new byte[1024]; while ((readByte = ins.read(buf)) != -1) { outs.write(buf, 0, readByte); } System.out.println("复制单个文件" + srcFileName + "到" + descFileName + "成功!"); return true; } catch (Exception e) { System.out.println("复制文件失败:" + e.getMessage()); return false; } finally { if (outs != null) { try { outs.close(); } catch (IOException oute) { oute.printStackTrace(); } } if (ins != null) { try { ins.close(); } catch (IOException ine) { ine.printStackTrace(); } } } }
172
1
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(); } } }
private void copy(final File src, final File dstDir) { dstDir.mkdirs(); final File dst = new File(dstDir, src.getName()); BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(src), "ISO-8859-1")); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "ISO-8859-1")); String read; while ((read = reader.readLine()) != null) { Line line = new Line(read); if (line.isComment()) continue; writer.write(read); writer.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } if (writer != null) { try { writer.flush(); } catch (IOException e) { } try { writer.close(); } catch (IOException e) { } } } }
173
1
public static void copy(String srcFileName, String destFileName) throws IOException { if (srcFileName == null) { throw new IllegalArgumentException("srcFileName is null"); } if (destFileName == null) { throw new IllegalArgumentException("destFileName is null"); } FileChannel src = null; FileChannel dest = null; try { src = new FileInputStream(srcFileName).getChannel(); dest = new FileOutputStream(destFileName).getChannel(); long n = src.size(); MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, n); dest.write(buf); } finally { if (dest != null) { try { dest.close(); } catch (IOException e1) { } } if (src != null) { try { src.close(); } catch (IOException e1) { } } } }
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()); }
174
0
protected static String getURLandWriteToDisk(String url, Model retModel) throws MalformedURLException, IOException { String path = null; URL ontURL = new URL(url); InputStream ins = ontURL.openStream(); InputStreamReader bufRead; OutputStreamWriter bufWrite; int offset = 0, read = 0; initModelHash(); if (System.getProperty("user.dir") != null) { String delimiter; path = System.getProperty("user.dir"); if (path.contains("/")) { delimiter = "/"; } else { delimiter = "\\"; } char c = path.charAt(path.length() - 1); if (c == '/' || c == '\\') { path = path.substring(0, path.length() - 2); } path = path.substring(0, path.lastIndexOf(delimiter) + 1); path = path.concat("ontologies" + delimiter + "downloaded"); (new File(path)).mkdir(); path = path.concat(delimiter); path = createFullPath(url, path); bufWrite = new OutputStreamWriter(new FileOutputStream(path)); bufRead = new InputStreamReader(ins); read = bufRead.read(); while (read != -1) { bufWrite.write(read); offset += read; read = bufRead.read(); } bufRead.close(); bufWrite.close(); ins.close(); FileInputStream fs = new FileInputStream(path); retModel.read(fs, ""); } return path; }
public static void main(String[] args) { try { File fichierXSD = new File("D:/Users/Balley/données/gml/commune.xsd"); URL urlFichierXSD = fichierXSD.toURI().toURL(); InputStream isXSD = urlFichierXSD.openStream(); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbFactory.newDocumentBuilder(); Document documentXSD = (builder.parse(isXSD)); ChargeurGMLSchema chargeur = new ChargeurGMLSchema(documentXSD); SchemaConceptuelJeu sc = chargeur.gmlSchema2schemaConceptuel(documentXSD); System.out.println(sc.getFeatureTypes().size()); for (int i = 0; i < sc.getFeatureTypes().size(); i++) { System.out.println(sc.getFeatureTypes().get(i).getTypeName()); for (int j = 0; j < sc.getFeatureTypes().get(i).getFeatureAttributes().size(); j++) { System.out.println(" " + sc.getFeatureTypes().get(i).getFeatureAttributes().get(j).getMemberName() + " : " + sc.getFeatureTypes().get(i).getFeatureAttributes().get(j).getValueType()); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } }
175
1
public static boolean copyFile(String fileIn, String fileOut) { FileChannel in = null; FileChannel out = null; boolean retour = false; try { in = new FileInputStream(fileIn).getChannel(); out = new FileOutputStream(fileOut).getChannel(); in.transferTo(0, in.size(), out); in.close(); out.close(); retour = true; } catch (IOException e) { System.err.println("File : " + fileIn); e.printStackTrace(); } return retour; }
protected static String getFileContentAsString(URL url, String encoding) throws IOException { InputStream input = null; StringWriter sw = new StringWriter(); try { System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); input = url.openStream(); IOUtils.copy(input, sw, encoding); System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); } finally { if (input != null) { input.close(); System.gc(); input = null; System.out.println("Free mem :" + Runtime.getRuntime().freeMemory()); } } return sw.toString(); }
176
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(); } }
public void jsFunction_extract(ScriptableFile outputFile) throws IOException, FileSystemException, ArchiveException { InputStream is = file.jsFunction_createInputStream(); OutputStream output = outputFile.jsFunction_createOutputStream(); BufferedInputStream buf = new BufferedInputStream(is); ArchiveInputStream input = ScriptableZipArchive.getFactory().createArchiveInputStream(buf); try { long count = 0; while (input.getNextEntry() != null) { if (count == offset) { IOUtils.copy(input, output); break; } count++; } } finally { input.close(); output.close(); is.close(); } }
177
1
public void copyFileFromLocalMachineToRemoteMachine(InputStream source, File destination) throws Exception { String fileName = destination.getPath(); File f = new File(getFtpServerHome(), "" + System.currentTimeMillis()); f.deleteOnExit(); org.apache.commons.io.IOUtils.copy(source, new FileOutputStream(f)); remoteHostClient.setAscii(isAscii()); remoteHostClient.setPromptOn(isPrompt()); remoteHostClient.copyFileFromLocalMachineToRemoteClient(f.getName(), fileName); }
public static void copieFichier(File fichier1, File fichier2) { FileChannel in = null; FileChannel out = null; try { in = new FileInputStream(fichier1).getChannel(); out = new FileOutputStream(fichier2).getChannel(); in.transferTo(0, in.size(), out); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { } } if (out != null) { try { out.close(); } catch (IOException e) { } } } }
178
0
public void readConfig(String urlString) throws Exception { try { URL url = new URL(urlString); InputStream in = url.openStream(); XmlDoc xml = new Parser().parse(new InputSource(in), true, true); Verifier v = new Verifier(InputOutput.create(SCHEMA), null); v.verify(xml.getDocument()); this.config = xml.getDocument(); } catch (Exception e) { log("Can't read " + urlString + ": " + e.toString()); throw e; } initParms(); log("Got parameters: \n" + paramsInfo()); initMessages(); log("Got messages: \n" + messagesInfo()); checkMessageId(); }
protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream, DocumentFormat outputFormat) { File inputFile = null; File outputFile = null; try { inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); OutputStream inputFileStream = null; try { inputFileStream = new FileOutputStream(inputFile); IOUtils.copy(inputStream, inputFileStream); } finally { IOUtils.closeQuietly(inputFileStream); } outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); convert(inputFile, inputFormat, outputFile, outputFormat); InputStream outputFileStream = null; try { outputFileStream = new FileInputStream(outputFile); IOUtils.copy(outputFileStream, outputStream); } finally { IOUtils.closeQuietly(outputFileStream); } } catch (IOException ioException) { throw new OpenOfficeException("conversion failed", ioException); } finally { if (inputFile != null) { inputFile.delete(); } if (outputFile != null) { outputFile.delete(); } } }
179
1
private static void insertModuleInEar(File fromEar, File toEar, String moduleType, String moduleName, String contextRoot) throws Exception { ZipInputStream earFile = new ZipInputStream(new FileInputStream(fromEar)); FileOutputStream fos = new FileOutputStream(toEar); ZipOutputStream tempZip = new ZipOutputStream(fos); ZipEntry next = earFile.getNextEntry(); while (next != null) { ByteArrayOutputStream content = new ByteArrayOutputStream(); byte[] data = new byte[30000]; int numberread; while ((numberread = earFile.read(data)) != -1) { content.write(data, 0, numberread); } if (next.getName().equals("META-INF/application.xml")) { content = insertModule(earFile, next, content, moduleType, moduleName, contextRoot); next = new ZipEntry("META-INF/application.xml"); } tempZip.putNextEntry(next); tempZip.write(content.toByteArray()); next = earFile.getNextEntry(); } earFile.close(); tempZip.close(); fos.close(); }
public void copyFileToFileWithPaths(String sourcePath, String destinPath) throws Exception { BufferedInputStream in = null; BufferedOutputStream out = null; byte dataBuff[] = new byte[bufferSize]; File file1 = new File(sourcePath); if (file1.exists() && (file1.isFile())) { File file2 = new File(destinPath); if (file2.exists()) { file2.delete(); } FileUtils.getInstance().createDirectory(file2.getParent()); in = new BufferedInputStream(new FileInputStream(sourcePath), bufferSize); out = new BufferedOutputStream(new FileOutputStream(destinPath), bufferSize); int readLen; while ((readLen = in.read(dataBuff)) > 0) { out.write(dataBuff, 0, readLen); } out.flush(); in.close(); out.close(); } else { throw new Exception("Source file not exist ! sourcePath = (" + sourcePath + ")"); } }
180
1
public static void main(String argv[]) { Matrix A, B, C, Z, O, I, R, S, X, SUB, M, T, SQ, DEF, SOL; int errorCount = 0; int warningCount = 0; double tmp, s; double[] columnwise = { 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12. }; double[] rowwise = { 1., 4., 7., 10., 2., 5., 8., 11., 3., 6., 9., 12. }; double[][] avals = { { 1., 4., 7., 10. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] rankdef = avals; double[][] tvals = { { 1., 2., 3. }, { 4., 5., 6. }, { 7., 8., 9. }, { 10., 11., 12. } }; double[][] subavals = { { 5., 8., 11. }, { 6., 9., 12. } }; double[][] rvals = { { 1., 4., 7. }, { 2., 5., 8., 11. }, { 3., 6., 9., 12. } }; double[][] pvals = { { 1., 1., 1. }, { 1., 2., 3. }, { 1., 3., 6. } }; double[][] ivals = { { 1., 0., 0., 0. }, { 0., 1., 0., 0. }, { 0., 0., 1., 0. } }; double[][] evals = { { 0., 1., 0., 0. }, { 1., 0., 2.e-7, 0. }, { 0., -2.e-7, 0., 1. }, { 0., 0., 1., 0. } }; double[][] square = { { 166., 188., 210. }, { 188., 214., 240. }, { 210., 240., 270. } }; double[][] sqSolution = { { 13. }, { 15. } }; double[][] condmat = { { 1., 3. }, { 7., 9. } }; int rows = 3, cols = 4; int invalidld = 5; int raggedr = 0; int raggedc = 4; int validld = 3; int nonconformld = 4; int ib = 1, ie = 2, jb = 1, je = 3; int[] rowindexset = { 1, 2 }; int[] badrowindexset = { 1, 3 }; int[] columnindexset = { 1, 2, 3 }; int[] badcolumnindexset = { 1, 2, 4 }; double columnsummax = 33.; double rowsummax = 30.; double sumofdiagonals = 15; double sumofsquares = 650; print("\nTesting constructors and constructor-like methods...\n"); try { A = new Matrix(columnwise, invalidld); errorCount = try_failure(errorCount, "Catch invalid length in packed constructor... ", "exception not thrown for invalid input"); } catch (IllegalArgumentException e) { try_success("Catch invalid length in packed constructor... ", e.getMessage()); } try { A = new Matrix(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to default constructor... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructor... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } try { A = Matrix.constructWithCopy(rvals); tmp = A.get(raggedr, raggedc); } catch (IllegalArgumentException e) { try_success("Catch ragged input to constructWithCopy... ", e.getMessage()); } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "Catch ragged input to constructWithCopy... ", "exception not thrown in construction...ArrayIndexOutOfBoundsException thrown later"); } A = new Matrix(columnwise, validld); B = new Matrix(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; C = B.minus(A); avals[0][0] = tmp; B = Matrix.constructWithCopy(avals); tmp = B.get(0, 0); avals[0][0] = 0.0; if ((tmp - B.get(0, 0)) != 0.0) { errorCount = try_failure(errorCount, "constructWithCopy... ", "copy not effected... data visible outside"); } else { try_success("constructWithCopy... ", ""); } avals[0][0] = columnwise[0]; I = new Matrix(ivals); try { check(I, Matrix.identity(3, 4)); try_success("identity... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "identity... ", "identity Matrix not successfully created"); } print("\nTesting access methods...\n"); B = new Matrix(avals); if (B.getRowDimension() != rows) { errorCount = try_failure(errorCount, "getRowDimension... ", ""); } else { try_success("getRowDimension... ", ""); } if (B.getColumnDimension() != cols) { errorCount = try_failure(errorCount, "getColumnDimension... ", ""); } else { try_success("getColumnDimension... ", ""); } B = new Matrix(avals); double[][] barray = B.getArray(); if (barray != avals) { errorCount = try_failure(errorCount, "getArray... ", ""); } else { try_success("getArray... ", ""); } barray = B.getArrayCopy(); if (barray == avals) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not (deep) copied"); } try { check(barray, avals); try_success("getArrayCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getArrayCopy... ", "data not successfully (deep) copied"); } double[] bpacked = B.getColumnPackedCopy(); try { check(bpacked, columnwise); try_success("getColumnPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getColumnPackedCopy... ", "data not successfully (deep) copied by columns"); } bpacked = B.getRowPackedCopy(); try { check(bpacked, rowwise); try_success("getRowPackedCopy... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getRowPackedCopy... ", "data not successfully (deep) copied by rows"); } try { tmp = B.get(B.getRowDimension(), B.getColumnDimension() - 1); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { tmp = B.get(B.getRowDimension() - 1, B.getColumnDimension()); errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("get(int,int)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "get(int,int)... ", "OutOfBoundsException expected but not thrown"); } try { if (B.get(B.getRowDimension() - 1, B.getColumnDimension() - 1) != avals[B.getRowDimension() - 1][B.getColumnDimension() - 1]) { errorCount = try_failure(errorCount, "get(int,int)... ", "Matrix entry (i,j) not successfully retreived"); } else { try_success("get(int,int)... ", ""); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "get(int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } SUB = new Matrix(subavals); try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, jb, je); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, jb, je); try { check(SUB, M); try_success("getMatrix(int,int,int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(ib, ie, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(ib, ie + B.getRowDimension() + 1, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int,int,int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(ib, ie, columnindexset); try { check(SUB, M); try_success("getMatrix(int,int,int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int,int,int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, jb, je); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, jb, je + B.getColumnDimension() + 1); errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int,int)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, jb, je); try { check(SUB, M); try_success("getMatrix(int[],int,int)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int,int)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { M = B.getMatrix(badrowindexset, columnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { M = B.getMatrix(rowindexset, badcolumnindexset); errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("getMatrix(int[],int[])... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { M = B.getMatrix(rowindexset, columnindexset); try { check(SUB, M); try_success("getMatrix(int[],int[])... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "submatrix not successfully retreived"); } } catch (java.lang.ArrayIndexOutOfBoundsException e) { errorCount = try_failure(errorCount, "getMatrix(int[],int[])... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.set(B.getRowDimension(), B.getColumnDimension() - 1, 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.set(B.getRowDimension() - 1, B.getColumnDimension(), 0.); errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("set(int,int,double)... OutofBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "OutOfBoundsException expected but not thrown"); } try { B.set(ib, jb, 0.); tmp = B.get(ib, jb); try { check(tmp, 0.); try_success("set(int,int,double)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Matrix element not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "set(int,int,double)... ", "Unexpected ArrayIndexOutOfBoundsException"); } M = new Matrix(2, 3, 0.); try { B.setMatrix(ib, ie + B.getRowDimension() + 1, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, jb, je, M); try { check(M.minus(B.getMatrix(ib, ie, jb, je)), M); try_success("setMatrix(int,int,int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(ib, ie + B.getRowDimension() + 1, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(ib, ie, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int,int,int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(ib, ie, columnindexset, M); try { check(M.minus(B.getMatrix(ib, ie, columnindexset)), M); try_success("setMatrix(int,int,int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int,int,int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, jb, je + B.getColumnDimension() + 1, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, jb, je, M); errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int,int,Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, jb, je, M); try { check(M.minus(B.getMatrix(rowindexset, jb, je)), M); try_success("setMatrix(int[],int,int,Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "submatrix not successfully set"); } B.setMatrix(ib, ie, jb, je, SUB); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int,int,Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } try { B.setMatrix(rowindexset, badcolumnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { try { B.setMatrix(badrowindexset, columnindexset, M); errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } catch (java.lang.ArrayIndexOutOfBoundsException e1) { try_success("setMatrix(int[],int[],Matrix)... ArrayIndexOutOfBoundsException... ", ""); } } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "ArrayIndexOutOfBoundsException expected but not thrown"); } try { B.setMatrix(rowindexset, columnindexset, M); try { check(M.minus(B.getMatrix(rowindexset, columnindexset)), M); try_success("setMatrix(int[],int[],Matrix)... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "submatrix not successfully set"); } } catch (java.lang.ArrayIndexOutOfBoundsException e1) { errorCount = try_failure(errorCount, "setMatrix(int[],int[],Matrix)... ", "Unexpected ArrayIndexOutOfBoundsException"); } print("\nTesting array-like methods...\n"); S = new Matrix(columnwise, nonconformld); R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); A = R; try { S = A.minus(S); errorCount = try_failure(errorCount, "minus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minus conformance check... ", ""); } if (A.minus(R).norm1() != 0.) { errorCount = try_failure(errorCount, "minus... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minus... ", ""); } A = R.copy(); A.minusEquals(R); Z = new Matrix(A.getRowDimension(), A.getColumnDimension()); try { A.minusEquals(S); errorCount = try_failure(errorCount, "minusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("minusEquals conformance check... ", ""); } if (A.minus(Z).norm1() != 0.) { errorCount = try_failure(errorCount, "minusEquals... ", "(difference of identical Matrices is nonzero,\nSubsequent use of minus should be suspect)"); } else { try_success("minusEquals... ", ""); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); C = A.minus(B); try { S = A.plus(S); errorCount = try_failure(errorCount, "plus conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plus conformance check... ", ""); } try { check(C.plus(B), A); try_success("plus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plus... ", "(C = A - B, but C + B != A)"); } C = A.minus(B); C.plusEquals(B); try { A.plusEquals(S); errorCount = try_failure(errorCount, "plusEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("plusEquals conformance check... ", ""); } try { check(C, A); try_success("plusEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "plusEquals... ", "(C = A - B, but C = C + B != A)"); } A = R.uminus(); try { check(A.plus(R), Z); try_success("uminus... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "uminus... ", "(-A + A != zeros)"); } A = R.copy(); O = new Matrix(A.getRowDimension(), A.getColumnDimension(), 1.0); C = A.arrayLeftDivide(R); try { S = A.arrayLeftDivide(S); errorCount = try_failure(errorCount, "arrayLeftDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivide conformance check... ", ""); } try { check(C, O); try_success("arrayLeftDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivide... ", "(M.\\M != ones)"); } try { A.arrayLeftDivideEquals(S); errorCount = try_failure(errorCount, "arrayLeftDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayLeftDivideEquals conformance check... ", ""); } A.arrayLeftDivideEquals(R); try { check(A, O); try_success("arrayLeftDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayLeftDivideEquals... ", "(M.\\M != ones)"); } A = R.copy(); try { A.arrayRightDivide(S); errorCount = try_failure(errorCount, "arrayRightDivide conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivide conformance check... ", ""); } C = A.arrayRightDivide(R); try { check(C, O); try_success("arrayRightDivide... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivide... ", "(M./M != ones)"); } try { A.arrayRightDivideEquals(S); errorCount = try_failure(errorCount, "arrayRightDivideEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayRightDivideEquals conformance check... ", ""); } A.arrayRightDivideEquals(R); try { check(A, O); try_success("arrayRightDivideEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayRightDivideEquals... ", "(M./M != ones)"); } A = R.copy(); B = Matrix.random(A.getRowDimension(), A.getColumnDimension()); try { S = A.arrayTimes(S); errorCount = try_failure(errorCount, "arrayTimes conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimes conformance check... ", ""); } C = A.arrayTimes(B); try { check(C.arrayRightDivideEquals(B), A); try_success("arrayTimes... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimes... ", "(A = R, C = A.*B, but C./B != A)"); } try { A.arrayTimesEquals(S); errorCount = try_failure(errorCount, "arrayTimesEquals conformance check... ", "nonconformance not raised"); } catch (IllegalArgumentException e) { try_success("arrayTimesEquals conformance check... ", ""); } A.arrayTimesEquals(B); try { check(A.arrayRightDivideEquals(B), R); try_success("arrayTimesEquals... ", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "arrayTimesEquals... ", "(A = R, A = A.*B, but A./B != R)"); } print("\nTesting I/O methods...\n"); try { DecimalFormat fmt = new DecimalFormat("0.0000E00"); fmt.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US)); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read()...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } catch (Exception e) { try { e.printStackTrace(System.out); warningCount = try_warning(warningCount, "print()/read()...", "Formatting error... will try JDK1.1 reformulation..."); DecimalFormat fmt = new DecimalFormat("0.0000"); PrintWriter FILE = new PrintWriter(new FileOutputStream("JamaTestMatrix.out")); A.print(FILE, fmt, 10); FILE.close(); R = Matrix.read(new BufferedReader(new FileReader("JamaTestMatrix.out"))); if (A.minus(R).norm1() < .001) { try_success("print()/read()...", ""); } else { errorCount = try_failure(errorCount, "print()/read() (2nd attempt) ...", "Matrix read from file does not match Matrix printed to file"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "print()/read()...", "unexpected I/O error, unable to run print/read test; check write permission in current directory and retry"); } } R = Matrix.random(A.getRowDimension(), A.getColumnDimension()); String tmpname = "TMPMATRIX.serial"; try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(tmpname)); out.writeObject(R); ObjectInputStream sin = new ObjectInputStream(new FileInputStream(tmpname)); A = (Matrix) sin.readObject(); try { check(A, R); try_success("writeObject(Matrix)/readObject(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "Matrix not serialized correctly"); } } catch (java.io.IOException ioe) { warningCount = try_warning(warningCount, "writeObject()/readObject()...", "unexpected I/O error, unable to run serialization test; check write permission in current directory and retry"); } catch (Exception e) { errorCount = try_failure(errorCount, "writeObject(Matrix)/readObject(Matrix)...", "unexpected error in serialization test"); } print("\nTesting linear algebra methods...\n"); A = new Matrix(columnwise, 3); T = new Matrix(tvals); T = A.transpose(); try { check(A.transpose(), T); try_success("transpose...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "transpose()...", "transpose unsuccessful"); } A.transpose(); try { check(A.norm1(), columnsummax); try_success("norm1...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "norm1()...", "incorrect norm calculation"); } try { check(A.normInf(), rowsummax); try_success("normInf()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normInf()...", "incorrect norm calculation"); } try { check(A.normF(), Math.sqrt(sumofsquares)); try_success("normF...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "normF()...", "incorrect norm calculation"); } try { check(A.trace(), sumofdiagonals); try_success("trace()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "trace()...", "incorrect trace calculation"); } try { check(A.getMatrix(0, A.getRowDimension() - 1, 0, A.getRowDimension() - 1).det(), 0.); try_success("det()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "det()...", "incorrect determinant calculation"); } SQ = new Matrix(square); try { check(A.times(A.transpose()), SQ); try_success("times(Matrix)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(Matrix)...", "incorrect Matrix-Matrix product calculation"); } try { check(A.times(0.), Z); try_success("times(double)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "times(double)...", "incorrect Matrix-scalar product calculation"); } A = new Matrix(columnwise, 4); QRDecomposition QR = A.qr(); R = QR.getR(); try { check(A, QR.getQ().times(R)); try_success("QRDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "QRDecomposition...", "incorrect QR decomposition calculation"); } SingularValueDecomposition SVD = A.svd(); try { check(A, SVD.getU().times(SVD.getS().times(SVD.getV().transpose()))); try_success("SingularValueDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "SingularValueDecomposition...", "incorrect singular value decomposition calculation"); } DEF = new Matrix(rankdef); try { check(DEF.rank(), Math.min(DEF.getRowDimension(), DEF.getColumnDimension()) - 1); try_success("rank()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "rank()...", "incorrect rank calculation"); } B = new Matrix(condmat); SVD = B.svd(); double[] singularvalues = SVD.getSingularValues(); try { check(B.cond(), singularvalues[0] / singularvalues[Math.min(B.getRowDimension(), B.getColumnDimension()) - 1]); try_success("cond()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "cond()...", "incorrect condition number calculation"); } int n = A.getColumnDimension(); A = A.getMatrix(0, n - 1, 0, n - 1); A.set(0, 0, 0.); LUDecomposition LU = A.lu(); try { check(A.getMatrix(LU.getPivot(), 0, n - 1), LU.getL().times(LU.getU())); try_success("LUDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "LUDecomposition...", "incorrect LU decomposition calculation"); } X = A.inverse(); try { check(A.times(X), Matrix.identity(3, 3)); try_success("inverse()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "inverse()...", "incorrect inverse calculation"); } O = new Matrix(SUB.getRowDimension(), 1, 1.0); SOL = new Matrix(sqSolution); SQ = SUB.getMatrix(0, SUB.getRowDimension() - 1, 0, SUB.getRowDimension() - 1); try { check(SQ.solve(SOL), O); try_success("solve()...", ""); } catch (java.lang.IllegalArgumentException e1) { errorCount = try_failure(errorCount, "solve()...", e1.getMessage()); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "solve()...", e.getMessage()); } A = new Matrix(pvals); CholeskyDecomposition Chol = A.chol(); Matrix L = Chol.getL(); try { check(A, L.times(L.transpose())); try_success("CholeskyDecomposition...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition...", "incorrect Cholesky decomposition calculation"); } X = Chol.solve(Matrix.identity(3, 3)); try { check(A.times(X), Matrix.identity(3, 3)); try_success("CholeskyDecomposition solve()...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "CholeskyDecomposition solve()...", "incorrect Choleskydecomposition solve calculation"); } EigenvalueDecomposition Eig = A.eig(); Matrix D = Eig.getD(); Matrix V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (symmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (symmetric)...", "incorrect symmetric Eigenvalue decomposition calculation"); } A = new Matrix(evals); Eig = A.eig(); D = Eig.getD(); V = Eig.getV(); try { check(A.times(V), V.times(D)); try_success("EigenvalueDecomposition (nonsymmetric)...", ""); } catch (java.lang.RuntimeException e) { errorCount = try_failure(errorCount, "EigenvalueDecomposition (nonsymmetric)...", "incorrect nonsymmetric Eigenvalue decomposition calculation"); } print("\nTestMatrix completed.\n"); print("Total errors reported: " + Integer.toString(errorCount) + "\n"); print("Total warnings reported: " + Integer.toString(warningCount) + "\n"); }
public static void copyFileByNIO(File in, File out) throws IOException { FileChannel sourceChannel = new FileInputStream(in).getChannel(); FileChannel destinationChannel = new FileOutputStream(out).getChannel(); sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); sourceChannel.close(); destinationChannel.close(); }
181
1
public static int zipFile(File file_input, File dir_output) { File zip_output = new File(dir_output, file_input.getName() + ".zip"); ZipOutputStream zip_out_stream; try { FileOutputStream out = new FileOutputStream(zip_output); zip_out_stream = new ZipOutputStream(new BufferedOutputStream(out)); } catch (IOException e) { return STATUS_OUT_FAIL; } byte[] input_buffer = new byte[BUF_SIZE]; int len = 0; try { ZipEntry zip_entry = new ZipEntry(file_input.getName()); zip_out_stream.putNextEntry(zip_entry); FileInputStream in = new FileInputStream(file_input); BufferedInputStream source = new BufferedInputStream(in, BUF_SIZE); while ((len = source.read(input_buffer, 0, BUF_SIZE)) != -1) zip_out_stream.write(input_buffer, 0, len); in.close(); } catch (IOException e) { return STATUS_ZIP_FAIL; } try { zip_out_stream.close(); } catch (IOException e) { } return STATUS_OK; }
public final void deliver(final String from, final String recipient, final InputStream data) throws TooMuchDataException, IOException { System.out.println("FROM: " + from); System.out.println("TO: " + recipient); final File tmpDir = new File(System.getProperty("java.io.tmpdir")); final File file = new File(tmpDir, recipient); final FileWriter fw = new FileWriter(file); try { IOUtils.copy(data, fw); } finally { fw.close(); } }
182
0
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); response.setContentType("text/html"); HttpSession session = request.getSession(); String session_id = session.getId(); File session_fileDir = new File(destinationDir + java.io.File.separator + session_id); session_fileDir.mkdir(); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); fileItemFactory.setSizeThreshold(1 * 1024 * 1024); fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); String pathToFile = new String(); try { List items = uploadHandler.parseRequest(request); Iterator itr = items.iterator(); while (itr.hasNext()) { FileItem item = (FileItem) itr.next(); if (item.isFormField()) { ; } else { pathToFile = getServletContext().getRealPath("/") + "files" + java.io.File.separator + session_id; File file = new File(pathToFile + java.io.File.separator + item.getName()); item.write(file); getContents(file, pathToFile); ComtorStandAlone.setMode(Mode.CLOUD); Comtor.start(pathToFile); } } try { File reportFile = new File(pathToFile + java.io.File.separator + "comtorReport.txt"); String reportURLString = AWSServices.storeReportS3(reportFile, session_id).toString(); if (reportURLString.startsWith("https")) reportURLString = reportURLString.replaceFirst("https", "http"); String requestURL = request.getRequestURL().toString(); String url = requestURL.substring(0, requestURL.lastIndexOf("/")); out.println("<html><head/><body>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/><hr/>"); Scanner scan = new Scanner(reportFile); out.println("<pre>"); while (scan.hasNextLine()) out.println(scan.nextLine()); out.println("</pre><hr/>"); out.println("<a href=\"" + url + "\">Return to home</a>&nbsp;&nbsp;"); out.println("<a href=\"" + reportURLString + "\">Report URL</a><br/>"); out.println("</body></html>"); } catch (Exception ex) { System.err.println(ex); } } catch (FileUploadException ex) { System.err.println("Error encountered while parsing the request" + ex); } catch (Exception ex) { System.err.println("Error encountered while uploading file" + ex); } }
@Override public HostRecord addressForHost(String domainName) throws Exception { String fullUrl = requestUrlStub + domainName; URL url = new URL(fullUrl); HttpURLConnection connection = null; connection = null; connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setReadTimeout(10000); connection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; HostRecord result = new HostRecord(domainName); byte parts[] = new byte[4]; while ((inputLine = in.readLine()) != null) { String pat1 = "<span class='orange'>"; String pat2 = "</span>"; int index1 = inputLine.indexOf(pat1); int index2 = inputLine.indexOf(pat2); if ((index1 > 0) && (index2 > 0)) { String ipStr = inputLine.substring(index1 + pat1.length(), index2); String[] s = ipStr.split("\\."); for (int i = 0; i < s.length; i++) parts[i] = (byte) Integer.parseInt(s[i]); } } IPAddress ipAddress = new IPAddress(parts); result.addIpAddress(ipAddress); in.close(); return result; }
183
0
public Program updateProgramPath(int id, String sourcePath) throws AdaptationException { Program program = null; Connection connection = null; Statement statement = null; ResultSet resultSet = null; try { String query = "UPDATE Programs SET " + "sourcePath = '" + sourcePath + "' " + "WHERE id = " + id; connection = DriverManager.getConnection(CONN_STR); statement = connection.createStatement(); statement.executeUpdate(query); query = "SELECT * from Programs WHERE id = " + id; resultSet = statement.executeQuery(query); if (!resultSet.next()) { connection.rollback(); String msg = "Attempt to update program failed."; log.error(msg); throw new AdaptationException(msg); } program = getProgram(resultSet); connection.commit(); } catch (SQLException ex) { try { connection.rollback(); } catch (Exception e) { } String msg = "SQLException in updateProgramPath"; log.error(msg, ex); throw new AdaptationException(msg, ex); } finally { try { resultSet.close(); } catch (Exception ex) { } try { statement.close(); } catch (Exception ex) { } try { connection.close(); } catch (Exception ex) { } } return program; }
public void fetchFile(String ID) { String url = "http://www.nal.usda.gov/cgi-bin/agricola-ind?bib=" + ID + "&conf=010000++++++++++++++&screen=MA"; System.out.println(url); try { PrintWriter pw = new PrintWriter(new FileWriter("MARC" + ID + ".txt")); if (!id.contains("MARC" + ID + ".txt")) { id.add("MARC" + ID + ".txt"); } in = new BufferedReader(new InputStreamReader((new URL(url)).openStream())); in.readLine(); String inputLine, stx = ""; StringBuffer sb = new StringBuffer(); while ((inputLine = in.readLine()) != null) { if (inputLine.startsWith("<TR><TD><B>")) { String sts = (inputLine.substring(inputLine.indexOf("B>") + 2, inputLine.indexOf("</"))); int i = 0; try { i = Integer.parseInt(sts); } catch (NumberFormatException nfe) { } if (i > 0) { stx = stx + "\n" + sts + " - "; } else { stx += sts; } } if (!(inputLine.startsWith("<") || inputLine.startsWith(" <") || inputLine.startsWith(">"))) { String tx = inputLine.trim(); stx += tx; } } pw.println(stx); pw.close(); } catch (Exception e) { System.out.println("Couldn't open stream"); System.out.println(e); } }
184
0
public String stringOfUrl(String addr) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(addr); IOUtils.copy(url.openStream(), output); return output.toString(); }
protected InputStream callApiMethod(String apiUrl, String xmlContent, String contentType, String method, int expected) { try { URL url = new URL(apiUrl); HttpURLConnection request = (HttpURLConnection) url.openConnection(); if (ApplicationConstants.CONNECT_TIMEOUT > -1) { request.setConnectTimeout(ApplicationConstants.CONNECT_TIMEOUT); } if (ApplicationConstants.READ_TIMEOUT > -1) { request.setReadTimeout(ApplicationConstants.READ_TIMEOUT); } for (String headerName : requestHeaders.keySet()) { request.setRequestProperty(headerName, requestHeaders.get(headerName)); } request.setRequestMethod(method); request.setDoOutput(true); if (contentType != null) { request.setRequestProperty("Content-Type", contentType); } if (xmlContent != null) { PrintStream out = new PrintStream(new BufferedOutputStream(request.getOutputStream())); out.print(xmlContent); out.flush(); out.close(); } request.connect(); if (request.getResponseCode() != expected) { throw new BingMapsException(convertStreamToString(request.getErrorStream())); } else { return getWrappedInputStream(request.getInputStream(), GZIP_ENCODING.equalsIgnoreCase(request.getContentEncoding())); } } catch (IOException e) { throw new BingMapsException(e); } }
185
1
public static void copy(File from, File to, CopyMode mode) throws IOException { if (!from.exists()) { IllegalArgumentException e = new IllegalArgumentException("Source doesn't exist: " + from.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (from.isFile()) { if (!to.canWrite()) { IllegalArgumentException e = new IllegalArgumentException("Cannot write to target location: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } } if (to.exists()) { if ((mode.val & CopyMode.OverwriteFile.val) != CopyMode.OverwriteFile.val) { IllegalArgumentException e = new IllegalArgumentException("Target already exists: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } if (to.isDirectory()) { if ((mode.val & CopyMode.OverwriteFolder.val) != CopyMode.OverwriteFolder.val) { IllegalArgumentException e = new IllegalArgumentException("Target is a folder: " + to.getCanonicalFile()); log.throwing("IOUtils", "copy", e); throw e; } else to.delete(); } } if (from.isFile()) { FileChannel in = new FileInputStream(from).getChannel(); FileLock inLock = in.lock(); FileChannel out = new FileOutputStream(to).getChannel(); FileLock outLock = out.lock(); try { in.transferTo(0, (int) in.size(), out); } finally { inLock.release(); outLock.release(); in.close(); out.close(); } } else { to.mkdirs(); File[] contents = to.listFiles(); for (File file : contents) { File newTo = new File(to.getCanonicalPath() + "/" + file.getName()); copy(file, newTo, mode); } } }
@Test public void testCopy_inputStreamToWriter_Encoding() throws Exception { InputStream in = new ByteArrayInputStream(inData); in = new YellOnCloseInputStreamTest(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); YellOnFlushAndCloseOutputStreamTest out = new YellOnFlushAndCloseOutputStreamTest(baout, true, true); Writer writer = new OutputStreamWriter(baout, "US-ASCII"); IOUtils.copy(in, writer, "UTF8"); out.off(); writer.flush(); assertTrue("Not all bytes were read", in.available() == 0); byte[] bytes = baout.toByteArray(); bytes = new String(bytes, "UTF8").getBytes("US-ASCII"); assertTrue("Content differs", Arrays.equals(inData, bytes)); }
186
1
public static void copia(File nombreFuente, File nombreDestino) throws IOException { FileInputStream fis = new FileInputStream(nombreFuente); FileOutputStream fos = new FileOutputStream(nombreDestino); FileChannel canalFuente = fis.getChannel(); FileChannel canalDestino = fos.getChannel(); canalFuente.transferTo(0, canalFuente.size(), canalDestino); fis.close(); fos.close(); }
public void updateFiles(String ourPath) { System.out.println("Update"); DataInputStream dis = null; DataOutputStream dos = null; for (int i = 0; i < newFiles.size() && i < nameNewFiles.size(); i++) { try { dis = new DataInputStream(new FileInputStream((String) newFiles.get(i))); dos = new DataOutputStream(new FileOutputStream((new StringBuilder(String.valueOf(ourPath))).append("\\").append((String) nameNewFiles.get(i)).toString())); } catch (IOException e) { System.out.println(e.toString()); System.exit(0); } try { do dos.writeChar(dis.readChar()); while (true); } catch (EOFException e) { } catch (IOException e) { System.out.println(e.toString()); } } }
187
0
private void insert() throws SQLException, NamingException { Logger logger = getLogger(); if (logger.isDebugEnabled()) { logger.debug("enter - " + getClass().getName() + ".insert()"); } try { if (logger.isInfoEnabled()) { logger.info("insert(): Create new sequencer record for " + getName()); } Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { InitialContext ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(dataSourceName); conn = ds.getConnection(); conn.setReadOnly(false); stmt = conn.prepareStatement(INSERT_SEQ); stmt.setString(INS_NAME, getName()); stmt.setLong(INS_NEXT_KEY, defaultInterval * 2); stmt.setLong(INS_INTERVAL, defaultInterval); stmt.setLong(INS_UPDATE, System.currentTimeMillis()); try { if (stmt.executeUpdate() != 1) { nextId = -1L; logger.warn("insert(): Failed to create sequencer entry for " + getName() + " (no error message)"); } else if (logger.isInfoEnabled()) { nextId = defaultInterval; nextSeed = defaultInterval * 2; interval = defaultInterval; logger.info("insert(): First ID will be " + nextId); } } catch (SQLException e) { logger.warn("insert(): Error inserting row into database, possible concurrency issue: " + e.getMessage()); if (logger.isDebugEnabled()) { e.printStackTrace(); } nextId = -1L; } if (!conn.getAutoCommit()) { conn.commit(); } } finally { if (rs != null) { try { rs.close(); } catch (SQLException ignore) { } } if (stmt != null) { try { stmt.close(); } catch (SQLException ignore) { } } if (conn != null) { if (!conn.getAutoCommit()) { try { conn.rollback(); } catch (SQLException ignore) { } } try { conn.close(); } catch (SQLException ignore) { } } } } finally { if (logger.isDebugEnabled()) { logger.debug("exit - " + getClass().getName() + ".insert()"); } } }
protected ProductionTabsProperties(final PlayerID playerId, final List<Rule> mRules, final String mapDir) { m_rules = mRules; final ResourceLoader loader = ResourceLoader.getMapResourceLoader(mapDir); String propertyFile = PROPERTY_FILE + "." + playerId.getName() + ".properties"; URL url = loader.getResource(propertyFile); if (url == null) { propertyFile = PROPERTY_FILE + ".properties"; url = loader.getResource(propertyFile); if (url == null) { } else { try { m_properties.load(url.openStream()); } catch (final IOException e) { System.out.println("Error reading " + propertyFile + e); } } } }
188
0
public static boolean checkEncode(String origin, byte[] mDigest, String algorithm) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(origin.getBytes()); if (MessageDigest.isEqual(mDigest, md.digest())) { return true; } else { return false; } }
public String output(final ComponentParameter compParameter) { InputStream inputStream; try { final URL url = new URL("http://xml.weather.yahoo.com/forecastrss?p=" + getPagelet().getOptionProperty("_weather_code") + "&u=c"); inputStream = url.openStream(); } catch (final IOException e) { return e.getMessage(); } final StringBuilder sb = new StringBuilder(); new AbstractXmlDocument(inputStream) { @Override protected void init() throws Exception { final Element root = getRoot(); final Namespace ns = root.getNamespaceForPrefix("yweather"); final Element channel = root.element("channel"); final String link = channel.elementText("link"); final Element item = channel.element("item"); Element ele = item.element(QName.get("condition", ns)); if (ele == null) { sb.append("ERROR"); return; } final String imgPath = getPagelet().getColumnBean().getPortalBean().getCssResourceHomePath(compParameter) + "/images/yahoo/"; String text, image; Date date = new SimpleDateFormat(YahooWeatherUtils.RFC822_MASKS[1], Locale.US).parse(ele.attributeValue("date")); final int temp = Integer.parseInt(ele.attributeValue("temp")); int code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append("<div style=\"line-height: normal;\"><a target=\"_blank\" href=\"").append(link).append("\"><img src=\""); sb.append(image).append("\" /></a>"); sb.append(YahooWeatherUtils.formatHour(date)).append(" - "); sb.append(text).append(" - ").append(temp).append("℃").append("<br>"); final Iterator<?> it = item.elementIterator(QName.get("forecast", ns)); while (it.hasNext()) { ele = (Element) it.next(); date = new SimpleDateFormat("dd MMM yyyy", Locale.US).parse(ele.attributeValue("date")); final int low = Integer.parseInt(ele.attributeValue("low")); final int high = Integer.parseInt(ele.attributeValue("high")); code = Integer.valueOf(ele.attributeValue("code")).intValue(); if (code == 3200) { text = YahooWeatherUtils.yahooTexts[YahooWeatherUtils.yahooTexts.length - 1]; image = imgPath + "3200.gif"; } else { text = YahooWeatherUtils.yahooTexts[code]; image = imgPath + code + ".gif"; } sb.append(YahooWeatherUtils.formatWeek(date)).append(" ( "); sb.append(text).append(". "); sb.append(low).append("℃~").append(high).append("℃"); sb.append(" )<br>"); } sb.append("</div>"); } }; return sb.toString(); }
189
0
@Override public void run() { try { long pos = begin; byte[] buf = new byte[1024]; URLConnection cn = url.openConnection(); Utils.setHeader(cn); cn.setRequestProperty("Range", "bytes=" + begin + "-" + end); BufferedInputStream bis = new BufferedInputStream(cn.getInputStream()); int len; while ((len = bis.read(buf)) > 0) { synchronized (file) { file.seek(pos); file.write(buf, 0, len); } pos += len; Statics.getInstance().addComleted(len); } } catch (Exception e) { e.printStackTrace(); } latch.countDown(); }
@Override public void copy(final String fileName) throws FileIOException { final long savedCurrentPositionInFile = currentPositionInFile; if (opened) { closeImpl(); } final FileInputStream fis; try { fis = new FileInputStream(file); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + file, file, exception); } final File destinationFile = new File(fileName); final FileOutputStream fos; try { fos = new FileOutputStream(destinationFile); } catch (FileNotFoundException exception) { throw HELPER_FILE_UTIL.fileIOException(FAILED_OPEN + destinationFile, destinationFile, exception); } try { final byte[] buf = new byte[1024]; int readLength = 0; while ((readLength = fis.read(buf)) != -1) { fos.write(buf, 0, readLength); } } catch (IOException exception) { throw HELPER_FILE_UTIL.fileIOException("failed copy from " + file + " to " + destinationFile, null, exception); } finally { try { if (fis != null) { fis.close(); } } catch (Exception exception) { } try { if (fos != null) { fos.close(); } } catch (Exception exception) { } } if (opened) { openImpl(); seek(savedCurrentPositionInFile); } }
190
0
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 void add(Channel channel) throws Exception { String sqlStr = null; DBOperation dbo = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { sqlStr = "insert into t_ip_channel (id,name,description,ascii_name,channel_path,site_id,type,data_url,template_id,use_status,order_no,style,creator,create_date,refresh_flag,page_num) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; dbo = createDBOperation(); connection = dbo.getConnection(); connection.setAutoCommit(false); String[] path = new String[1]; path[0] = channel.getPath(); selfDefineAdd(path, channel, connection, preparedStatement); preparedStatement = connection.prepareStatement(sqlStr); preparedStatement.setInt(1, channel.getChannelID()); preparedStatement.setString(2, channel.getName()); preparedStatement.setString(3, channel.getDescription()); preparedStatement.setString(4, channel.getAsciiName()); preparedStatement.setString(5, channel.getPath()); preparedStatement.setInt(6, channel.getSiteId()); preparedStatement.setString(7, channel.getChannelType()); preparedStatement.setString(8, channel.getDataUrl()); if (channel.getTemplateId() == null || channel.getTemplateId().trim().equals("")) preparedStatement.setNull(9, Types.INTEGER); else preparedStatement.setInt(9, Integer.parseInt(channel.getTemplateId())); preparedStatement.setString(10, channel.getUseStatus()); preparedStatement.setInt(11, channel.getOrderNo()); preparedStatement.setString(12, channel.getStyle()); preparedStatement.setInt(13, channel.getCreator()); preparedStatement.setTimestamp(14, (Timestamp) channel.getCreateDate()); preparedStatement.setString(15, channel.getRefPath()); preparedStatement.setInt(16, channel.getPageNum()); preparedStatement.executeUpdate(); connection.commit(); int operateTypeID = Const.OPERATE_TYPE_ID; int resID = channel.getChannelID() + Const.CHANNEL_TYPE_RES; String resName = channel.getName(); int resTypeID = Const.RES_TYPE_ID; String remark = ""; AuthorityManager am = new AuthorityManager(); am.createExtResource(Integer.toString(resID), resName, resTypeID, operateTypeID, remark); } catch (SQLException ex) { connection.rollback(); log.error("���Ƶ��ʱSql�쳣��ִ����䣺" + sqlStr); throw ex; } finally { close(resultSet, null, preparedStatement, connection, dbo); } }
191
0
public RFC1345List(URL url) { if (url == null) return; try { BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(url.openStream()))); final String linePattern = " XX??????? HHHH X"; String line; mnemos = new HashMap(); nextline: while ((line = br.readLine()) != null) { if (line.length() < 9) continue nextline; if (line.charAt(7) == ' ' || line.charAt(8) != ' ') { line = line.substring(0, 8) + " " + line.substring(8); } if (line.length() < linePattern.length()) continue nextline; for (int i = 0; i < linePattern.length(); i++) { char c = line.charAt(i); switch(linePattern.charAt(i)) { case ' ': if (c != ' ') continue nextline; break; case 'X': if (c == ' ') continue nextline; break; case '?': break; case 'H': if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) ; else continue nextline; break; default: throw new RuntimeException("Pattern broken!"); } } char c = (char) Integer.parseInt(line.substring(16, 20), 16); String mnemo = line.substring(1, 16).trim(); if (mnemo.length() < 2) throw new RuntimeException(); mnemos.put(mnemo, new Character(c)); } br.close(); } catch (FileNotFoundException ex) { } catch (IOException ex) { ex.printStackTrace(); } }
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); } }
192
1
public void actionPerformed(ActionEvent e) { if (path.compareTo("") != 0) { imageName = (path.substring(path.lastIndexOf(File.separator) + 1, path.length())); String name = imageName.substring(0, imageName.lastIndexOf('.')); String extension = imageName.substring(imageName.lastIndexOf('.') + 1, imageName.length()); File imageFile = new File(path); directoryPath = "images" + File.separator + imageName.substring(0, 1).toUpperCase(); File directory = new File(directoryPath); directory.mkdirs(); imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName; File newFile = new File(imagePath); if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.REPLACE_IMAGE"))) { Vector<Vector<String>> aux = TIGDataBase.imageSearchByName(name); if (aux.size() != 0) { int idImage = TIGDataBase.imageKeySearchName(name); TIGDataBase.deleteAsociatedOfImage(idImage); } } if (myImagesBehaviour.equals(TLanguage.getString("TIGManageGalleryDialog.ADD_IMAGE"))) { int i = 1; while (newFile.exists()) { imagePath = "." + File.separator + "images" + File.separator + imageName.substring(0, 1).toUpperCase() + File.separator + imageName.substring(0, imageName.lastIndexOf('.')) + "_" + i + imageName.substring(imageName.lastIndexOf('.'), imageName.length()); name = name + "_" + i; newFile = new File(imagePath); i++; } } imagePathThumb = (imagePath.substring(0, imagePath.lastIndexOf("."))).concat("_th.jpg"); imageName = name + "." + extension; try { FileChannel srcChannel = new FileInputStream(path).getChannel(); FileChannel dstChannel = new FileOutputStream(imagePath).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); } catch (IOException exc) { System.out.println(exc.getMessage()); System.out.println(exc.toString()); } TIGDataBase.insertDB(theConcepts, imageName, imageName.substring(0, imageName.lastIndexOf('.'))); image = null; if (imageFile != null) { if (TFileUtils.isJAIRequired(imageFile)) { RenderedOp src = JAI.create("fileload", imageFile.getAbsolutePath()); BufferedImage bufferedImage = src.getAsBufferedImage(); image = new ImageIcon(bufferedImage); } else { image = new ImageIcon(imageFile.getAbsolutePath()); } if (image.getImageLoadStatus() == MediaTracker.ERRORED) { int choosenOption = JOptionPane.NO_OPTION; choosenOption = JOptionPane.showConfirmDialog(null, TLanguage.getString("TIGInsertImageAction.MESSAGE"), TLanguage.getString("TIGInsertImageAction.NAME"), JOptionPane.CLOSED_OPTION, JOptionPane.ERROR_MESSAGE); } else { createThumbnail(); } } } }
public static boolean copyFile(File sourceFile, File destFile) { FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(sourceFile).getChannel(); dstChannel = new FileOutputStream(destFile).getChannel(); long pos = 0; long count = srcChannel.size(); if (count > MAX_BLOCK_SIZE) { count = MAX_BLOCK_SIZE; } long transferred = Long.MAX_VALUE; while (transferred > 0) { transferred = dstChannel.transferFrom(srcChannel, pos, count); pos = transferred; } } catch (IOException e) { return false; } finally { if (srcChannel != null) { try { srcChannel.close(); } catch (IOException e) { } } if (dstChannel != null) { try { dstChannel.close(); } catch (IOException e) { } } } return true; }
193
1
public AssessmentItemType getAssessmentItemType(String filename) { if (filename.contains(" ") && (System.getProperty("os.name").contains("Windows"))) { File source = new File(filename); String tempDir = System.getenv("TEMP"); File dest = new File(tempDir + "/temp.xml"); MQMain.logger.info("Importing from " + dest.getAbsolutePath()); FileChannel in = null, out = null; try { in = new FileInputStream(source).getChannel(); out = new FileOutputStream(dest).getChannel(); long size = in.size(); MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size); out.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) try { in.close(); } catch (IOException e) { e.printStackTrace(); } if (out != null) try { out.close(); } catch (IOException e) { e.printStackTrace(); } filename = tempDir + "/temp.xml"; } } AssessmentItemType assessmentItemType = null; JAXBElement<?> jaxbe = null; try { XMLReader reader = XMLReaderFactory.createXMLReader(); ChangeNamespace convertfromv2p0tov2p1 = new ChangeNamespace(reader, "http://www.imsglobal.org/xsd/imsqti_v2p0", "http://www.imsglobal.org/xsd/imsqti_v2p1"); SAXSource source = null; try { FileInputStream fis = new FileInputStream(filename); InputStreamReader isr = null; try { isr = new InputStreamReader(fis, "UTF-8"); } catch (UnsupportedEncodingException e) { } InputSource is = new InputSource(isr); source = new SAXSource(convertfromv2p0tov2p1, is); } catch (FileNotFoundException e) { MQMain.logger.error("SAX/getAssessmentItemType/file not found"); } jaxbe = (JAXBElement<?>) MQModel.qtiCf.unmarshal(MQModel.imsqtiUnmarshaller, source); assessmentItemType = (AssessmentItemType) jaxbe.getValue(); } catch (JAXBException e) { MQMain.logger.error("JAX/getAssessmentItemType", e); } catch (SAXException e) { MQMain.logger.error("SAX/getAssessmentItemType", e); } return assessmentItemType; }
public Object execute(ExecutionEvent event) throws ExecutionException { final List<InformationUnit> informationUnitsFromExecutionEvent = InformationHandlerUtil.getInformationUnitsFromExecutionEvent(event); Shell activeShell = HandlerUtil.getActiveShell(event); DirectoryDialog fd = new DirectoryDialog(activeShell, SWT.SAVE); String section = Activator.getDefault().getDialogSettings().get("lastExportSection"); fd.setFilterPath(section); final String open = fd.open(); if (open != null) { Activator.getDefault().getDialogSettings().put("lastExportSection", open); CancelableRunnable runnable = new CancelableRunnable() { @Override protected IStatus runCancelableRunnable(IProgressMonitor monitor) { IStatus returnValue = Status.OK_STATUS; monitor.beginTask(NLS.bind(Messages.SaveFileOnDiskHandler_SavingFiles, open), informationUnitsFromExecutionEvent.size()); for (InformationUnit informationUnit : informationUnitsFromExecutionEvent) { if (!monitor.isCanceled()) { monitor.setTaskName(NLS.bind(Messages.SaveFileOnDiskHandler_Saving, informationUnit.getLabel())); InformationStructureRead read = InformationStructureRead.newSession(informationUnit); read.getValueByNodeId(Activator.FILENAME); IFile binaryReferenceFile = InformationUtil.getBinaryReferenceFile(informationUnit); FileWriter writer = null; try { if (binaryReferenceFile != null) { File file = new File(open, (String) read.getValueByNodeId(Activator.FILENAME)); InputStream contents = binaryReferenceFile.getContents(); writer = new FileWriter(file); IOUtils.copy(contents, writer); monitor.worked(1); } } catch (Exception e) { returnValue = StatusCreator.newStatus(NLS.bind(Messages.SaveFileOnDiskHandler_ErrorSaving, informationUnit.getLabel(), e)); break; } finally { if (writer != null) { try { writer.flush(); writer.close(); } catch (IOException e) { } } } } } return returnValue; } }; ProgressMonitorDialog progressMonitorDialog = new ProgressMonitorDialog(activeShell); try { progressMonitorDialog.run(true, true, runnable); } catch (InvocationTargetException e) { if (e.getCause() instanceof CoreException) { ErrorDialog.openError(activeShell, Messages.SaveFileOnDiskHandler_ErrorSaving2, Messages.SaveFileOnDiskHandler_ErrorSaving2, ((CoreException) e.getCause()).getStatus()); } else { ErrorDialog.openError(activeShell, Messages.SaveFileOnDiskHandler_ErrorSaving2, Messages.SaveFileOnDiskHandler_ErrorSaving2, StatusCreator.newStatus(Messages.SaveFileOnDiskHandler_ErrorSaving3, e)); } } catch (InterruptedException e) { } } return null; }
194
1
protected void doRestoreOrganizeType() throws Exception { Connection con = null; PreparedStatement ps = null; ResultSet result = null; String strDelQuery = "DELETE FROM " + Common.ORGANIZE_TYPE_TABLE; String strSelQuery = "SELECT organize_type_id,organize_type_name,width " + "FROM " + Common.ORGANIZE_TYPE_B_TABLE + " " + "WHERE version_no = ?"; String strInsQuery = "INSERT INTO " + Common.ORGANIZE_TYPE_TABLE + " " + "(organize_type_id,organize_type_name,width) " + "VALUES (?,?,?)"; DBOperation dbo = factory.createDBOperation(POOL_NAME); try { try { con = dbo.getConnection(); con.setAutoCommit(false); ps = con.prepareStatement(strDelQuery); ps.executeUpdate(); ps = con.prepareStatement(strSelQuery); ps.setInt(1, this.versionNO); result = ps.executeQuery(); ps = con.prepareStatement(strInsQuery); while (result.next()) { ps.setString(1, result.getString("organize_type_id")); ps.setString(2, result.getString("organize_type_name")); ps.setInt(3, result.getInt("width")); int resultCount = ps.executeUpdate(); if (resultCount != 1) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): ERROR Inserting data " + "in T_SYS_ORGANIZE_TYPE INSERT !! resultCount = " + resultCount); } } con.commit(); } catch (SQLException se) { con.rollback(); throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): SQLException: " + se); } finally { con.setAutoCommit(true); close(dbo, ps, result); } } catch (SQLException se) { throw new CesSystemException("Organize_backup.doRestoreOrganizeType(): SQLException while committing or rollback"); } }
public static String deleteTag(String tag_id) { String so = OctopusErrorMessages.UNKNOWN_ERROR; if (tag_id == null || tag_id.trim().equals("")) { return OctopusErrorMessages.TAG_ID_CANT_BE_EMPTY; } DBConnection theConnection = null; try { theConnection = DBServiceManager.allocateConnection(); theConnection.setAutoCommit(false); String query = "DELETE FROM tr_translation WHERE tr_translation_trtagid=?"; PreparedStatement state = theConnection.prepareStatement(query); state.setString(1, tag_id); state.executeUpdate(); String query2 = "DELETE FROM tr_tag WHERE tr_tag_id=? "; PreparedStatement state2 = theConnection.prepareStatement(query2); state2.setString(1, tag_id); state2.executeUpdate(); theConnection.commit(); so = OctopusErrorMessages.ACTION_DONE; } catch (SQLException e) { try { theConnection.rollback(); } catch (SQLException ex) { } so = OctopusErrorMessages.ERROR_DATABASE; } finally { if (theConnection != null) { try { theConnection.setAutoCommit(true); } catch (SQLException ex) { } theConnection.release(); } } return so; }
195
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 int deleteSysPosInsert() { Connection conn = null; PreparedStatement psmt = null; StringBuffer SQL = new StringBuffer(200); int deleted = 0; SQL.append(" DELETE FROM JHF_SYS_POSITION_INSERT "); try { conn = JdbcConnectionPool.mainConnection(); conn.setAutoCommit(false); conn.setReadOnly(false); psmt = conn.prepareStatement(SQL.toString()); deleted = psmt.executeUpdate(); conn.commit(); } catch (SQLException e) { if (null != conn) { try { conn.rollback(); } catch (SQLException e1) { System.out.println(" error when roll back !"); } } } finally { try { if (null != psmt) { psmt.close(); psmt = null; } if (null != conn) { conn.close(); conn = null; } } catch (SQLException e) { System.out.println(" error when psmt close or conn close ."); } } return deleted; }
196
0
public AbstractASiCSignatureService(InputStream documentInputStream, DigestAlgo digestAlgo, RevocationDataService revocationDataService, TimeStampService timeStampService, String claimedRole, IdentityDTO identity, byte[] photo, TemporaryDataStorage temporaryDataStorage, OutputStream documentOutputStream) throws IOException { super(digestAlgo); this.temporaryDataStorage = temporaryDataStorage; this.documentOutputStream = documentOutputStream; this.tmpFile = File.createTempFile("eid-dss-", ".asice"); FileOutputStream fileOutputStream; fileOutputStream = new FileOutputStream(this.tmpFile); IOUtils.copy(documentInputStream, fileOutputStream); addSignatureFacet(new ASiCSignatureFacet(this.tmpFile, digestAlgo)); XAdESSignatureFacet xadesSignatureFacet = new XAdESSignatureFacet(getSignatureDigestAlgorithm()); xadesSignatureFacet.setRole(claimedRole); xadesSignatureFacet.setXadesNamespacePrefix("xades"); addSignatureFacet(xadesSignatureFacet); addSignatureFacet(new XAdESXLSignatureFacet(timeStampService, revocationDataService, getSignatureDigestAlgorithm())); addSignatureFacet(new KeyInfoSignatureFacet(true, false, false)); if (null != identity) { IdentitySignatureFacet identitySignatureFacet = new IdentitySignatureFacet(identity, photo, getSignatureDigestAlgorithm()); addSignatureFacet(identitySignatureFacet); } }
public static String[] parsePLS(String strURL, Context c) { URL url; URLConnection urlConn = null; String TAG = "parsePLS"; Vector<String> radio = new Vector<String>(); final String filetoken = "file"; final String SPLITTER = "="; try { url = new URL(strURL); urlConn = url.openConnection(); Log.d(TAG, "Got data"); } catch (IOException ioe) { Log.e(TAG, "Could not connect to " + strURL); } try { DataInputStream in = new DataInputStream(urlConn.getInputStream()); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; while ((strLine = br.readLine()) != null) { String temp = strLine.toLowerCase(); Log.d(TAG, strLine); if (temp.startsWith(filetoken)) { String[] s = Pattern.compile(SPLITTER).split(temp); radio.add(s[1]); Log.d(TAG, "Found audio " + s[1]); } } br.close(); in.close(); } catch (Exception e) { Log.e(TAG, "Trouble reading file: " + e.getMessage()); } String[] t = new String[0]; String[] r = null; if (radio.size() != 0) { r = (String[]) radio.toArray(t); Log.d(TAG, "Found total: " + String.valueOf(r.length)); } return r; }
197
0
private void updateUser(AddEditUserForm addform, HttpServletRequest request) throws Exception { Session hbsession = HibernateUtil.currentSession(); try { Transaction tx = hbsession.beginTransaction(); NvUsers user = (NvUsers) hbsession.load(NvUsers.class, addform.getLogin()); if (!addform.getPassword().equalsIgnoreCase("")) { MessageDigest md = (MessageDigest) MessageDigest.getInstance("MD5").clone(); md.update(addform.getPassword().getBytes("UTF-8")); byte[] pd = md.digest(); StringBuffer app = new StringBuffer(); for (int i = 0; i < pd.length; i++) { String s2 = Integer.toHexString(pd[i] & 0xFF); app.append((s2.length() == 1) ? "0" + s2 : s2); } user.setPassword(app.toString()); } ActionErrors errors = new ActionErrors(); HashMap cAttrs = addform.getCustomAttrs(); Query q1 = hbsession.createQuery("from org.nodevision.portal.hibernate.om.NvCustomAttrs as a"); Iterator attrs = q1.iterate(); HashMap attrInfos = new HashMap(); while (attrs.hasNext()) { NvCustomAttrs element = (NvCustomAttrs) attrs.next(); attrInfos.put(element.getAttrName(), element.getAttrType()); NvCustomValuesId id = new NvCustomValuesId(); id.setNvUsers(user); NvCustomValues value = new NvCustomValues(); id.setNvCustomAttrs(element); value.setId(id); if (element.getAttrType().equalsIgnoreCase("String")) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(cAttrs.get(element.getAttrName()).toString()); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } else if (element.getAttrType().equalsIgnoreCase("Boolean")) { Boolean valueBoolean = Boolean.FALSE; if (cAttrs.get(element.getAttrName()) != null) { valueBoolean = Boolean.TRUE; } ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(valueBoolean); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } else if (element.getAttrType().equalsIgnoreCase("Date")) { Date date = new Date(0); if (!cAttrs.get(element.getAttrName()).toString().equalsIgnoreCase("")) { String bdate = cAttrs.get(element.getAttrName()).toString(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); date = df.parse(bdate); } ByteArrayOutputStream bout = new ByteArrayOutputStream(); ObjectOutputStream serializer = new ObjectOutputStream(bout); serializer.writeObject(date); value.setAttrValue(Hibernate.createBlob(bout.toByteArray())); } hbsession.saveOrUpdate(value); hbsession.flush(); } String bdate = addform.getUser_bdate(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); Date parsedDate = df.parse(bdate); user.setTimezone(addform.getTimezone()); user.setLocale(addform.getLocale()); user.setBdate(new BigDecimal(parsedDate.getTime())); user.setGender(addform.getUser_gender()); user.setEmployer(addform.getEmployer()); user.setDepartment(addform.getDepartment()); user.setJobtitle(addform.getJobtitle()); user.setNamePrefix(addform.getName_prefix()); user.setNameGiven(addform.getName_given()); user.setNameFamily(addform.getName_famliy()); user.setNameMiddle(addform.getName_middle()); user.setNameSuffix(addform.getName_suffix()); user.setHomeName(addform.getHome_name()); user.setHomeStreet(addform.getHome_street()); user.setHomeStateprov(addform.getHome_stateprov()); user.setHomePostalcode(addform.getHome_postalcode().equalsIgnoreCase("") ? new Integer(0) : new Integer(addform.getHome_postalcode())); user.setHomeOrganization(addform.getHome_organization_name()); user.setHomeCountry(addform.getHome_country()); user.setHomeCity(addform.getHome_city()); user.setHomePhoneIntcode((addform.getHome_phone_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_intcode())); user.setHomePhoneLoccode((addform.getHome_phone_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_loccode())); user.setHomePhoneNumber((addform.getHome_phone_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_number())); user.setHomePhoneExt((addform.getHome_phone_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_phone_ext())); user.setHomePhoneComment(addform.getHome_phone_commment()); user.setHomeFaxIntcode((addform.getHome_fax_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_intcode())); user.setHomeFaxLoccode((addform.getHome_fax_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_loccode())); user.setHomeFaxNumber((addform.getHome_fax_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_number())); user.setHomeFaxExt((addform.getHome_fax_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_fax_ext())); user.setHomeFaxComment(addform.getHome_fax_commment()); user.setHomeMobileIntcode((addform.getHome_mobile_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_intcode())); user.setHomeMobileLoccode((addform.getHome_mobile_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_loccode())); user.setHomeMobileNumber((addform.getHome_mobile_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_number())); user.setHomeMobileExt((addform.getHome_mobile_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_mobile_ext())); user.setHomeMobileComment(addform.getHome_mobile_commment()); user.setHomePagerIntcode((addform.getHome_pager_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_intcode())); user.setHomePagerLoccode((addform.getHome_pager_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_loccode())); user.setHomePagerNumber((addform.getHome_pager_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_number())); user.setHomePagerExt((addform.getHome_pager_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getHome_pager_ext())); user.setHomePagerComment(addform.getHome_pager_commment()); user.setHomeUri(addform.getHome_uri()); user.setHomeEmail(addform.getHome_email()); user.setBusinessName(addform.getBusiness_name()); user.setBusinessStreet(addform.getBusiness_street()); user.setBusinessStateprov(addform.getBusiness_stateprov()); user.setBusinessPostalcode((addform.getBusiness_postalcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_postalcode())); user.setBusinessOrganization(addform.getBusiness_organization_name()); user.setBusinessCountry(addform.getBusiness_country()); user.setBusinessCity(addform.getBusiness_city()); user.setBusinessPhoneIntcode((addform.getBusiness_phone_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_intcode())); user.setBusinessPhoneLoccode((addform.getBusiness_phone_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_loccode())); user.setBusinessPhoneNumber((addform.getBusiness_phone_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_number())); user.setBusinessPhoneExt((addform.getBusiness_phone_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_phone_ext())); user.setBusinessPhoneComment(addform.getBusiness_phone_commment()); user.setBusinessFaxIntcode((addform.getBusiness_fax_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_intcode())); user.setBusinessFaxLoccode((addform.getBusiness_fax_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_loccode())); user.setBusinessFaxNumber((addform.getBusiness_fax_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_number())); user.setBusinessFaxExt((addform.getBusiness_fax_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_fax_ext())); user.setBusinessFaxComment(addform.getBusiness_fax_commment()); user.setBusinessMobileIntcode((addform.getBusiness_mobile_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_intcode())); user.setBusinessMobileLoccode((addform.getBusiness_mobile_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_loccode())); user.setBusinessMobileNumber((addform.getBusiness_mobile_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_number())); user.setBusinessMobileExt((addform.getBusiness_mobile_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_mobile_ext())); user.setBusinessMobileComment(addform.getBusiness_mobile_commment()); user.setBusinessPagerIntcode((addform.getBusiness_pager_intcode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_intcode())); user.setBusinessPagerLoccode((addform.getBusiness_pager_loccode().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_loccode())); user.setBusinessPagerNumber((addform.getBusiness_pager_number().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_number())); user.setBusinessPagerExt((addform.getBusiness_pager_ext().equalsIgnoreCase("")) ? new Integer(0) : Integer.valueOf(addform.getBusiness_pager_ext())); user.setBusinessPagerComment(addform.getBusiness_pager_commment()); user.setBusinessUri(addform.getBusiness_uri()); user.setBusinessEmail(addform.getBusiness_email()); String hqlDelete = "delete org.nodevision.portal.hibernate.om.NvUserRoles where login = :login"; int deletedEntities = hbsession.createQuery(hqlDelete).setString("login", user.getLogin()).executeUpdate(); String[] selectedGroups = addform.getSelectedGroups(); Set newGroups = new HashSet(); for (int i = 0; i < selectedGroups.length; i++) { NvUserRolesId userroles = new NvUserRolesId(); userroles.setNvUsers(user); userroles.setNvRoles((NvRoles) hbsession.load(NvRoles.class, selectedGroups[i])); NvUserRoles newRole = new NvUserRoles(); newRole.setId(userroles); newGroups.add(newRole); } user.setSetOfNvUserRoles(newGroups); hbsession.update(user); hbsession.flush(); if (!hbsession.connection().getAutoCommit()) { tx.commit(); } } finally { HibernateUtil.closeSession(); } }
private String clientLogin(AuthInfo authInfo) throws AuthoricationRequiredException { logger.fine("clientLogin."); try { String url = "https://www.google.com/accounts/ClientLogin"; HttpPost httpPost = new HttpPost(url); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("accountType", "HOSTED_OR_GOOGLE")); params.add(new BasicNameValuePair("Email", authInfo.getEmail())); params.add(new BasicNameValuePair("Passwd", new String(authInfo.getPassword()))); params.add(new BasicNameValuePair("service", "ah")); params.add(new BasicNameValuePair("source", "client.kotan-server.appspot.com")); httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = clientManager.httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { entity.consumeContent(); throw new AuthoricationRequiredException(EntityUtils.toString(entity)); } BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent())); while (true) { String line = reader.readLine(); if (line == null) break; if (line.startsWith("Auth=")) { return line.substring("Auth=".length()); } } reader.close(); throw new AuthoricationRequiredException("Login failure."); } catch (IOException e) { throw new AuthoricationRequiredException(e); } }
198
1
public static String getDigest(String seed, String code) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(seed.getBytes("UTF-8")); byte[] passwordMD5Byte = md.digest(code.getBytes("UTF-8")); StringBuffer sb = new StringBuffer(); for (int i = 0; i < passwordMD5Byte.length; i++) sb.append(Integer.toHexString(passwordMD5Byte[i] & 0XFF)); return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.error(e); return null; } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e); return null; } }
@SuppressWarnings("unused") private String getMD5(String value) { MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { return ""; } md5.reset(); md5.update(value.getBytes()); byte[] messageDigest = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } String hashedPassword = hexString.toString(); return hashedPassword; }
199