private void loop() { while (thread == Thread.currentThread()) { try { Request key = peekKey(); if (key == null) throw new IOException("end of stream"); synchronized (response_map) { Response response = (Response) response_map.get(key); if (response == null) { if (log.level >= 4) log.println("Invalid key, skipping message"); doSkip(); } else { doRecv(response); response.isReceived = true; response_map.notifyAll(); } } } catch (Exception ex) { String msg = ex.getMessage(); boolean timeout = msg != null && msg.equals("Read timed out"); /* If just a timeout, try to disconnect gracefully */ boolean hard = timeout == false; if (!timeout && log.level >= 3) ex.printStackTrace(log); try { disconnect(hard); } catch (IOException ioe) { ioe.printStackTrace(log); } } } }
private Response respond(Map<String, String> headers, String uri) { // Remove URL arguments uri = uri.trim().replace(File.separatorChar, '/'); if (uri.indexOf('?') >= 0) { uri = uri.substring(0, uri.indexOf('?')); } // Prohibit getting out of current directory if (uri.contains("../")) { return createResponse( Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "FORBIDDEN: Won't serve ../ for security reasons."); } File f = new File(webRoot, uri); if (!f.exists()) { return createResponse( Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Error 404, file not found."); } // Browsers get confused without '/' after the directory, send a // redirect. if (f.isDirectory() && !uri.endsWith("/")) { uri += "/"; Response res = createResponse( Response.Status.REDIRECT, NanoHTTPD.MIME_HTML, "<html><body>Redirected: <a href=\"" + uri + "\">" + uri + "</a></body></html>"); res.addHeader("Location", uri); return res; } if (f.isDirectory()) { // First look for index files (index.html, index.htm, etc) and if // none found, list the directory if readable. String indexFile = findIndexFileInDirectory(f); if (indexFile == null) { if (f.canRead()) { // No index file, list the directory if it is readable return createResponse(Response.Status.OK, NanoHTTPD.MIME_HTML, listDirectory(uri, f)); } else { return createResponse( Response.Status.FORBIDDEN, NanoHTTPD.MIME_PLAINTEXT, "FORBIDDEN: No directory listing."); } } else { return respond(headers, uri + indexFile); } } Response response = null; response = serveFile(uri, headers, f, getMimeTypeForFile(uri)); return response != null ? response : createResponse( Response.Status.NOT_FOUND, NanoHTTPD.MIME_PLAINTEXT, "Error 404, file not found."); }
public Optional<Response> get(Optional<Request> request) { if (!valid) { Logger.error("CANNOT GET! NO VALID CONNECTION"); return Optional.empty(); } Response response = new Response(); if (request.isPresent()) { Request r = request.get(); response.key = r.key; response.table = r.table; try { final Table htable = connection.getTable(TableName.valueOf(r.table)); Result result = htable.get(new Get(r.key)); if (result == null || result.isEmpty()) { return Optional.empty(); } r.columns.forEach( c -> response.columns.add( new Request.Column( c.family, c.qualifier, result.getValue(c.family.getBytes(), c.qualifier.getBytes())))); } catch (IOException e) { e.printStackTrace(); } } return Optional.of(response); }
/** * Validates a specified template. * * @param validateTemplateRequest The input for <a>ValidateTemplate</a> action. * @return Result of the ValidateTemplate operation returned by the service. * @sample AmazonCloudFormation.ValidateTemplate */ @Override public ValidateTemplateResult validateTemplate(ValidateTemplateRequest validateTemplateRequest) { ExecutionContext executionContext = createExecutionContext(validateTemplateRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<ValidateTemplateRequest> request = null; Response<ValidateTemplateResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new ValidateTemplateRequestMarshaller() .marshall(super.beforeMarshalling(validateTemplateRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } StaxResponseHandler<ValidateTemplateResult> responseHandler = new StaxResponseHandler<ValidateTemplateResult>( new ValidateTemplateResultStaxUnmarshaller()); response = invoke(request, responseHandler, executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } }
/** * You use this operation to change the parameters specified in the original manifest file by * supplying a new manifest file. The manifest file attached to this request replaces the original * manifest file. You can only use the operation after a CreateJob request but before the data * transfer starts and you can only use it on jobs you own. * * @param updateJobRequest Container for the necessary parameters to execute the UpdateJob service * method on AmazonImportExport. * @return The response from the UpdateJob service method, as returned by AmazonImportExport. * @throws MalformedManifestException * @throws BucketPermissionException * @throws InvalidAddressException * @throws InvalidParameterException * @throws UnableToUpdateJobIdException * @throws MultipleRegionsException * @throws InvalidVersionException * @throws MissingParameterException * @throws InvalidFileSystemException * @throws CanceledJobIdException * @throws MissingCustomsException * @throws NoSuchBucketException * @throws ExpiredJobIdException * @throws InvalidAccessKeyIdException * @throws InvalidCustomsException * @throws InvalidManifestFieldException * @throws MissingManifestFieldException * @throws InvalidJobIdException * @throws AmazonClientException If any internal errors are encountered inside the client while * attempting to make the request or handle the response. For example if a network connection * is not available. * @throws AmazonServiceException If an error response is returned by AmazonImportExport * indicating either a problem with the data in the request, or a server side issue. */ public UpdateJobResult updateJob(UpdateJobRequest updateJobRequest) { ExecutionContext executionContext = createExecutionContext(updateJobRequest); AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics(); awsRequestMetrics.startEvent(Field.ClientExecuteTime); Request<UpdateJobRequest> request = null; Response<UpdateJobResult> response = null; try { awsRequestMetrics.startEvent(Field.RequestMarshallTime); try { request = new UpdateJobRequestMarshaller().marshall(super.beforeMarshalling(updateJobRequest)); // Binds the request metrics to the current request. request.setAWSRequestMetrics(awsRequestMetrics); } finally { awsRequestMetrics.endEvent(Field.RequestMarshallTime); } response = invoke(request, new UpdateJobResultStaxUnmarshaller(), executionContext); return response.getAwsResponse(); } finally { endClientExecution(awsRequestMetrics, request, response); } }
public void sendrecv(Request request, Response response, long timeout) throws IOException { synchronized (response_map) { makeKey(request); response.isReceived = false; try { response_map.put(request, response); doSend(request); response.expiration = System.currentTimeMillis() + timeout; while (!response.isReceived) { response_map.wait(timeout); timeout = response.expiration - System.currentTimeMillis(); if (timeout <= 0) { throw new TransportException(name + " timedout waiting for response to " + request); } } } catch (IOException ioe) { if (log.level > 2) ioe.printStackTrace(log); try { disconnect(true); } catch (IOException ioe2) { ioe2.printStackTrace(log); } throw ioe; } catch (InterruptedException ie) { throw new TransportException(ie); } finally { response_map.remove(request); } } }
public NanoHTTPD.Response serve(NanoHTTPD server, Properties args, RequestType type) { // Needs to be done also for help to initialize or argument records String query = checkArguments(args, type); switch (type) { case help: return wrap(server, build(Response.done(serveHelp()))); case json: case www: if (log()) { String log = getClass().getSimpleName(); for (Object arg : args.keySet()) { String value = args.getProperty((String) arg); if (value != null && value.length() != 0) log += " " + arg + "=" + value; } Log.debug(Sys.HTTPD, log); } if (query != null) return wrap(server, query, type); long time = System.currentTimeMillis(); Response response = serve(); response.setTimeStart(time); if (type == RequestType.json) return wrap(server, response.toJson()); return wrap(server, build(response)); case debug: response = serve_debug(); return wrap(server, build(response)); case query: return wrap(server, query); default: throw new RuntimeException("Invalid request type " + type.toString()); } }
public void processCancel(RequestEvent requestEvent, ServerTransaction serverTransactionId) { Request request = requestEvent.getRequest(); SipProvider sipProvider = (SipProvider) requestEvent.getSource(); try { logger.info("shootme: got a cancel. "); // Because this is not an In-dialog request, you will get a null server Tx id here. if (serverTransactionId == null) { serverTransactionId = sipProvider.getNewServerTransaction(request); } Response response = protocolObjects.messageFactory.createResponse(200, request); serverTransactionId.sendResponse(response); String serverTxId = ((ViaHeader) response.getHeader(ViaHeader.NAME)).getBranch(); ServerTransaction serverTx = (ServerTransaction) this.serverTxTable.get(serverTxId); if (serverTx != null && (serverTx.getState().equals(TransactionState.TRYING) || serverTx.getState().equals(TransactionState.PROCEEDING))) { Request originalRequest = serverTx.getRequest(); Response resp = protocolObjects.messageFactory.createResponse( Response.REQUEST_TERMINATED, originalRequest); serverTx.sendResponse(resp); } } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } }
private void sendInviteOK(RequestEvent requestEvent, ServerTransaction inviteTid) { try { logger.info("sendInviteOK: " + inviteTid); if (inviteTid.getState() != TransactionState.COMPLETED) { logger.info("shootme: Dialog state before OK: " + inviteTid.getDialog().getState()); SipProvider sipProvider = (SipProvider) requestEvent.getSource(); Request request = requestEvent.getRequest(); Response okResponse = protocolObjects.messageFactory.createResponse(Response.OK, request); ListeningPoint lp = sipProvider.getListeningPoint(protocolObjects.transport); int myPort = lp.getPort(); Address address = protocolObjects.addressFactory.createAddress( "Shootme <sip:" + myAddress + ":" + myPort + ">"); ContactHeader contactHeader = protocolObjects.headerFactory.createContactHeader(address); okResponse.addHeader(contactHeader); inviteTid.sendResponse(okResponse); logger.info("shootme: Dialog state after OK: " + inviteTid.getDialog().getState()); TestHarness.assertEquals(DialogState.CONFIRMED, inviteTid.getDialog().getState()); } else { logger.info("semdInviteOK: inviteTid = " + inviteTid + " state = " + inviteTid.getState()); } } catch (Exception ex) { ex.printStackTrace(); } }
@Test public void post() throws Exception { given(connection.getURL()).willReturn(new URL(URL)); given(connection.getResponseCode()).willReturn(200); given(connection.getResponseMessage()).willReturn("OK"); Map<String, List<String>> responseHeaderFields = new LinkedHashMap<String, List<String>>(); responseHeaderFields.put("Set-Cookie", Arrays.asList("aaa")); given(connection.getHeaderFields()).willReturn(responseHeaderFields); Request request = new Request( "POST", URL, Arrays.asList(new Header("Hoge", "Piyo")), new FormUrlEncodedTypedOutput().addField("foo", "bar")); Response response = underTest.execute(request); verify(connection).setRequestMethod("POST"); verify(connection).addRequestProperty("Hoge", "Piyo"); verify(connection).getOutputStream(); assertThat(response.getUrl()).isEqualTo(URL); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.getReason()).isEqualTo("OK"); assertThat(response.getHeaders()).isEqualTo(Arrays.asList(new Header("Set-Cookie", "aaa"))); assertThat(output.toString("UTF-8")).isEqualTo("foo=bar"); }
@Test public void canRetrieveUnsetKey() { ShardedJedisPipeline p = jedis.pipelined(); Response<String> shouldNotExist = p.get(UUID.randomUUID().toString()); p.sync(); assertNull(shouldNotExist.get()); }
public void doCall(String method, Object value) throws Exception { Call call = new Call(); call.setTargetObjectURI("http://soapinterop.org/"); call.setMethodName(method); call.setEncodingStyleURI(encodingStyleURI); Vector params = new Vector(); params.addElement(new Parameter("in", value.getClass(), value, null)); call.setParams(params); // make the call: note that the action URI is empty because the // XML-SOAP rpc router does not need this. This may change in the // future. Response resp = call.invoke(url, ""); // Check the response. if (resp.generatedFault()) { Fault fault = resp.getFault(); System.out.println("Ouch, the call failed: "); System.out.println(" Fault Code = " + fault.getFaultCode()); System.out.println(" Fault String = " + fault.getFaultString()); } else { Parameter result = resp.getReturnValue(); System.out.println("Call succeeded: "); System.out.println("Result = " + result.getValue()); } }
public Response call(DB db, DBCollection coll, OutMessage m, int retries) throws MongoException { final MyPort mp = _threadPort.get(); final DBPort port = mp.get(false); port.checkAuth(db); Response res = null; try { res = port.call(m, coll); mp.done(port); } catch (IOException ioe) { mp.error(ioe); if (_error(ioe) && retries > 0) { return call(db, coll, m, retries - 1); } throw new MongoException.Network("can't call something", ioe); } catch (RuntimeException re) { mp.error(re); throw re; } ServerError err = res.getError(); if (err != null && err.isNotMasterError()) { _pickCurrent(); if (retries <= 0) { throw new MongoException("not talking to master and retries used up"); } return call(db, coll, m, retries - 1); } return res; }
public void run() { Request request = requestEvent.getRequest(); try { // System.out.println("shootme: got an Invite sending OK"); Response response = messageFactory.createResponse(180, request); ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME); Address address = addressFactory.createAddress("Shootme <sip:" + myAddress + ":" + myPort + ">"); ContactHeader contactHeader = headerFactory.createContactHeader(address); response.addHeader(contactHeader); // System.out.println("got a server tranasaction " + st); Dialog dialog = st.getDialog(); /* * if (dialog != null) { System.out.println("Dialog " + dialog); * System.out.println("Dialog state " + dialog.getState()); } */ st.sendResponse(response); // send 180(RING) response = messageFactory.createResponse(200, request); toHeader = (ToHeader) response.getHeader(ToHeader.NAME); String toTag = new Integer((int) (Math.random() * 1000)).toString(); toHeader.setTag(toTag); // Application is supposed to set. response.addHeader(contactHeader); st.sendResponse(response); // send 200(OK) } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } }
@PUT @Consumes(MediaType.APPLICATION_XML) public Response putTaskData(String value) { Response res = null; // add your code here // first check if the Entity exists in the datastore DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService(); syncCache.setErrorHandler(ErrorHandlers.getConsistentLogAndContinue(Level.INFO)); Key entKey = KeyFactory.createKey("TaskData", keyname); Date date = new Date(); try { // if it is, signal that we updated the entity Entity ts = datastore.get(entKey); ts.setProperty("value", value); ts.setProperty("date", date); datastore.put(ts); res = Response.noContent().build(); } catch (EntityNotFoundException e) { // if it is not, create it and // signal that we created the entity in the datastore Entity taskdata = new Entity("TaskData", keyname); taskdata.setProperty("value", value); taskdata.setProperty("date", date); datastore.put(taskdata); res = Response.created(uriInfo.getAbsolutePath()).build(); } TaskData td = new TaskData(keyname, value, date); syncCache.put(keyname, td); return res; }
private static synchronized void retrieveTestAccountsForAppIfNeeded() { if (appTestAccounts != null) { return; } appTestAccounts = new HashMap<String, TestAccount>(); // The data we need is split across two different FQL tables. We construct two queries, submit // them // together (the second one refers to the first one), then cross-reference the results. // Get the test accounts for this app. String testAccountQuery = String.format( "SELECT id,access_token FROM test_account WHERE app_id = %s", testApplicationId); // Get the user names for those accounts. String userQuery = "SELECT uid,name FROM user WHERE uid IN (SELECT id FROM #test_accounts)"; Bundle parameters = new Bundle(); // Build a JSON string that contains our queries and pass it as the 'q' parameter of the query. JSONObject multiquery; try { multiquery = new JSONObject(); multiquery.put("test_accounts", testAccountQuery); multiquery.put("users", userQuery); } catch (JSONException exception) { throw new FacebookException(exception); } parameters.putString("q", multiquery.toString()); // We need to authenticate as this app. parameters.putString("access_token", getAppAccessToken()); Request request = new Request(null, "fql", parameters, null); Response response = request.executeAndWait(); if (response.getError() != null) { throw response.getError().getException(); } FqlResponse fqlResponse = response.getGraphObjectAs(FqlResponse.class); GraphObjectList<FqlResult> fqlResults = fqlResponse.getData(); if (fqlResults == null || fqlResults.size() != 2) { throw new FacebookException("Unexpected number of results from FQL query"); } // We get back two sets of results. The first is from the test_accounts query, the second from // the users query. Collection<TestAccount> testAccounts = fqlResults.get(0).getFqlResultSet().castToListOf(TestAccount.class); Collection<UserAccount> userAccounts = fqlResults.get(1).getFqlResultSet().castToListOf(UserAccount.class); // Use both sets of results to populate our static array of accounts. populateTestAccounts(testAccounts, userAccounts); return; }
public void processResponse(ResponseEvent responseReceivedEvent) { // Log.info("Registering response...." + sipCallId); Response response = (Response) responseReceivedEvent.getResponse(); int statusCode = response.getStatusCode(); String method = ((CSeqHeader) response.getHeader(CSeqHeader.NAME)).getMethod(); Log.debug("Got response " + response); if (statusCode == Response.OK) { isRegistered = true; Log.info( "Voice bridge successfully registered with " + registrar + " for " + proxyCredentials.getXmppUserName()); PluginImpl.sipRegisterStatus = "Registered ok with " + proxyCredentials.getHost(); sipServerCallback.removeSipListener(sipCallId); } else if (statusCode == Response.UNAUTHORIZED || statusCode == Response.PROXY_AUTHENTICATION_REQUIRED) { if (method.equals(Request.REGISTER)) { CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME); if (cseq.getSequenceNumber() < 2) { ClientTransaction regTrans = SipService.handleChallenge( response, responseReceivedEvent.getClientTransaction(), proxyCredentials); if (regTrans != null) { try { regTrans.sendRequest(); } catch (Exception e) { Log.info("Registration failed, cannot send transaction " + e); PluginImpl.sipRegisterStatus = "Registration error " + e.toString(); } } else { Log.info("Registration failed, cannot create transaction"); PluginImpl.sipRegisterStatus = "Registration cannot create transaction"; } } else { Log.info("Registration failed " + responseReceivedEvent); PluginImpl.sipRegisterStatus = "Registration failed"; } } } else { Log.info("Unrecognized response: " + response); } }
@Override public Response statfs(Map<Byte, Long> instanceMap) throws TException { // TODO: don't care about this for now Response r = new Response(replica.getInstanceMap()); r.setStatfs( new FileSystemStats(32 * 1024, 0, Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 0, 1024)); return r; }
public void sendResponse() { int statusCode = response.getStatus().getCode(); if (statusCode >= 400) { context.clientError(statusCode); } else { response.send(MediaType.TEXT_HTML, responseContent); } }
/** Process the invite request. */ public void processInvite(RequestEvent requestEvent, ServerTransaction serverTransaction) { SipProvider sipProvider = (SipProvider) requestEvent.getSource(); Request request = requestEvent.getRequest(); try { logger.info("shootme: got an Invite sending Trying"); // logger.info("shootme: " + request); ServerTransaction st = requestEvent.getServerTransaction(); if (st == null) { logger.info("null server tx -- getting a new one"); st = sipProvider.getNewServerTransaction(request); } logger.info("getNewServerTransaction : " + st); String txId = ((ViaHeader) request.getHeader(ViaHeader.NAME)).getBranch(); this.serverTxTable.put(txId, st); // Create the 100 Trying response. Response response = protocolObjects.messageFactory.createResponse(Response.TRYING, request); ListeningPoint lp = sipProvider.getListeningPoint(protocolObjects.transport); int myPort = lp.getPort(); Address address = protocolObjects.addressFactory.createAddress( "Shootme <sip:" + myAddress + ":" + myPort + ">"); // Add a random sleep to stagger the two OK's for the benifit of implementations // that may not be too good about handling re-entrancy. int timeToSleep = (int) (Math.random() * 1000); Thread.sleep(timeToSleep); st.sendResponse(response); Response ringingResponse = protocolObjects.messageFactory.createResponse(Response.RINGING, request); ContactHeader contactHeader = protocolObjects.headerFactory.createContactHeader(address); response.addHeader(contactHeader); ToHeader toHeader = (ToHeader) ringingResponse.getHeader(ToHeader.NAME); String toTag = actAsNonRFC3261UAS ? null : new Integer((int) (Math.random() * 10000)).toString(); if (!actAsNonRFC3261UAS) toHeader.setTag(toTag); // Application is supposed to set. ringingResponse.addHeader(contactHeader); st.sendResponse(ringingResponse); Dialog dialog = st.getDialog(); dialog.setApplicationData(st); this.inviteSeen = true; new Timer().schedule(new MyTimerTask(requestEvent, st /*,toTag*/), 1000); } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } }
@Test(expected = JedisDataException.class) public void pipelineResponseWithinPipeline() { jedis.set("string", "foo"); ShardedJedisPipeline p = jedis.pipelined(); Response<String> string = p.get("string"); string.get(); p.sync(); }
@Override public Response open(String path, int flags, Map<Byte, Long> instanceMap) throws TException { path = makePathAbsolute(path); Set<Byte> parts = oracle.partitionsOf(path); Command cmd = newCommand(CommandType.OPEN, parts, instanceMap); OpenCmd open = new OpenCmd(path, flags, parts); cmd.setOpen(open); FileHandle fh = (FileHandle) replica.submitCommand(cmd); Response r = new Response(replica.getInstanceMap()); r.setOpen(fh); return r; }
public void processResponse(ResponseEvent responseReceivedEvent) { System.out.println("Got a response"); Response response = (Response) responseReceivedEvent.getResponse(); Transaction tid = responseReceivedEvent.getClientTransaction(); System.out.println( "Response received with client transaction id " + tid + ":\n" + response.getStatusCode()); if (tid == null) { System.out.println("Stray response -- dropping "); return; } System.out.println("transaction state is " + tid.getState()); System.out.println("Dialog = " + tid.getDialog()); System.out.println("Dialog State is " + tid.getDialog().getState()); try { if (response.getStatusCode() == Response.OK && ((CSeqHeader) response.getHeader(CSeqHeader.NAME)) .getMethod() .equals(Request.INVITE)) { // Request cancel = inviteTid.createCancel(); // ClientTransaction ct = // sipProvider.getNewClientTransaction(cancel); // ct.sendRequest(); Dialog dialog = tid.getDialog(); CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME); Request ackRequest = dialog.createAck(cseq.getSeqNumber()); System.out.println("Sending ACK"); dialog.sendAck(ackRequest); // Send a Re INVITE but this time force it // to use UDP as the transport. Else, it will // Use whatever transport was used to create // the dialog. if (reInviteCount == 0) { Request inviteRequest = dialog.createRequest(Request.INVITE); ((SipURI) inviteRequest.getRequestURI()).removeParameter("transport"); ((ViaHeader) inviteRequest.getHeader(ViaHeader.NAME)).setTransport("udp"); inviteRequest.addHeader(contactHeader); try { Thread.sleep(100); } catch (Exception ex) { } ClientTransaction ct = udpProvider.getNewClientTransaction(inviteRequest); dialog.sendRequest(ct); reInviteCount++; } } } catch (Exception ex) { ex.printStackTrace(); System.exit(0); } }
/** * Repartition is required when number of partitions are not equal to required partitions. * * @param batchedOperatorStats the stats to use when repartitioning. * @return Returns the stats listener response. */ @Override public Response processStats(BatchedOperatorStats batchedOperatorStats) { Response res = new Response(); res.repartitionRequired = false; if (currentPartitions != partitionCount) { LOG.info( "processStats: trying repartition of input operator current {} required {}", currentPartitions, partitionCount); res.repartitionRequired = true; } return res; }
/* -------------------- AsyncRequestHandler Interface --------------------- */ public void handle(Message request, Response response) throws Exception { if (req_handler != null) { if (req_handler instanceof AsyncRequestHandler) ((AsyncRequestHandler) req_handler).handle(request, response); else { Object retval = req_handler.handle(request); if (response != null) response.send(retval, false); } return; } Object retval = handle(request); if (response != null) response.send(retval, false); }
/** * Gets the <tt>TransportAddress</tt> specified in the XOR-MAPPED-ADDRESS attribute of a specific * <tt>Response</tt>. * * @param response the <tt>Response</tt> from which the XOR-MAPPED-ADDRESS attribute is to be * retrieved and its <tt>TransportAddress</tt> value is to be returned * @return the <tt>TransportAddress</tt> specified in the XOR-MAPPED-ADDRESS attribute of * <tt>response</tt> */ protected TransportAddress getMappedAddress(Response response) { Attribute attribute = response.getAttribute(Attribute.XOR_MAPPED_ADDRESS); if (attribute instanceof XorMappedAddressAttribute) { return ((XorMappedAddressAttribute) attribute).getAddress(response.getTransactionID()); } // old STUN servers (RFC3489) send MAPPED-ADDRESS address attribute = response.getAttribute(Attribute.MAPPED_ADDRESS); if (attribute instanceof MappedAddressAttribute) { return ((MappedAddressAttribute) attribute).getAddress(); } else return null; }
@Override public Response readlink(String path, Map<Byte, Long> instanceMap) throws TException { path = makePathAbsolute(path); // can be sent to ANY partition that replicates the path - we send it to the first returned by // the oracle Set<Byte> parts = Sets.newHashSet(Byte.valueOf(partition)); Command cmd = newCommand(CommandType.READLINK, parts, instanceMap); ReadlinkCmd readlink = new ReadlinkCmd(path, parts); cmd.setReadlink(readlink); String result = (String) replica.submitCommand(cmd); Response r = new Response(replica.getInstanceMap()); r.setReadlink(result); return r; }
@Test public void errorResponseThrowsHttpError() throws Exception { given(connection.getURL()).willReturn(new URL(URL)); given(connection.getResponseCode()).willReturn(400); Map<String, List<String>> responseHeaderFields = new LinkedHashMap<String, List<String>>(); given(connection.getHeaderFields()) .willReturn(responseHeaderFields, Collections.<String, List<String>>emptyMap()); Request request = new Request("GET", URL, Collections.<Header>emptyList(), null); Response response = underTest.execute(request); assertThat(response.getStatus()).isEqualTo(400); }
@Override public Response getattr(String path, Map<Byte, Long> instanceMap) throws TException { // can be sent to ANY partition that replicates the path - we send it to the first returned by // the oracle path = makePathAbsolute(path); Set<Byte> parts = Sets.newHashSet(Byte.valueOf(partition)); Command cmd = newCommand(CommandType.ATTR, parts, instanceMap); AttrCmd attr = new AttrCmd(path, parts); cmd.setAttr(attr); Attr result = (Attr) replica.submitCommand(cmd); Response r = new Response(replica.getInstanceMap()); r.setGetattr(result); return r; }
public void setErrResponse(Exception ex, Response response) { if (ex instanceof java.sql.SQLException || ex instanceof com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException || ex instanceof org.springframework.jdbc.BadSqlGrammarException || ex instanceof org.springframework.dao.InvalidDataAccessApiUsageException || ex instanceof org.springframework.dao.DataAccessException || ex instanceof org.springframework.web.util.NestedServletException || ex instanceof com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException) { response.setResponseMsg(ex.getMessage()); response.setResponseStatus(ConstException.ERR_CODE_DB_ERROR); } else if (ex instanceof java.lang.NullPointerException) { response.setResponseMsg(ex.getMessage()); response.setResponseStatus(ConstException.ERR_CODE_UNKNOWN); } else if (ex instanceof ConstException) { ConstException constException = (ConstException) ex; response.setResponseMsg(constException.getMessage()); response.setResponseStatus(constException.getCode()); } else if (ex instanceof java.lang.IllegalThreadStateException) { response.setResponseMsg(ex.getMessage()); response.setResponseStatus(ConstException.ERR_CODE_INVALID_THREAD_STOP); } else { setErrResponse(ex, response, ConstException.ERR_CODE_UNKNOWN); } }