Example usage for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED

List of usage examples for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.

Prototype

int SC_UNAUTHORIZED

To view the source code for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.

Click Source Link

Document

Status code (401) indicating that the request requires HTTP authentication.

Usage

From source file:io.apiman.common.servlet.AuthenticationFilter.java

/**
 * Sends a response that tells the client that authentication is required.
 * @param response//from w ww. ja v  a  2s  . co m
 * @throws IOException 
 */
private void sendAuthResponse(HttpServletResponse response) throws IOException {
    response.setHeader("WWW-Authenticate", String.format("BASIC realm=\"%1$s\"", realm)); //$NON-NLS-1$ //$NON-NLS-2$
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

From source file:com.janrain.backplane.server.Backplane1Controller.java

/**
 * Handle auth errors/*  w w  w. java  2  s . c om*/
 */
@ExceptionHandler
@ResponseBody
public Map<String, String> handle(final AuthException e, HttpServletResponse response) {
    logger.error("Backplane authentication error: " + e.getMessage(), bpConfig.getDebugException(e));
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return new HashMap<String, String>() {
        {
            put(ERR_MSG_FIELD, e.getMessage());
        }
    };
}

From source file:com.janrain.backplane.provision.ProvisioningController2.java

/**
 * Handle auth errors as part of normal application flow
 *//*from   w w w.j a  va 2 s.c  om*/
@ExceptionHandler
@ResponseBody
public Map<String, String> handle(final AuthException e, HttpServletResponse response) {
    logger.info("Provisioning authentication error: " + e.getMessage());
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return new HashMap<String, String>() {
        {
            put(ERR_MSG_FIELD, e.getMessage());
        }
    };
}

From source file:com.iorga.iraj.security.AbstractSecurityFilter.java

protected void rejectGenericInvalidAccessKeyIdOrSignature(final String debugMessage,
        final HttpServletResponse httpResponse) throws IOException {
    sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid accessKeyId or signature", httpResponse,
            debugMessage);/*from   www.  ja v  a  2  s. co m*/
}

From source file:net.d53.syman.web.controller.PatientController.java

