List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED
int HTTP_UNAUTHORIZED
To view the source code for java.net HttpURLConnection HTTP_UNAUTHORIZED.
Click Source Link
From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java
/** * Get an action data with specific ID from database * @param appId applicationId//from w w w .j a va 2s . c o m * @param actionId action id * @return HttpResponse returned as JSON object */ @GET @Path("/{appId}/{actionId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found an action"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") }) @ApiOperation(value = "Find action for specific App ID and action ID", notes = "Returns a action", response = ActionModel.class, authorizations = @Authorization(value = "api_key")) public HttpResponse getActionWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId, @ApiParam(value = "Action ID") @PathParam("actionId") String actionId) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/actions/" + appId + "/" + actionId); long randomLong = new Random().nextLong(); //To be able to match ActionModel action = null; Connection conn = null; JSONObject objResponse = new JSONObject(); UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong); try { try { if (!actionAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot get action. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (SQLException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot get action. Cannot check whether application ID exist or not. Database error. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } if (!actionAccess.isActionIdExist(conn, appId, actionId)) { objResponse.put("message", "Cannot get action. Action not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } action = actionAccess.getActionWithId(conn, appId, actionId); if (action != null) { ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); String actionString = objectMapper.writeValueAsString(action); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId); return new HttpResponse(actionString, HttpURLConnection.HTTP_OK); } else { objResponse.put("message", "Cannot get action. Cannot find badge with " + actionId); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot get action. DB Error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (JsonProcessingException e) { e.printStackTrace(); objResponse.put("message", "Cannot get action. JSON processing error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot get action. DB Error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } // always close connections finally { try { conn.close(); } catch (SQLException e) { logger.printStackTrace(e); } } }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java
public ListFile list(String sessionId, String dataspacePath, String pathname) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)).append("data/").append(dataspacePath).append('/'); ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory) .build();/*from w w w . j av a 2 s . co m*/ ResteasyWebTarget target = client.target(uriTmpl.toString()).path(pathname).queryParam("comp", "list"); Response response = null; try { response = target.request().header("sessionid", sessionId).get(); if (response.getStatus() != HttpURLConnection.HTTP_OK) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Cannot list the specified location: %s", pathname), response); } } return response.readEntity(ListFile.class); } finally { if (response != null) { response.close(); } } }
From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java
/** * Get an achievement data with specific ID from database * @param appId applicationId/*from w w w. java 2 s . c o m*/ * @param achievementId achievement id * @return HttpResponse returned as JSON object */ @GET @Path("/{appId}/{achievementId}") @Produces(MediaType.APPLICATION_JSON) @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Found an achievement"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Error"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") }) @ApiOperation(value = "getAchievementWithId", notes = "Get achievement data with specified ID", response = AchievementModel.class) public HttpResponse getAchievementWithId(@ApiParam(value = "Application ID") @PathParam("appId") String appId, @ApiParam(value = "Achievement ID") @PathParam("achievementId") String achievementId) { // Request log L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "GET " + "gamification/achievements/" + appId + "/" + achievementId); long randomLong = new Random().nextLong(); //To be able to match AchievementModel achievement = null; Connection conn = null; JSONObject objResponse = new JSONObject(); UserAgent userAgent = (UserAgent) getContext().getMainAgent(); String name = userAgent.getLoginName(); if (name.equals("anonymous")) { return unauthorizedMessage(); } try { conn = dbm.getConnection(); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_16, "" + randomLong); try { try { if (!achievementAccess.isAppIdExist(conn, appId)) { objResponse.put("message", "Cannot get achievement detail. App not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (SQLException e1) { e1.printStackTrace(); objResponse.put("message", "Cannot get achievement detail. Cannot check whether application ID exist or not. Database error. " + e1.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } if (!achievementAccess.isAchievementIdExist(conn, appId, achievementId)) { objResponse.put("message", "Cannot get achievement detail. Achievement not found"); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } achievement = achievementAccess.getAchievementWithId(conn, appId, achievementId); if (achievement == null) { objResponse.put("message", "Achievement Null, Cannot find achievement with " + achievementId); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } ObjectMapper objectMapper = new ObjectMapper(); //Set pretty printing of json objectMapper.enable(SerializationFeature.INDENT_OUTPUT); String achievementString = objectMapper.writeValueAsString(achievement); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_17, "" + randomLong); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_26, "" + name); L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_27, "" + appId); return new HttpResponse(achievementString, HttpURLConnection.HTTP_OK); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot get achievement detail. DB Error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST); } } catch (JsonProcessingException e) { e.printStackTrace(); objResponse.put("message", "Cannot get achievement detail. JSON processing error. " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR); } catch (SQLException e) { e.printStackTrace(); objResponse.put("message", "Cannot get achievement. Failed to fetch " + achievementId + ". " + e.getMessage()); L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message")); return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR); } }
From source file:org.openrdf.http.client.HTTPClient.java
public void sendUpdate(QueryLanguage ql, String update, String baseURI, Dataset dataset, boolean includeInferred, Binding... bindings) throws IOException, RepositoryException, MalformedQueryException, UnauthorizedException, QueryInterruptedException { HttpMethod method = getUpdateMethod(ql, update, baseURI, dataset, includeInferred, bindings); try {//from ww w . j a v a 2 s.c om int httpCode = httpClient.executeMethod(method); if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new UnauthorizedException(); } else if (!is2xx(httpCode)) { ErrorInfo errInfo = ErrorInfo.parse(method.getResponseBodyAsString()); if (errInfo.getErrorType() == ErrorType.MALFORMED_QUERY) { throw new MalformedQueryException(errInfo.getErrorMessage()); } else { throw new RepositoryException("Failed to execute update: " + errInfo); } } } finally { releaseConnection(method); } }
From source file:org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerRestClient.java
public Map<String, Object> metadata(String sessionId, String dataspacePath, String pathname) throws Exception { StringBuffer uriTmpl = (new StringBuffer()).append(restEndpointURL) .append(addSlashIfMissing(restEndpointURL)).append("data/").append(dataspacePath) .append(escapeUrlPathSegment(pathname)); ResteasyClient client = new ResteasyClientBuilder().httpEngine(httpEngine).providerFactory(providerFactory) .build();//from ww w. j a va2 s. c o m ResteasyWebTarget target = client.target(uriTmpl.toString()); Response response = null; try { response = target.request().header("sessionid", sessionId).head(); if (response.getStatus() != HttpURLConnection.HTTP_OK) { if (response.getStatus() == HttpURLConnection.HTTP_UNAUTHORIZED) { throw new NotConnectedRestException("User not authenticated or session timeout."); } else { throwException(String.format("Cannot get metadata from %s in %s.", pathname, dataspacePath), response); } } MultivaluedMap<String, Object> headers = response.getHeaders(); Map<String, Object> metaMap = Maps.newHashMap(); if (headers.containsKey(HttpHeaders.LAST_MODIFIED)) { metaMap.put(HttpHeaders.LAST_MODIFIED, headers.getFirst(HttpHeaders.LAST_MODIFIED)); } return metaMap; } finally { if (response != null) { response.close(); } } }
From source file:org.apache.hadoop.hbase.http.TestHttpServer.java
/** * Verify the administrator access for /logs, /stacks, /conf, /logLevel and * /metrics servlets.//from w w w .jav a2 s . c o m * * @throws Exception */ @Test @Ignore public void testAuthorizationOfDefaultServlets() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, true); conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_INSTRUMENTATION_REQUIRES_ADMIN, true); conf.set(HttpServer.FILTER_INITIALIZERS_PROPERTY, DummyFilterInitializer.class.getName()); conf.set(CommonConfigurationKeys.HADOOP_SECURITY_GROUP_MAPPING, MyGroupsProvider.class.getName()); Groups.getUserToGroupsMappingService(conf); MyGroupsProvider.clearMapping(); MyGroupsProvider.mapping.put("userA", Arrays.asList("groupA")); MyGroupsProvider.mapping.put("userB", Arrays.asList("groupB")); MyGroupsProvider.mapping.put("userC", Arrays.asList("groupC")); MyGroupsProvider.mapping.put("userD", Arrays.asList("groupD")); MyGroupsProvider.mapping.put("userE", Arrays.asList("groupE")); HttpServer myServer = new HttpServer.Builder().setName("test").addEndpoint(new URI("http://localhost:0")) .setFindPort(true).setConf(conf).setACL(new AccessControlList("userA,userB groupC,groupD")).build(); myServer.setAttribute(HttpServer.CONF_CONTEXT_ATTRIBUTE, conf); myServer.start(); String serverURL = "http://" + NetUtils.getHostPortString(myServer.getConnectorAddress(0)) + "/"; for (String servlet : new String[] { "conf", "logs", "stacks", "logLevel", "metrics" }) { for (String user : new String[] { "userA", "userB", "userC", "userD" }) { assertEquals(HttpURLConnection.HTTP_OK, getHttpStatusCode(serverURL + servlet, user)); } assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getHttpStatusCode(serverURL + servlet, "userE")); } myServer.stop(); }
From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java
private GzipGetMethod connectInternal(String requestURL, boolean gzip, IProgressMonitor monitor, String eTagValue) throws IOException, CoreException { monitor = Policy.monitorFor(monitor); hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor); for (int attempt = 0; attempt < 2; attempt++) { // force authentication authenticate(monitor);// ww w .j av a2s.c om GzipGetMethod getMethod = new GzipGetMethod(WebUtil.getRequestPath(requestURL), gzip); if (requestURL.contains(QUERY_DELIMITER)) { getMethod.setQueryString(requestURL.substring(requestURL.indexOf(QUERY_DELIMITER))); } getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" //$NON-NLS-1$ //$NON-NLS-2$ + getCharacterEncoding()); if (eTagValue != null && eTagValue.compareTo("") != 0) { //$NON-NLS-1$ getMethod.setRequestHeader("If-None-Match", eTagValue); //$NON-NLS-1$ } // Resolves bug#195113 httpClient.getParams().setParameter("http.protocol.single-cookie-header", true); //$NON-NLS-1$ // WARNING!! Setting browser compatibility breaks Bugzilla // authentication // getMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); // getMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109); getMethod.setDoAuthentication(true); int code; try { code = WebUtil.execute(httpClient, hostConfiguration, getMethod, monitor); } catch (IOException e) { WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e)); } switch (code) { case HttpURLConnection.HTTP_OK: return getMethod; case HttpURLConnection.HTTP_NOT_MODIFIED: WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new Status(IStatus.WARNING, BugzillaCorePlugin.ID_PLUGIN, "Not changed")); //$NON-NLS-1$ case HttpURLConnection.HTTP_UNAUTHORIZED: case HttpURLConnection.HTTP_FORBIDDEN: // login or reauthenticate due to an expired session loggedIn = false; WebUtil.releaseConnection(getMethod, monitor); authenticate(monitor); break; case HttpURLConnection.HTTP_PROXY_AUTH: loggedIn = false; WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(), "Proxy authentication required")); //$NON-NLS-1$ case HttpURLConnection.HTTP_INTERNAL_ERROR: loggedIn = false; InputStream stream = getResponseStream(getMethod, monitor); ByteArrayOutputStream ou = new ByteArrayOutputStream(1024); transferData(stream, ou); WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_NETWORK, repositoryUrl.toString(), "Error = 500")); //$NON-NLS-1$ default: WebUtil.releaseConnection(getMethod, monitor); throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$ } } throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, RepositoryStatus.ERROR_REPOSITORY_LOGIN, "All connection attempts to " + repositoryUrl.toString() //$NON-NLS-1$ + " failed. Please verify connection and authentication information.")); //$NON-NLS-1$ }
From source file:com.microsoft.aad.adal.Oauth2.java
private AuthenticationResult postMessage(String requestMessage, HashMap<String, String> headers) throws IOException, AuthenticationException { AuthenticationResult result = null;//www . j a v a 2s . c om final URL authority = StringExtensions.getUrl(getTokenEndpoint()); if (authority == null) { throw new AuthenticationException(ADALError.DEVELOPER_AUTHORITY_IS_NOT_VALID_URL); } try { mWebRequestHandler.setRequestCorrelationId(mRequest.getCorrelationId()); ClientMetrics.INSTANCE.beginClientMetricsRecord(authority, mRequest.getCorrelationId(), headers); HttpWebResponse response = mWebRequestHandler.sendPost(authority, headers, requestMessage.getBytes(AuthenticationConstants.ENCODING_UTF8), "application/x-www-form-urlencoded"); if (response.getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { if (response.getResponseHeaders() != null && response.getResponseHeaders() .containsKey(AuthenticationConstants.Broker.CHALLENGE_REQUEST_HEADER)) { // Device certificate challenge will send challenge request // in 401 header. String challengeHeader = response.getResponseHeaders() .get(AuthenticationConstants.Broker.CHALLENGE_REQUEST_HEADER).get(0); Logger.v(TAG, "Device certificate challenge request:" + challengeHeader); if (!StringExtensions.IsNullOrBlank(challengeHeader)) { // Handle each specific challenge header if (StringExtensions.hasPrefixInHeader(challengeHeader, AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE)) { Logger.v(TAG, "Challenge is related to device certificate"); ChallengeResponseBuilder certHandler = new ChallengeResponseBuilder(mJWSBuilder); Logger.v(TAG, "Processing device challenge"); final ChallengeResponse challengeResponse = certHandler .getChallengeResponseFromHeader(challengeHeader, authority.toString()); headers.put(AuthenticationConstants.Broker.CHALLENGE_RESPONSE_HEADER, challengeResponse.mAuthorizationHeaderValue); Logger.v(TAG, "Sending request with challenge response"); response = mWebRequestHandler.sendPost(authority, headers, requestMessage.getBytes(AuthenticationConstants.ENCODING_UTF8), "application/x-www-form-urlencoded"); } } else { throw new AuthenticationException(ADALError.DEVICE_CERTIFICATE_REQUEST_INVALID, "Challenge header is empty"); } } else { // AAD server returns 401 response for wrong request // messages Logger.v(TAG, "401 http status code is returned without authorization header"); } } boolean isBodyEmpty = TextUtils.isEmpty(response.getBody()); if (!isBodyEmpty) { // Protocol related errors will read the error stream and report // the error and error description Logger.v(TAG, "Token request does not have exception"); result = processTokenResponse(response); ClientMetrics.INSTANCE.setLastError(null); } if (result == null) { // non-protocol related error String errMessage = isBodyEmpty ? "Status code:" + response.getStatusCode() : response.getBody(); Logger.e(TAG, "Server error message", errMessage, ADALError.SERVER_ERROR); throw new AuthenticationException(ADALError.SERVER_ERROR, errMessage); } else { ClientMetrics.INSTANCE.setLastErrorCodes(result.getErrorCodes()); } } catch (UnsupportedEncodingException e) { ClientMetrics.INSTANCE.setLastError(null); Logger.e(TAG, e.getMessage(), "", ADALError.ENCODING_IS_NOT_SUPPORTED, e); throw e; } catch (IOException e) { ClientMetrics.INSTANCE.setLastError(null); Logger.e(TAG, e.getMessage(), "", ADALError.SERVER_ERROR, e); throw e; } finally { ClientMetrics.INSTANCE.endClientMetricsRecord(ClientMetricsEndpointType.TOKEN, mRequest.getCorrelationId()); } return result; }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Fetches the list of friend data updates from the server * /*from www . j av a 2 s .co m*/ * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account, String auth_url, String authtoken, long serverSyncState/*Date lastUpdated*/, String type_contact) throws JSONException, ParseException, IOException, AuthenticationException { ArrayList<User> friendList = new ArrayList<User>(); ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_OPERATION, "sync")); params.add(new BasicNameValuePair(PARAM_SESSIONNAME, sessionName)); if (serverSyncState == 0) params.add(new BasicNameValuePair("modifiedTime", "878925701")); // il y a 14 ans.... else params.add(new BasicNameValuePair("modifiedTime", String.valueOf(serverSyncState))); params.add(new BasicNameValuePair("elementType", type_contact)); // "Accounts,Leads , Contacts... Log.d(TAG, "fetchFriendUpdates"); // params.add(new BasicNameValuePair(PARAM_QUERY, "select firstname,lastname,mobile,email,homephone,phone from Contacts;")); // if (lastUpdated != null) { // final SimpleDateFormat formatter = // new SimpleDateFormat("yyyy/MM/dd HH:mm"); // formatter.setTimeZone(TimeZone.getTimeZone("UTC")); // params.add(new BasicNameValuePair(PARAM_UPDATED, formatter // .format(lastUpdated))); // } // HTTP GET REQUEST URL url = new URL(auth_url + "/webservice.php?" + URLEncodedUtils.format(params, "utf-8")); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setRequestProperty("accept", "application/json"); con.setUseCaches(false); con.setAllowUserInteraction(false); int timeout = 10000; // si tiemout pas assez important la connection echouait =>IOEXception con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); LastFetchOperationStatus = true; if (status == HttpURLConnection.HTTP_OK) { // Succesfully connected to the samplesyncadapter server and // authenticated. // Extract friends data in json format. BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); String response = sb.toString(); Log.i(TAG, "--response--"); // <Hack> to bypass vtiger 5.4 webservice bug: int idx = response.indexOf("{\"success"); response = response.substring(idx); Log.i(TAG, response); // </Hack> Log.i(TAG, "--response end--"); JSONObject result = new JSONObject(response); String success = result.getString("success"); Log.i(TAG, "success is" + success); if (success == "true") { Log.i(TAG, result.getString("result")); final JSONObject data = new JSONObject(result.getString("result")); final JSONArray friends = new JSONArray(data.getString("updated")); // == VTiger updated contacts == for (int i = 0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } // == Vtiger contacts deleted === String deleted_contacts = data.getString("deleted"); Log.d(TAG, deleted_contacts); Log.d(TAG, deleted_contacts.substring(deleted_contacts.indexOf("["))); List<String> items = Arrays.asList( deleted_contacts.substring(deleted_contacts.indexOf("[") + 1, deleted_contacts.indexOf("]")) .split("\\s*,\\s*")); for (int ii = 0; ii < items.size(); ii++) { Log.d(TAG, items.get(ii)); if (items.get(ii).startsWith("\"4x")) // this is a contact { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"contact_no\":\"CON1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"3x")) // this is an account { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"account_no\":\"ACC1\"}"); friendList.add(User.valueOf(item)); } if (items.get(ii).startsWith("\"2x")) // this is a lead { //Log.d(TAG,"{\"id\":"+items.get(ii)+",\"d\":true,\"contact_no\":1}"); JSONObject item = new JSONObject( "{\"id\":" + items.get(ii) + ",\"d\":true,\"lead_no\":\"LEA1\"}"); friendList.add(User.valueOf(item)); } } } else { LastFetchOperationStatus = false; // FIXME: else false... // possible error code : //{"success":false,"error":{"code":"AUTHENTICATION_REQUIRED","message":"Authencation required"}} // throw new AuthenticationException(); } } else { if (status == HttpURLConnection.HTTP_UNAUTHORIZED) { LastFetchOperationStatus = false; Log.e(TAG, "Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { LastFetchOperationStatus = false; Log.e(TAG, "Server error in fetching remote contacts: "); throw new IOException(); } } return friendList; }
From source file:co.cask.cdap.client.rest.RestStreamClientTest.java
@Test public void testNotAuthorizedCreate() throws IOException { try {/*from w w w . jav a 2 s .c o m*/ streamClient.create(TestUtils.AUTH_STREAM_NAME); Assert.fail("Expected HttpFailureException"); } catch (HttpFailureException e) { Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode()); } }