private static String senderBase(Method type, String path, String[]... args) { HTTPBaseClient client; switch (type) { case get: client = new HTTPGetClient(path); break; case post: client = new HTTPPostClient(path); break; default: client = null; break; } for (String[] pair : args) { client.addParameter(pair[0], pair[1]); } if (client != null) { try { return client.execute(); } catch (ConnectionException e) { e.printStackTrace(); return e.toString(); } } else { return null; } }
protected JSONObject doInBackground(String... args) { JSONObject json = new JSONObject(); try { HttpUploader uploader = new HttpUploader( getActivity().getResources(), BuildConfig.DOMAIN + Constantes.PUBLISH_COMMENT); uploader.añadirArgumento( "idevento", event.getId()); // le pasamos el codigo del evento del cual estamos mostrando el detalle uploader.añadirArgumento("message", etCommentTxt.getText().toString().trim()); uploader.añadirArgumento("devid", Utilidades.getDevId(getActivity())); uploader.añadirArgumento("timezoneoffset", Utilidades.getTimeZoneOffset(getActivity())); json = uploader.enviar(); } catch (ConnectionException e) { e.printStackTrace(); try { json.put(Constantes.JSON_MESSAGE, e.getMessage()); json.put(Constantes.JSON_SUCCESS, 0); } catch (JSONException e1) { e1.printStackTrace(); } } return json; }
protected JSONObject doInBackground(String... args) { JSONObject json = new JSONObject(); ///////////////////////////////////////////////////// try { HttpUploader uploader = new HttpUploader( getActivity().getResources(), BuildConfig.DOMAIN + Constantes.LOAD_MESSAGES_FILE); uploader.añadirArgumento( "idevento", event.getId()); // le pasamos el codigo del evento del cual estamos mostrando el detalle uploader.añadirArgumento("thumb_width", Float.toString(Constantes.THUMB_SIZE)); uploader.añadirArgumento("thumb_height", Float.toString(Constantes.THUMB_SIZE)); uploader.añadirArgumento("timezoneoffset", Utilidades.getTimeZoneOffset(getActivity())); if ((args != null) && (args.length > 0)) { uploader.añadirArgumento("numerocomments", args[0]); } json = uploader.enviar(); } catch (ConnectionException e) { e.printStackTrace(); try { json.put(Constantes.JSON_MESSAGE, e.getMessage()); json.put(Constantes.JSON_SUCCESS, 0); } catch (JSONException e1) { e1.printStackTrace(); } } return json; }
public void networkException(int id, ExitCode reason) { try { numRunningThreads--; if (tunneling) { // httpSenders[id].disconnect(); System.out.println(NAME + "Failed to use http tunneling. Stopping."); stop(); notifyNetworkConnectionListener(reason); } else { socketSenders[id].disconnect(); } if (numRunningThreads < 1) { System.out.println(NAME + "No more sender threads. Stopping."); stop(); notifyNetworkConnectionListener(reason); } else { System.out.println( NAME + "Sender thread stopped. " + numRunningThreads + " sender threads remaining."); } } catch (ConnectionException e) { // TODO Auto-generated catch block e.printStackTrace(); if (numRunningThreads < 1) { System.out.println(NAME + "No more sender threads. Stopping."); notifyNetworkConnectionListener(reason); } else { System.out.println( NAME + "Sender thread stopped. " + numRunningThreads + " sender threads remaining."); } } }
@SuppressWarnings("unchecked") public <R> ExecuteWithFailover<CL, R> newExecuteWithFailover(Operation<CL, R> operation) throws ConnectionException { try { if (operation.getPinnedHost() != null) { HostConnectionPool<CL> pool = hosts.get(operation.getPinnedHost()); if (pool == null) { throw new NoAvailableHostsException("Host " + operation.getPinnedHost() + " not active"); } return new RoundRobinExecuteWithFailover<CL, R>( config, monitor, Arrays.<HostConnectionPool<CL>>asList(pool), 0); } int index = roundRobinCounter.incrementAndGet(); if (index > Integer.MAX_VALUE / 2) { roundRobinCounter.set(0); index = 0; } return new RoundRobinExecuteWithFailover<CL, R>( config, monitor, topology.getAllPools().getPools(), index); } catch (ConnectionException e) { monitor.incOperationFailure(e.getHost(), e); throw e; } }
/** * Tests the API using the supplied tester instance. First the API is tested with non-null * parameters, then with null parameters and finally the failure of the API is tested. * * @param inTester the tester to test the API invocation. * @param <R> the return type of the API. * @throws Exception if there were unexpected errors */ private static <R> void testAPI(final WSTester<R> inTester) throws Exception { // Test a regular invocation. R value = inTester.setReturnValue(false); verifyEquals(value, inTester.invokeApi(false)); inTester.verifyInputParams(false); // Test invocation with nulls resetServiceParameters(); value = inTester.setReturnValue(true); verifyEquals(value, inTester.invokeApi(true)); inTester.verifyInputParams(true); // Test a failure resetServiceParameters(); I18NException failure = new I18NException(new I18NMessage0P(Messages.LOGGER, "test")); getMockSAService().setFailure(failure); inTester.setReturnValue(false); ConnectionException e = new ExpectedFailure<ConnectionException>() { @Override protected void run() throws Exception { inTester.invokeApi(false); } }.getException(); assertNotNull(e.getCause()); assertEquals(failure, e.getCause()); // Verify that input parameters were received even when failure occured. inTester.verifyInputParams(false); // Test service interruption verifyInvocationCannotBeInterrupted(inTester); }
public boolean connect() { int failedAttempts = 0; socketSenders = new NetworkSocketStreamSender[numThreads]; try { NetworkSocket socket = new NetworkSocket(host, port); for (int i = 0; i < numThreads; i++) { try { createSender(i, socket); numRunningThreads++; } catch (ConnectionException e) { failedAttempts++; } } } catch (ConnectionException e) { e.printStackTrace(); failedAttempts = numThreads; } if ((failedAttempts == numThreads) && httpTunnel) { System.out.println(NAME + "Trying http tunneling"); failedAttempts = 0; numRunningThreads = 0; if (tryHttpTunneling()) { tunneling = true; System.out.println(NAME + "Will use http tunneling"); httpSenders = new NetworkHttpStreamSender[numThreads]; for (int i = 0; i < numThreads; i++) { try { createHttpSender(i); numRunningThreads++; } catch (ConnectionException e) { failedAttempts++; } } return failedAttempts != numThreads; } } else { if (numRunningThreads != numThreads) { try { stop(); } catch (ConnectionException e) { e.printStackTrace(); } return false; } else { return true; } } System.out.println(NAME + "Http tunneling failed."); return false; }
public Map<String, Construct> evaluate(BindableEvent e) throws EventException { Map<String, Construct> retn = new HashMap<String, Construct>(); if (e instanceof ConnectionException) { ConnectionException msg = (ConnectionException) e; retn.put("id", new CString(msg.getBot().getID(), Target.UNKNOWN)); retn.put("message", new CString(msg.getMessage(), Target.UNKNOWN)); retn.put("exceptionclass", new CString(msg.className(), Target.UNKNOWN)); } return retn; }
public void start() { System.out.println(NAME + "Starting network sender."); if (tunneling) { for (int i = 0; i < numRunningThreads; i++) { httpSenders[i].sendStartStreamMessage(); executor.execute(httpSenders[i]); } } else { for (int i = 0; i < numRunningThreads; i++) { try { socketSenders[i].sendStartStreamMessage(); executor.execute(socketSenders[i]); } catch (ConnectionException e) { e.printStackTrace(); } } } stopped = false; }
private void handleConnect() { if (jToggleButtonConnect.isSelected() || jMenuItemServerConnect.isEnabled()) try { jTextPaneDisplayMessages.setText(""); session = new Session(); try { String userid = jTextFieldUser.getText(); if (jPasswordFieldPwd.getPassword() != null) { String pwd = String.valueOf(jPasswordFieldPwd.getPassword()).trim(); if (!pwd.equals("")) { userid += ":" + pwd; } } if (session.connect(jTextFieldServer.getText(), userid)) { displayMessage("Connected\n", incomingMsgAttrSet); session.addListener(this); jToggleButtonConnect.setText("Disconnect"); jMenuItemServerConnect.setEnabled(false); jMenuItemServerDisconnect.setEnabled(true); } else { jToggleButtonConnect.setSelected(false); jMenuItemServerConnect.setEnabled(true); jMenuItemServerDisconnect.setEnabled(false); displayMessage("Connection attempt failed\n", offlineClientAttrSet); } } catch (ConnectionException ex1) { jToggleButtonConnect.setSelected(false); jMenuItemServerConnect.setEnabled(true); jMenuItemServerDisconnect.setEnabled(false); displayMessage( "Connection attempt failed: " + ex1.getMessage() + "\n", offlineClientAttrSet); } } catch (Exception ex) { ex.printStackTrace(); } else { disconnect(); jMenuItemServerConnect.setEnabled(true); jMenuItemServerDisconnect.setEnabled(false); displayMessage("Disconnected\n", offlineClientAttrSet); } }
private HostConnectionPool addHost(Host host) { try { HostDistance distance = loadBalancer.distance(host); if (distance == HostDistance.IGNORED) { return pools.get(host); } else { logger.debug("Adding {} to list of queried hosts", host); return pools.put(host, new HostConnectionPool(host, distance, this)); } } catch (AuthenticationException e) { logger.error("Error creating pool to {} ({})", host, e.getMessage()); host.getMonitor() .signalConnectionFailure(new ConnectionException(e.getHost(), e.getMessage())); return pools.get(host); } catch (ConnectionException e) { logger.debug("Error creating pool to {} ({})", host, e.getMessage()); host.getMonitor().signalConnectionFailure(e); return pools.get(host); } }
protected JSONObject doInBackground(String... args) { JSONObject json = new JSONObject(); try { HttpUploader uploader = new HttpUploader( getActivity().getResources(), BuildConfig.DOMAIN + Constantes.GET_IMAGE_FILE); uploader.añadirArgumento( "image", args[0]); // args[0] is the name of the image we're trying to get json = uploader.enviar(); } catch (ConnectionException e) { e.printStackTrace(); try { json.put(Constantes.JSON_MESSAGE, e.getMessage()); json.put(Constantes.JSON_SUCCESS, 0); } catch (JSONException e1) { e1.printStackTrace(); } } return json; }
private ConnectionException parseDetail(XmlInputStream xin, QName faultCode, String faultstring) throws IOException, ConnectionException { ConnectionException e; xin.nextTag(); // consume <detail> xin.peekTag(); // move to the body of <detail> if (xin.getEventType() == XmlInputStream.END_TAG) { // check for empty detail element throw new SoapFaultException(faultCode, faultstring); } TypeInfo info = new TypeInfo(null, null, null, null, 1, 1, true); try { e = (ConnectionException) typeMapper.readObject(xin, info, ConnectionException.class); if (e instanceof SoapFaultException) { ((SoapFaultException) e).setFaultCode(faultCode); if (faultstring != null && (faultstring.contains("Session timed out") || faultstring.contains("Session not found") || faultstring.contains("Illegal Session")) && "INVALID_SESSION_ID".equals(faultCode.getLocalPart())) { e = new SessionTimedOutException(faultstring, e); } } } catch (ConnectionException ce) { throw new ConnectionException( "Failed to parse detail: " + xin + " due to: " + ce, ce.getCause()); } xin.nextTag(); // consume </detail> if (!"detail".equals(xin.getName())) { throw new ConnectionException("Failed to find </detail>"); } return e; }
protected JSONObject doInBackground(String... args) { JSONObject json = new JSONObject(); try { HttpUploader uploader = new HttpUploader( getActivity().getResources(), BuildConfig.DOMAIN + Constantes.LEER_EVENTOS_FILE); uploader.añadirArgumento( "_id", args[0]); // le pasamos el codigo del evento del cual estamos mostrando el detalle uploader.añadirArgumento("timezoneoffset", Utilidades.getTimeZoneOffset(getActivity())); json = uploader.enviar(); } catch (ConnectionException e) { e.printStackTrace(); try { json.put(Constantes.JSON_MESSAGE, e.getMessage()); json.put(Constantes.JSON_SUCCESS, 0); } catch (JSONException e1) { e1.printStackTrace(); } } return json; }
@Override public List<String> getIdsOfUsersFollowedBy(String userId) throws ConnectionException { Uri sUri = Uri.parse(getApiPath(ApiRoutineEnum.GET_FRIENDS_IDS)); Uri.Builder builder = sUri.buildUpon(); builder.appendQueryParameter("user_id", userId); List<String> list = new ArrayList<String>(); JSONArray jArr = http.getRequestAsArray(builder.build().toString()); try { for (int index = 0; index < jArr.length(); index++) { list.add(jArr.getString(index)); } } catch (JSONException e) { throw ConnectionException.loggedJsonException(this, e, null, "Parsing friendsIds"); } return list; }
/** * Retrieves a group of URLs representing the documents accepted by the given participant id * * @param participantId participant id to look up * @return list of URLs representing each document type accepted */ @Override public List<PeppolDocumentTypeId> getServiceGroups(ParticipantId participantId) throws SmpLookupException, ParticipantNotRegisteredException { // Creates the URL for the service meta data for the supplied participant URL serviceGroupURL = constructServiceGroupURL(participantId); if (!isParticipantRegistered(serviceGroupURL)) { throw new ParticipantNotRegisteredException(participantId); } NodeList nodes; List<PeppolDocumentTypeId> result = new ArrayList<PeppolDocumentTypeId>(); InputSource smpContents; /* When looking up ParticipantId("9908:976098897") we expected the SML not to resolve, but it actually did and we got a not found (HTTP 404) response from SMP instead (smp-basware.publisher.sml.peppolcentral.org). */ try { smpContents = smpContentRetriever.getUrlContent(serviceGroupURL); } catch (ConnectionException ex) { if (404 == ex.getCode()) { // signal that we got a NOT FOUND for that participant in the SMP throw new ParticipantNotRegisteredException(participantId); } else { throw ex; // re-throw exception } } // Parses the XML response from the SMP try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder; Document document; documentBuilder = documentBuilderFactory.newDocumentBuilder(); document = documentBuilder.parse(smpContents); // Locates the namespace URI of the root element String nameSpaceURI = document.getDocumentElement().getNamespaceURI(); nodes = document.getElementsByTagNameNS(nameSpaceURI, "ServiceMetadataReference"); } catch (Exception e) { throw new SmpLookupException(participantId, serviceGroupURL, e); } // Loop the SMR elements, if any, and populate the result list if (nodes != null) { for (int i = 0; i < nodes.getLength(); i++) { String docTypeAsString = null; try { // Fetch href attribute Element element = (Element) nodes.item(i); String hrefAsString = element.getAttribute("href"); // Gets rid of all the funny %3A's... hrefAsString = URLDecoder.decode(hrefAsString, "UTF-8"); // Grabs the entire text string after "busdox-docid-qns::" docTypeAsString = hrefAsString.substring( hrefAsString.indexOf("busdox-docid-qns::") + "busdox-docid-qns::".length()); // Parses and creates the document type id PeppolDocumentTypeId peppolDocumentTypeId = PeppolDocumentTypeId.valueOf(docTypeAsString); result.add(peppolDocumentTypeId); } catch (Exception e) { /* ignore unparseable document types at runtime */ Log.warn( "Unable to create PeppolDocumentTypeId from " + docTypeAsString + ", got exception " + e.getMessage()); } } } return result; }