@RequestMapping(value = "/api/auth", method = RequestMethod.POST)
@ResponseBody// w  ww. ja  v  a 2s  .co m
public String APIauthenticate(@RequestParam String username, @RequestParam String password,
        HttpServletRequest request, HttpServletResponse response) {
    String token = null;
    UsernamePasswordAuthenticationToken authenticationRequest = new UsernamePasswordAuthenticationToken(
            username, password);

    authenticationRequest.setDetails(APIAuthenticationToken.API_TOKEN_IDENTIFIER);

    try {
        APIAuthenticationToken res = (APIAuthenticationToken) authenticationManager
                .authenticate(authenticationRequest);
        LOGGER.info(ToStringBuilder.reflectionToString(res));
        if (res != null) {
            token = res.getCredentials().toString();
            LOGGER.info("Generated token " + token);
            SecurityContext context = SecurityContextHolder.getContext();
            context.setAuthentication(res);
            this.securityContextRepository.saveContext(context, request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (AuthenticationException e) {
        LOGGER.info("Authentication error: " + e.getMessage());
        SecurityContextHolder.clearContext();
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
    return token;
}

From source file:com.hortonworks.registries.auth.server.TestKerberosAuthenticationHandler.java

public void testRequestWithAuthorization() throws Exception {
    String token = KerberosTestUtils.doAsClient(new Callable<String>() {
        @Override//from  w ww.j a  v  a  2  s  .c  om
        public String call() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSContext gssContext = null;
            try {
                String servicePrincipal = KerberosTestUtils.getServerPrincipal();
                Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                gssContext.requestCredDeleg(true);
                gssContext.requestMutualAuth(true);

                byte[] inToken = new byte[0];
                byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                Base64 base64 = new Base64(0);
                return base64.encodeToString(outToken);

            } finally {
                if (gssContext != null) {
                    gssContext.dispose();
                }
            }
        }
    });

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
            .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token);
    Mockito.when(request.getServerName()).thenReturn("localhost");

    AuthenticationToken authToken = handler.authenticate(request, response);

    if (authToken != null) {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);

        Assert.assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName());
        Assert.assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName()));
        Assert.assertEquals(getExpectedType(), authToken.getType());
    } else {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:com.lucidworks.security.authentication.server.KerberosAuthenticationHandler.java

/**
 * It enforces the the Kerberos SPNEGO authentication sequence returning an {@link AuthenticationToken} only
 * after the Kerberos SPNEGO sequence has completed successfully.
 * <p/>/*from   w ww  . j a  v a 2s.  co m*/
 *
 * @param request the HTTP client request.
 * @param response the HTTP client response.
 *
 * @return an authentication token if the Kerberos SPNEGO sequence is complete and valid,
 *         <code>null</code> if it is in progress (in this case the handler handles the response to the client).
 *
 * @throws IOException thrown if an IO error occurred.
 * @throws AuthenticationException thrown if Kerberos SPNEGO sequence failed.
 */
@Override
public AuthenticationToken authenticate(HttpServletRequest request, final HttpServletResponse response)
        throws IOException, AuthenticationException {
    AuthenticationToken token = null;
    String authorization = request.getHeader(KerberosAuthenticator.AUTHORIZATION);

    if (authorization == null || !authorization.startsWith(KerberosAuthenticator.NEGOTIATE)) {
        response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE, KerberosAuthenticator.NEGOTIATE);
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        if (authorization == null) {
            LOG.trace("SPNEGO starting");
        } else {
            LOG.warn("'" + KerberosAuthenticator.AUTHORIZATION + "' does not start with '"
                    + KerberosAuthenticator.NEGOTIATE + "' :  {}", authorization);
        }
    } else {
        authorization = authorization.substring(KerberosAuthenticator.NEGOTIATE.length()).trim();
        final Base64 base64 = new Base64(0);
        final byte[] clientToken = base64.decode(authorization);
        Subject serverSubject = loginContext.getSubject();
        try {
            token = Subject.doAs(serverSubject, new PrivilegedExceptionAction<AuthenticationToken>() {

                @Override
                public AuthenticationToken run() throws Exception {
                    AuthenticationToken token = null;
                    GSSContext gssContext = null;
                    GSSCredential gssCreds = null;
                    try {
                        if (PlatformName.IBM_JAVA) {
                            // IBM JDK needs non-null credentials to be passed to createContext here, with
                            // SPNEGO mechanism specified, otherwise JGSS will use its default mechanism
                            // only, which is Kerberos V5.
                            gssCreds = gssManager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME,
                                    new Oid[] { KerberosUtil.getOidInstance("GSS_SPNEGO_MECH_OID"),
                                            KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID") },
                                    GSSCredential.ACCEPT_ONLY);
                        }
                        gssContext = gssManager.createContext(gssCreds);
                        byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length);
                        if (serverToken != null && serverToken.length > 0) {
                            String authenticate = base64.encodeToString(serverToken);
                            response.setHeader(KerberosAuthenticator.WWW_AUTHENTICATE,
                                    KerberosAuthenticator.NEGOTIATE + " " + authenticate);
                        }
                        if (!gssContext.isEstablished()) {
                            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                            LOG.trace("SPNEGO in progress");
                        } else {
                            String clientPrincipal = gssContext.getSrcName().toString();
                            KerberosName kerberosName = new KerberosName(clientPrincipal);
                            String userName = kerberosName.getShortName();
                            token = new AuthenticationToken(userName, clientPrincipal, getType());
                            response.setStatus(HttpServletResponse.SC_OK);
                            LOG.trace("SPNEGO completed for principal [{}]", clientPrincipal);
                        }
                    } finally {
                        if (gssContext != null) {
                            gssContext.dispose();
                        }
                        if (gssCreds != null) {
                            gssCreds.dispose();
                        }
                    }
                    return token;
                }
            });
        } catch (PrivilegedActionException ex) {
            if (ex.getException() instanceof IOException) {
                throw (IOException) ex.getException();
            } else {
                throw new AuthenticationException(ex.getException());
            }
        }
    }
    return token;
}

From source file:com.konakart.actions.ipn.BarclaycardSmartPayHostedNotificationAction.java

