List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java
/** * Wrap a basic HttpClient object in a Fedora SSL enabled HttpClient (which includes * Fedora SSL authentication cert) object. * // w ww .j a v a 2s . c om * @param base The HttpClient to wrap. * @return The SSL wrapped HttpClient. * @throws GeneralSecurityException * @throws IOException */ private HttpClient fedoraSslEnable(HttpClient base) throws GeneralSecurityException, FileNotFoundException, IOException { // Get a SSL related instance for setting up SSL connections. FedoraSSL fedoraSSL = FedoraSSLFactory.getInstance(); SSLSocketFactory sf = new SSLSocketFactory(fedoraSSL.getInitializedSSLContext(), // may throw FileNotFoundE SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$ sr.register(https); return new DefaultHttpClient(ccm, base.getParams()); }
From source file:com.strato.hidrive.api.connection.httpgateway.HTTPGateway.java
/** * wrap an httpclient with this stub for prevent ssl unverified exceptions (for testing purposes) *///from ww w. j av a2s. c om public DefaultHttpClient sslStubClient(HttpClient client) { try { X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new StubSSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = client.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, client.getParams()); } catch (Exception ex) { return null; } }
From source file:duthientan.mmanm.com.Main.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: try {/*w ww . j a va 2s . c om*/ HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpGet httpGet = new HttpGet("http://localhost:4000/api/store"); httpGet.setHeader("id", id); httpGet.addHeader("x-access-token", token); HttpResponse response = httpclient.execute(httpGet); JSONObject obj = new JSONObject(EntityUtils.toString(response.getEntity())); //System.out.println(EntityUtils.toString(response.getEntity())); JSONArray jsonArr = obj.getJSONArray("arr"); String result = ""; for (int i = 0; i < jsonArr.length(); i++) { result += "http://localhost:4000/" + jsonArr.get(i).toString() + "\n"; } textLinkFile.setText(result); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:duthientan.mmanm.com.Main.java
private void btnUploadFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUploadFileActionPerformed // TODO add your handling code here: if (!fileUploadPath.equals("")) { progressBarCipher.setIndeterminate(true); new Thread(new Runnable() { @Override/*ww w . j a v a 2s . c om*/ public void run() { try { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost("http://localhost:4000/api/upload"); File file = new File(fileUploadPath); MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file); mpEntity.addPart("files", cbFile); httppost.addHeader("id", id); httppost.addHeader("x-access-token", token); httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); progressBarCipher.setIndeterminate(false); JFrame frame = new JFrame("Upload Completed"); JOptionPane.showMessageDialog(frame, "File Uploaded"); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } }).start(); } else { JFrame frame = new JFrame("File not Found"); JOptionPane.showMessageDialog(frame, "Plase Choice File Upload"); } }
From source file:org.jvoicexml.documentserver.schemestrategy.HttpSchemeStrategy.java
/** * {@inheritDoc}/* ww w.j a v a 2 s . c o m*/ */ @Override public InputStream getInputStream(final String sessionId, final URI uri, final RequestMethod method, final long timeout, final Collection<KeyValuePair> parameters) throws BadFetchError { final HttpClient client = SESSION_STORAGE.getSessionIdentifier(sessionId); final URI fullUri; try { final URI fragmentLessUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), uri.getQuery(), null); fullUri = addParameters(parameters, fragmentLessUri); } catch (URISyntaxException e) { throw new BadFetchError(e.getMessage(), e); } catch (SemanticError e) { throw new BadFetchError(e.getMessage(), e); } final String url = fullUri.toString(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("connecting to '" + url + "'..."); } final HttpUriRequest request; if (method == RequestMethod.GET) { request = new HttpGet(url); } else { request = new HttpPost(url); } attachFiles(request, parameters); try { final HttpParams params = client.getParams(); setTimeout(timeout, params); final HttpResponse response = client.execute(request); final StatusLine statusLine = response.getStatusLine(); final int status = statusLine.getStatusCode(); if (status != HttpStatus.SC_OK) { throw new BadFetchError(statusLine.getReasonPhrase() + " (HTTP error code " + status + ")"); } final HttpEntity entity = response.getEntity(); return entity.getContent(); } catch (IOException e) { throw new BadFetchError(e.getMessage(), e); } }
From source file:it.iit.genomics.cru.structures.bridges.uniprot.UniprotkbUtils.java
private Collection<MoleculeEntry> getUniprotEntriesXML(String location, boolean waitAndRetryOnFailure) throws BridgesRemoteAccessException { String url = location + "&format=xml"; ArrayList<MoleculeEntry> uniprotEntries = new ArrayList<>(); try {//from ww w . j a v a 2s . co m HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE); HttpGet request = new HttpGet(url); // add request header request.addHeader("User-Agent", USER_AGENT); HttpResponse response = client.execute(request); if (response.getEntity().getContentLength() == 0) { // No result return uniprotEntries; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new InputSource(response.getEntity().getContent())); // optional, but recommended // read this - // http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work doc.getDocumentElement().normalize(); // interaction structure NodeList entryList = doc.getElementsByTagName("entry"); for (int i = 0; i < entryList.getLength(); i++) { Element entryElement = (Element) entryList.item(i); String dataset = entryElement.getAttribute("dataset"); String ac = entryElement.getElementsByTagName("accession").item(0).getFirstChild().getNodeValue(); MoleculeEntry uniprotEntry = new MoleculeEntry(ac); uniprotEntry.setDataset(dataset); // Taxid Element organism = (Element) entryElement.getElementsByTagName("organism").item(0); String organismCommonName = null; String organismScientificName = null; String organismOtherName = null; NodeList organismNames = organism.getElementsByTagName("name"); for (int j = 0; j < organismNames.getLength(); j++) { Element reference = (Element) organismNames.item(j); switch (reference.getAttribute("type")) { case "scientific": organismScientificName = reference.getTextContent(); break; case "common": organismCommonName = reference.getTextContent(); break; default: organismOtherName = reference.getTextContent(); break; } } if (null != organismCommonName) { uniprotEntry.setOrganism(organismCommonName); } else if (null != organismScientificName) { uniprotEntry.setOrganism(organismScientificName); } else if (null != organismOtherName) { uniprotEntry.setOrganism(organismOtherName); } NodeList organismReferences = organism.getElementsByTagName("dbReference"); for (int j = 0; j < organismReferences.getLength(); j++) { Element reference = (Element) organismReferences.item(j); if (reference.hasAttribute("type") && "NCBI Taxonomy".equals(reference.getAttribute("type"))) { String proteinTaxid = reference.getAttribute("id"); uniprotEntry.setTaxid(proteinTaxid); } } // GENE NodeList geneNames = entryElement.getElementsByTagName("gene"); for (int j = 0; j < geneNames.getLength(); j++) { Element gene = (Element) geneNames.item(j); NodeList nameList = gene.getElementsByTagName("name"); for (int k = 0; k < nameList.getLength(); k++) { Element name = (Element) nameList.item(k); uniprotEntry.addGeneName(name.getFirstChild().getNodeValue()); } } // modified residues HashMap<String, ModifiedResidue> modifiedResidues = new HashMap<>(); NodeList features = entryElement.getElementsByTagName("feature"); for (int j = 0; j < features.getLength(); j++) { Element feature = (Element) features.item(j); if (false == entryElement.equals(feature.getParentNode())) { continue; } // ensembl if (feature.hasAttribute("type") && "modified residue".equals(feature.getAttribute("type"))) { String description = feature.getAttribute("description").split(";")[0]; if (false == modifiedResidues.containsKey(description)) { modifiedResidues.put(description, new ModifiedResidue(description)); } NodeList locations = feature.getElementsByTagName("location"); for (int k = 0; k < locations.getLength(); k++) { Element loc = (Element) locations.item(k); NodeList positions = loc.getElementsByTagName("position"); for (int l = 0; l < positions.getLength(); l++) { Element position = (Element) positions.item(l); modifiedResidues.get(description).addPosition( new UniprotPosition(Integer.parseInt(position.getAttribute("position")))); } } } } uniprotEntry.getModifications().addAll(modifiedResidues.values()); // Xrefs: NodeList dbReferences = entryElement.getElementsByTagName("dbReference"); for (int j = 0; j < dbReferences.getLength(); j++) { Element dbReference = (Element) dbReferences.item(j); if (false == entryElement.equals(dbReference.getParentNode())) { continue; } NodeList molecules = dbReference.getElementsByTagName("molecule"); // ensembl if (dbReference.hasAttribute("type") && "Ensembl".equals(dbReference.getAttribute("type"))) { // transcript ID String id = dbReference.getAttribute("id"); for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) { Element molecule = (Element) molecules.item(iMolecule); uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id")); } uniprotEntry.addEnsemblGene(id); NodeList properties = dbReference.getElementsByTagName("property"); for (int k = 0; k < properties.getLength(); k++) { Element property = (Element) properties.item(k); if (property.hasAttribute("type") && "gene ID".equals(property.getAttribute("type"))) { uniprotEntry.addEnsemblGene(property.getAttribute("value")); } } } // refseq if (dbReference.hasAttribute("type") && "RefSeq".equals(dbReference.getAttribute("type"))) { NodeList properties = dbReference.getElementsByTagName("property"); for (int k = 0; k < properties.getLength(); k++) { Element property = (Element) properties.item(k); if (property.hasAttribute("type") && "nucleotide sequence ID".equals(property.getAttribute("type"))) { String id = property.getAttribute("value"); if (molecules.getLength() > 0) { for (int iMolecule = 0; iMolecule < molecules.getLength(); iMolecule++) { Element molecule = (Element) molecules.item(iMolecule); // If refseq, add also without the version uniprotEntry.addXrefToVarSplice(id, molecule.getAttribute("id")); uniprotEntry.addXrefToVarSplice(id.split("\\.")[0], molecule.getAttribute("id")); } } else { // If refseq, add also without the version uniprotEntry.addXrefToVarSplice(id, ac); uniprotEntry.addXrefToVarSplice(id.split("\\.")[0], ac); } uniprotEntry.addRefseq(id); } } } /* PDB chains will be imported from the webservice */ // PDB if (dbReference.hasAttribute("type") && "PDB".equals(dbReference.getAttribute("type"))) { NodeList properties = dbReference.getElementsByTagName("property"); String method = null; String chains = null; for (int k = 0; k < properties.getLength(); k++) { Element property = (Element) properties.item(k); if (property.hasAttribute("type") && "method".equals(property.getAttribute("type"))) { method = property.getAttribute("value"); } else if (property.hasAttribute("type") && "chains".equals(property.getAttribute("type"))) { chains = property.getAttribute("value"); } } if (method != null && "Model".equals(method)) { continue; } if (chains == null) { continue; } String pdb = dbReference.getAttribute("id"); uniprotEntry.addPDB(pdb, method); for (String chainElement : chains.split(",")) { try { String chainNames = chainElement.split("=")[0]; int start = Integer.parseInt(chainElement.split("=")[1].trim().split("-")[0]); int end = Integer .parseInt(chainElement.split("=")[1].trim().split("-")[1].replace(".", "")); for (String chainName : chainNames.split("/")) { uniprotEntry.addChain(pdb, new ChainMapping(pdb, chainName.trim(), start, end), method); } } catch (ArrayIndexOutOfBoundsException aiobe) { // IGBLogger.getInstance().warning( // "Cannot parse chain: " + chainElement // + ", skip"); } } } } // Sequence NodeList sequenceElements = entryElement.getElementsByTagName("sequence"); for (int j = 0; j < sequenceElements.getLength(); j++) { Element sequenceElement = (Element) sequenceElements.item(j); if (false == sequenceElement.getParentNode().equals(entryElement)) { continue; } String sequence = sequenceElement.getFirstChild().getNodeValue().replaceAll("\n", ""); uniprotEntry.setSequence(sequence); } // Diseases NodeList diseases = entryElement.getElementsByTagName("disease"); for (int j = 0; j < diseases.getLength(); j++) { Element disease = (Element) diseases.item(j); NodeList nameList = disease.getElementsByTagName("name"); for (int k = 0; k < nameList.getLength(); k++) { Element name = (Element) nameList.item(k); uniprotEntry.addDisease(name.getFirstChild().getNodeValue()); } } // Get fasta for all varsplice String fastaQuery = "http://www.uniprot.org/uniprot/" + uniprotEntry.getUniprotAc() + ".fasta?include=yes"; try { //HttpClient fastaClient = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE); HttpGet fastaRequest = new HttpGet(fastaQuery); // add request header request.addHeader("User-Agent", USER_AGENT); HttpResponse fastaResponse = client.execute(fastaRequest); if (fastaResponse.getEntity().getContentLength() == 0) { continue; } InputStream is = fastaResponse.getEntity().getContent(); try { LinkedHashMap<String, ProteinSequence> fasta = FastaReaderHelper .readFastaProteinSequence(is); boolean mainSequence = true; for (ProteinSequence seq : fasta.values()) { // logger.info("Add sequence: " + seq.getAccession().getID() + " : " + seq.getSequenceAsString()); uniprotEntry.addSequence(seq.getAccession().getID(), seq.getSequenceAsString()); if (mainSequence) { uniprotEntry.setMainIsoform(seq.getAccession().getID()); mainSequence = false; } } } catch (Exception e) { logger.error("Cannot retrieve fasta for : " + uniprotEntry.getUniprotAc()); } } catch (IOException | IllegalStateException ex) { logger.error(null, ex); } uniprotEntries.add(uniprotEntry); } } catch (SAXParseException se) { // Nothing was return // IGBLogger.getInstance() // .error("Uniprot returns empty result: " + url); } catch (IOException | ParserConfigurationException | IllegalStateException | SAXException | DOMException | NumberFormatException e) { if (waitAndRetryOnFailure && allowedUniprotFailures > 0) { try { allowedUniprotFailures--; Thread.sleep(5000); return getUniprotEntriesXML(location, false); } catch (InterruptedException e1) { logger.error("Fail to retrieve data from " + location); throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location); } } else { logger.error("Problem with Uniprot: " + url); throw new BridgesRemoteAccessException("Fail to retrieve data from Uniprot " + location); } } for (MoleculeEntry entry : uniprotEntries) { addToCache(entry); } return uniprotEntries; }
From source file:org.cgiar.ccafs.ap.util.ClientRepository.java
public DefaultHttpClient verifiedClient(HttpClient base) { try {//from ww w . j a v a2 s . c o m SSLContext ctx = SSLContext.getInstance("SSL"); X509TrustManager tm = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager mgr = base.getConnectionManager(); SchemeRegistry registry = mgr.getSchemeRegistry(); registry.register(new Scheme("https", 443, ssf)); return new DefaultHttpClient(mgr, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:uk.ac.brighton.ci360.bigarrow.PlacesAPISearch.java
@SuppressWarnings("unused") private HttpClient sslClient(HttpClient client) { try {// w w w .j ava 2s . c om X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new MySSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = client.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); return new DefaultHttpClient(ccm, client.getParams()); } catch (Exception ex) { return null; } }