public String execute() {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpServletResponse response = ServletActionContext.getResponse();

    String httpAuthStr = null;//  ww w.  j  a  v  a2s  .  c o  m
    String httpUsername = null;
    String httpPassword = null;
    ;
    String pspReference = null;
    String merchantReference = null;
    String merchantAccountCode = null;
    String eventDate = null;
    String successString = null;
    boolean success = false;
    String paymentMethod = null;
    String value = null;
    String currency = null;
    String reason = null;

    String eventCode = null;
    // String mbCurrency = null;
    String status = null;
    // String md5sig = null;
    // String orderIdString = null;

    String sessionId = null;

    KKAppEng kkAppEng = null;

    if (log.isDebugEnabled()) {
        log.debug(BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE + " Notification Action");
    }

    // Create these outside of try / catch since they are needed in the case of a general
    // exception
    IpnHistoryIf ipnHistory = new IpnHistory();
    ipnHistory.setOrderId(-1);
    ipnHistory.setModuleCode(BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE);

    try {
        if (request == null) {
            return null;
        }

        // Process the parameters sent in the callback
        StringBuffer sb = new StringBuffer();
        Enumeration<String> en = request.getParameterNames();
        while (en.hasMoreElements()) {
            String paramName = en.nextElement();
            String paramValue = request.getParameter(paramName);
            if (sb.length() > 0) {
                sb.append("\n");
            }
            sb.append(paramName);
            sb.append(" = ");
            sb.append(paramValue);

            // Capture important variables so that we can determine whether the transaction
            // was successful
            if (paramName != null) {
                if (paramName.equalsIgnoreCase("eventCode")) {
                    eventCode = paramValue;
                } else if (paramName.equalsIgnoreCase("pspReference")) {
                    pspReference = paramValue;
                } else if (paramName.equalsIgnoreCase("merchantReference")) {
                    merchantReference = paramValue;
                } else if (paramName.equalsIgnoreCase("merchantAccountCode")) {
                    merchantAccountCode = paramValue;
                } else if (paramName.equalsIgnoreCase("eventDate")) {
                    eventDate = paramValue;
                } else if (paramName.equalsIgnoreCase("success")) {
                    successString = paramValue;
                    success = Boolean.valueOf(successString);
                } else if (paramName.equalsIgnoreCase("paymentMethod")) {
                    paymentMethod = paramValue;
                } else if (paramName.equalsIgnoreCase("value")) {
                    value = paramValue;
                } else if (paramName.equalsIgnoreCase("currency")) {
                    currency = paramValue;
                } else if (paramName.equalsIgnoreCase("reason")) {
                    reason = paramValue;
                }
            }
        }

        if (log.isDebugEnabled()) {
            log.debug(BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE + " Raw Notification Data:\n"
                    + sb.toString());
            log.debug("\n    merchantAccountCode       = " + merchantAccountCode + "\n"
                    + "    eventCode                 = " + eventCode + "\n" + "    eventDate                 = "
                    + eventDate + "\n" + "    merchantReference         = " + merchantReference + "\n"
                    + "    pspReference              = " + pspReference + "\n"
                    + "    paymentMethod             = " + paymentMethod + "\n"
                    + "    amount                    = " + value + "\n" + "    currency                  = "
                    + currency + "\n" + "    success                   = " + successString + "\n"
                    + "    reason                    = " + reason);
        }

        /*
         * Get the uuid from the request so that we can look up the SSO Token
         */
        if (merchantReference == null) {
            throw new Exception(
                    "The callback from BarclaycardSmartPayHosted did not contain the 'merchantReference' parameter.");
        }

        // Get an instance of the KonaKart engine and look up the token
        kkAppEng = this.getKKAppEng(request, response);
        SSOTokenIf token = kkAppEng.getEng().getSSOToken(merchantReference, /* deleteToken */
                true);
        if (token == null) {
            throw new Exception("The SSOToken from the BarclaycardSmartPayHosted callback is null");
        }

        /*
         * Use the session of the logged in user to initialise kkAppEng
         */
        try {
            kkAppEng.getEng().checkSession(token.getSessionId());
        } catch (KKException e) {
            throw new Exception(
                    "The SessionId from the SSOToken in the BarclaycardSmartPayHosted Callback is not valid: "
                            + token.getSessionId());
        }

        // Log in the user
        kkAppEng.getCustomerMgr().loginBySession(token.getSessionId());
        sessionId = token.getSessionId();

        /*
         * Get the parameters from the token
         */
        String custom1 = token.getCustom1();
        String[] custom1Array = custom1.split("~");
        if (custom1Array == null || custom1Array.length != 3) {
            throw new Exception("Custom1 field of token doesn't contain expected data: " + token.getCustom1());
        }
        httpAuthStr = custom1Array[0];
        int orderId = Integer.parseInt(custom1Array[1]);
        String countryCode = custom1Array[2];
        httpUsername = token.getCustom2();
        httpPassword = token.getCustom3();

        if (countryCode == null) {
            log.warn("CountryCode not returned in the " + BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE
                    + " response");
        }

        ipnHistory.setOrderId(orderId);

        // If we didn't receive an eventCode, we log a warning and return
        if (eventCode == null) {
            log.warn("No eventCode returned by " + BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE);
            return null;
        }

        status = eventCode;
        if (eventCode.equals("AUTHORISATION")) {
            if (success) {
                status += " successful";
            } else {
                status += " unsuccessful";
            }
        }

        // Fill more details of the IPN history class
        ipnHistory.setGatewayResult(status);
        ipnHistory.setGatewayFullResponse(sb.toString());
        ipnHistory.setGatewayTransactionId(pspReference);

        // See if we need to send an email, by looking at the configuration
        String sendEmailsConfig = kkAppEng.getConfig(ConfigConstants.SEND_EMAILS);
        boolean sendEmail = false;
        if (sendEmailsConfig != null && sendEmailsConfig.equalsIgnoreCase("true")) {
            sendEmail = true;
        }

        // Do HTTP Authentication if required
        if (httpAuthStr != null && Boolean.valueOf(httpAuthStr)) {
            // Get Authorization header
            String auth = null;

            auth = request.getHeader("Authorization");

            // Do we allow that user?
            if (!allowUser(auth, httpUsername, httpPassword)) {
                // Not allowed, so return "unauthorized"
                response.setContentType("text/plain");
                response.setHeader("WWW-Authenticate", "BASIC realm=\"Protected Page\"");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                log.warn("Notification from " + BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE
                        + " could not be Authenticated");

                ipnHistory.setKonakartResultDescription(RET2_DESC);
                ipnHistory.setKonakartResultId(RET2);
                kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
                return null;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("Accept Notification for " + BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE);
        }

        // We always accept the Notification if we get this far
        response.setContentType("text/plain");
        response.getWriter().print("[accepted]\n");

        if (orderId < 0) {
            ipnHistory.setKonakartResultDescription(RET3_DESC);
            ipnHistory.setKonakartResultId(RET3);
            kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
            return null;
        }

        // If it's not an AUTHORISATION event, we just throw it away
        if (!eventCode.equals("AUTHORISATION")) {
            if (log.isInfoEnabled()) {
                log.info("'" + eventCode + "' notification sent from "
                        + BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE + " discarded");
            }
            return null;
        }

        // If we're about to set the order status to the current value we'll assume this is a
        // duplicate Notification from Barclaycard and not do any updates

        int currentOrderStatus = kkAppEng.getEng().getOrderStatus(sessionId, orderId);

        if (log.isDebugEnabled()) {
            log.debug("currentOrderStatus for orderId " + orderId + " = " + currentOrderStatus);
        }

        if ((success && currentOrderStatus == com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS)
                || (!success && currentOrderStatus == com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS)) {
            if (log.isDebugEnabled()) {
                log.debug("Duplicate '" + eventCode + "' notification sent from "
                        + BarclaycardSmartPayHosted.BC_SPAY_HOSTED_GATEWAY_CODE + " discarded");
            }
            return null;
        }

        ipnHistory.setKonakartResultDescription(RET0_DESC);
        ipnHistory.setKonakartResultId(RET0);
        kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);

        OrderUpdateIf updateOrder = new OrderUpdate();
        int updatedById = 0;
        try {
            updatedById = kkAppEng.getEng().checkSession(sessionId);
        } catch (Exception e) {
            log.warn("Could not derive customerId from session");
        }
        updateOrder.setUpdatedById(updatedById);

        if (success) {
            String comment = ORDER_HISTORY_COMMENT_OK + reason;
            kkAppEng.getEng().updateOrder(sessionId, orderId, com.konakart.bl.OrderMgr.PAYMENT_RECEIVED_STATUS,
                    sendEmail, comment, updateOrder);
            kkAppEng.getEng().updateInventory(sessionId, orderId);
        } else {
            String comment = ORDER_HISTORY_COMMENT_KO;
            kkAppEng.getEng().updateOrder(sessionId, orderId, com.konakart.bl.OrderMgr.PAYMENT_DECLINED_STATUS,
                    sendEmail, comment, updateOrder);
        }

        if (sendEmail) {
            sendOrderConfirmationMail(kkAppEng.getEng(), sessionId, countryCode, orderId, success);
        }

        return null;

    } catch (Exception e) {
        try {
            if (sessionId != null) {
                ipnHistory.setKonakartResultDescription(RET4_DESC);
                ipnHistory.setKonakartResultId(RET4);
                if (kkAppEng != null) {
                    kkAppEng.getEng().saveIpnHistory(sessionId, ipnHistory);
                }
            }
        } catch (KKException e1) {
            e1.printStackTrace();
        }
        e.printStackTrace();
        return null;
    } finally {
        if (sessionId != null && kkAppEng != null) {
            try {
                kkAppEng.getEng().logout(sessionId);
            } catch (KKException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.openmrs.module.metadatasharing.web.controller.PublishController.java

/**
 * Mapped to URL "ws/rest/metadatasharing/package/new.form". XML can be requested with either
 * GET or POST parameters. Parameters this takes are:
 * <ul>/*from   ww  w  .j ava  2 s . c o  m*/
 * <li>key: This must be set to 5b635b8d02812d2e1c97691cd71fc05a</li>
 * <li>type: Required. This is the fully-qualified class name of the type of object you wish to
 * export</li>
 * <li>uuids: This is a comma-separated list of uuids to export (you may specify either uuids,
 * ids, or both)</li>
 * <li>ids: This is a comma-separated list of ids to export (you may specify either uuids, ids,
 * or both)</li>
 * <li>modifiedSince: When specified, items to be returned should have had created or
 * modifications after the specified date</li>
 * </ul>
 * <br/>
 * Example:
 * 
 * <pre>
 *   ws/rest/metadatasharing/package/new.form?key=5b635b8d02812d2e1c97691cd71fc05a&type=org.openmrs.Location&ids=1,2,3&compress=true
 * </pre>
 */
@RequestMapping(value = OLD_PACKAGE_PATH + "/new")
public void getNewPackage(@RequestParam(required = false) String key, Class<?> type,
        @RequestParam(required = false) String ids, @RequestParam(required = false) String uuids,
        @RequestParam(required = false) Date modifiedSince, HttpServletResponse response)
        throws IOException, SerializationException {
    if (Boolean.valueOf(Context.getAdministrationService()
            .getGlobalProperty(MetadataSharingConsts.GP_ENABLE_ON_THE_FLY_PACKAGES, "false").trim())) {
        String accessKey = Context.getAdministrationService()
                .getGlobalProperty(MetadataSharingConsts.GP_WEBSERVICES_KEY);
        if (accessKey != null)
            accessKey = accessKey.trim();

        if (StringUtils.isBlank(accessKey) || OpenmrsUtil.nullSafeEquals(accessKey, key)) {

            try {
                Context.addProxyPrivilege(MetadataSharingConsts.MODULE_PRIVILEGE);
                //The extra privilege is needed because the Concept handler uses Context.getConceptService().
                Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPTS);

                PackageExporter exporter = MetadataSharing.getInstance().newPackageExporter();
                if (OpenmrsUtil.compareWithNullAsEarliest(new Date(), modifiedSince) > 0) {
                    if (uuids != null) {
                        String splitUuids[] = uuids.split(",");
                        for (String uuid : splitUuids) {
                            Object item = Handler.getItemByUuid(type, uuid.trim());
                            if (item != null) {
                                if (modifiedSince == null
                                        || OpenmrsUtil.compareWithNullAsEarliest(Handler.getDateChanged(item),
                                                modifiedSince) > 0) {
                                    exporter.addItem(item);
                                }
                            }
                        }
                    }

                    if (ids != null) {
                        String splitIds[] = ids.split(",");
                        for (String id : splitIds) {
                            Object item = Handler.getItemById(type, Integer.valueOf(id.trim()));
                            if (item != null) {
                                if (modifiedSince == null
                                        || OpenmrsUtil.compareWithNullAsEarliest(Handler.getDateChanged(item),
                                                modifiedSince) > 0) {
                                    exporter.addItem(item);
                                }
                            }
                        }
                    }
                }
                exporter.getPackage().setName("Package");
                exporter.getPackage().setDescription("Contains " + exporter.getPackage().getItems().size()
                        + " items of type " + type.getSimpleName());

                exporter.exportPackage();

                response.setContentType("application/zip");
                response.setHeader("Content-Disposition", "attachment; filename=\"metadata.zip\"");
                MetadataZipper zipper = new MetadataZipper();
                zipper.zipPackage(response.getOutputStream(),
                        exporter.getExportedPackage().getSerializedPackage());
            } finally {
                Context.removeProxyPrivilege(MetadataSharingConsts.MODULE_PRIVILEGE);
                Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_CONCEPTS);
            }

        } else {
            //TODO limit failed number of attempts by IP address
            sendErrorResponseAfterDelay(response, HttpServletResponse.SC_UNAUTHORIZED, "Invalid key");
        }
    } else {
        sendErrorResponseAfterDelay(response, HttpServletResponse.SC_FORBIDDEN,
                "The remote system doesn't provide the requested service");
    }
}

From source file:org.opendatakit.aggregate.externalservice.GoogleOauth2ExternalService.java

protected String executeStmt(String method, String urlString, String statement, List<NameValuePair> qparams,
        boolean isFTQuery, CallingContext cc)
        throws ServiceException, IOException, ODKExternalServiceException, GeneralSecurityException {

    if (statement == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new ODKExternalServiceException("No body supplied for POST, PATCH or PUT request");
    } else if (statement != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new ODKExternalServiceException("Body was supplied for GET or DELETE request");
    }//from   w  w  w .ja v a2  s .co m

    GenericUrl url = new GenericUrl(urlString);
    if (qparams != null) {
        for (NameValuePair param : qparams) {
            url.set(param.getName(), param.getValue());
        }
    }

    HttpContent entity = null;
    if (statement != null) {
        if (isFTQuery) {
            Map<String, String> formContent = new HashMap<String, String>();
            formContent.put("sql", statement);
            UrlEncodedContent urlEntity = new UrlEncodedContent(formContent);
            entity = urlEntity;
            HttpMediaType t = urlEntity.getMediaType();
            if (t != null) {
                t.setCharsetParameter(Charset.forName(HtmlConsts.UTF8_ENCODE));
            } else {
                t = new HttpMediaType("application", "x-www-form-urlencoded");
                t.setCharsetParameter(Charset.forName(HtmlConsts.UTF8_ENCODE));
                urlEntity.setMediaType(t);
            }
        } else {
            // the alternative -- using ContentType.create(,) throws an exception???
            // entity = new StringEntity(statement, "application/json", UTF_8);
            entity = new ByteArrayContent("application/json", statement.getBytes(HtmlConsts.UTF8_ENCODE));
        }
    }

    HttpRequest request = requestFactory.buildRequest(method, url, entity);
    HttpResponse resp = request.execute();
    String response = WebUtils.readGoogleResponse(resp);

    int statusCode = resp.getStatusCode();
    if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
        throw new ODKExternalServiceCredentialsException(response.toString() + statement);
    } else if (statusCode != HttpServletResponse.SC_OK) {
        throw new ODKExternalServiceException(response.toString() + statement);
    }

    return response;
}