Example usage for javax.servlet.http HttpServletResponse SC_FORBIDDEN

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

Introduction

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

Prototype

int SC_FORBIDDEN

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

Click Source Link

Document

Status code (403) indicating the server understood the request but refused to fulfill it.

Usage

From source file:eu.dasish.annotation.backend.rest.NotebookResource.java

/**
 * //from  w  w w . j  a v a2s .c  om
 * @param externalIdentifier the external UUID of a notebook.
 * @param maximumAnnotations the maximum amount of annotations from this notebook to output;
 * if the amount of annotations in the notebook is more than  (startAnnotations-1) + maximumAnnotations,
 * then exactly maximumAnnotations will be output, otherwise  the amount of annotations is limited by "# of annotations in the notebook" - (startAnnotation-1)
 * @param startAnnotations the index of the first annotation, min value is "1". 
 * @param orderBy the field in the table "notebook" on which annotations must be ordered.
 * @param desc if true then the annotations in the list must be ordered in descending order, otherwise in ascending order.
 * @return a {@link ReferenceList} element representing the list of annotations filtered according to the parameters.
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.APPLICATION_XML)
@Path("{notebookid: " + BackendConstants.regExpIdentifier + "}")
@Transactional(readOnly = true)
public JAXBElement<ReferenceList> getNotebookAnnotations(@PathParam("notebookid") String externalIdentifier,
        @QueryParam("maximumAnnotations") int maximumAnnotations,
        @QueryParam("startAnnotation") int startAnnotations, @QueryParam("orderBy") String orderBy,
        @QueryParam("descending") boolean desc) throws IOException {

    Number remotePrincipalID = this.getPrincipalID();
    if (remotePrincipalID == null) {
        return new ObjectFactory().createReferenceList(new ReferenceList());
    }
    try {
        Number notebookID = dbDispatcher.getResourceInternalIdentifier(UUID.fromString(externalIdentifier),
                Resource.NOTEBOOK);
        if (dbDispatcher.hasAccess(notebookID, remotePrincipalID, Access.fromValue("read"))) {
            ReferenceList annotations = dbDispatcher.getAnnotationsForNotebook(notebookID, startAnnotations,
                    maximumAnnotations, orderBy, desc);
            return new ObjectFactory().createReferenceList(annotations);
        } else {
            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
            return new ObjectFactory().createReferenceList(new ReferenceList());
        }

    } catch (NotInDataBaseException e) {
        loggerServer.debug(e.toString());
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e.toString());
        return new ObjectFactory().createReferenceList(new ReferenceList());
    }

}

From source file:net.bhira.sample.api.controller.EmployeeController.java

/**
 * Delete the instance of {@link net.bhira.sample.model.Employee} represented by given
 * employeeId. In case of an error return the error message.
 * //  w  ww. j ava  2 s .co  m
 * @param employeeId
 *            the ID for {@link net.bhira.sample.model.Employee}.
 * @param response
 *            the http response to which the results will be written.
 * @return the error message, if save was not successful.
 */
@RequestMapping(value = "/employee/{employeeId}", method = RequestMethod.DELETE)
@ResponseBody
public Callable<String> deleteEmployee(@PathVariable long employeeId, HttpServletResponse response) {
    return new Callable<String>() {
        public String call() throws Exception {
            LOG.debug("servicing DELETE employee/{}", employeeId);
            String body = "";
            try {
                boolean success = employeeService.delete(employeeId);
                LOG.debug("DELETE employee/{} status = {}", employeeId, success);
                if (!success) {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }
            } catch (Exception ex) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                body = ex.getLocalizedMessage();
                LOG.warn("Error deleting employee/{}. {}", employeeId, body);
                LOG.debug("Delete error stacktrace: ", ex);
            }
            return body;
        }
    };
}

From source file:io.warp10.standalone.StandaloneIngressHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    String token = null;//from ww  w  .  j  ava  2  s  .c om

    if (target.equals(Constants.API_ENDPOINT_UPDATE)) {
        baseRequest.setHandled(true);
    } else if (target.startsWith(Constants.API_ENDPOINT_UPDATE + "/")) {
        baseRequest.setHandled(true);
        token = target.substring(Constants.API_ENDPOINT_UPDATE.length() + 1);
    } else if (target.equals(Constants.API_ENDPOINT_META)) {
        handleMeta(target, baseRequest, request, response);
        return;
    } else {
        return;
    }

    try {
        //
        // CORS header
        //

        response.setHeader("Access-Control-Allow-Origin", "*");

        long nano = System.nanoTime();

        //
        // Extract DatalogRequest if specified
        //

        String datalogHeader = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_DATALOG));

        DatalogRequest dr = null;

        boolean forwarded = false;

        if (null != datalogHeader) {
            byte[] bytes = OrderPreservingBase64.decode(datalogHeader.getBytes(Charsets.US_ASCII));

            if (null != datalogPSK) {
                bytes = CryptoUtils.unwrap(datalogPSK, bytes);
            }

            if (null == bytes) {
                throw new IOException("Invalid Datalog header.");
            }

            TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory());

            try {
                dr = new DatalogRequest();
                deser.deserialize(dr, bytes);
            } catch (TException te) {
                throw new IOException();
            }

            token = dr.getToken();

            Map<String, String> labels = new HashMap<String, String>();
            labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                    OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
            labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
            Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_RECEIVED, labels, 1);
            forwarded = true;
        }

        //
        // TODO(hbs): Extract producer/owner from token
        //

        if (null == token) {
            token = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX));
        }

        WriteToken writeToken;

        try {
            writeToken = Tokens.extractWriteToken(token);
        } catch (WarpScriptException ee) {
            throw new IOException(ee);
        }

        String application = writeToken.getAppName();
        String producer = Tokens.getUUID(writeToken.getProducerId());
        String owner = Tokens.getUUID(writeToken.getOwnerId());

        Map<String, String> sensisionLabels = new HashMap<String, String>();
        sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer);

        long count = 0;
        long total = 0;

        File loggingFile = null;
        PrintWriter loggingWriter = null;

        try {
            if (null == producer || null == owner) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token.");
                return;
            }

            //
            // Build extra labels
            //

            Map<String, String> extraLabels = new HashMap<String, String>();

            // Add labels from the WriteToken if they exist
            if (writeToken.getLabelsSize() > 0) {
                extraLabels.putAll(writeToken.getLabels());
            }

            // Force internal labels
            extraLabels.put(Constants.PRODUCER_LABEL, producer);
            extraLabels.put(Constants.OWNER_LABEL, owner);
            // FIXME(hbs): remove me, apps should be set in all tokens now...
            if (null != application) {
                extraLabels.put(Constants.APPLICATION_LABEL, application);
                sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application);
            } else {
                // remove application label
                extraLabels.remove(Constants.APPLICATION_LABEL);
            }

            //
            // Determine if content if gzipped
            //

            boolean gzipped = false;

            if (null != request.getHeader("Content-Type")
                    && "application/gzip".equals(request.getHeader("Content-Type"))) {
                gzipped = true;
            }

            BufferedReader br = null;

            if (gzipped) {
                GZIPInputStream is = new GZIPInputStream(request.getInputStream());
                br = new BufferedReader(new InputStreamReader(is));
            } else {
                br = request.getReader();
            }

            //
            // Get the present time
            //

            Long now = TimeSource.getTime();

            //
            // Check the value of the 'now' header
            //
            // The following values are supported:
            //
            // A number, which will be interpreted as an absolute time reference,
            // i.e. a number of time units since the Epoch.
            //
            // A number prefixed by '+' or '-' which will be interpreted as a
            // delta from the present time.
            //
            // A '*' which will mean to not set 'now', and to recompute its value
            // each time it's needed.
            //

            String nowstr = null != dr ? dr.getNow()
                    : request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_NOW_HEADERX));

            if (null != nowstr) {
                if ("*".equals(nowstr)) {
                    now = null;
                } else if (nowstr.startsWith("+")) {
                    try {
                        long delta = Long.parseLong(nowstr.substring(1));
                        now = now + delta;
                    } catch (Exception e) {
                        throw new IOException("Invalid base timestamp.");
                    }
                } else if (nowstr.startsWith("-")) {
                    try {
                        long delta = Long.parseLong(nowstr.substring(1));
                        now = now - delta;
                    } catch (Exception e) {
                        throw new IOException("Invalid base timestamp.");
                    }
                } else {
                    try {
                        now = Long.parseLong(nowstr);
                    } catch (Exception e) {
                        throw new IOException("Invalid base timestamp.");
                    }
                }
            }

            //
            // Open the logging file if logging is enabled
            //

            if (null != loggingDir) {
                long nanos = null != dr ? dr.getTimestamp() : TimeSource.getNanoTime();
                StringBuilder sb = new StringBuilder();
                sb.append(Long.toHexString(nanos));
                sb.insert(0, "0000000000000000", 0, 16 - sb.length());
                sb.append("-");
                if (null != dr) {
                    sb.append(dr.getId());
                } else {
                    sb.append(datalogId);
                }

                sb.append("-");
                sb.append(dtf.print(nanos / 1000000L));
                sb.append(Long.toString(1000000L + (nanos % 1000000L)).substring(1));
                sb.append("Z");

                if (null == dr) {
                    dr = new DatalogRequest();
                    dr.setTimestamp(nanos);
                    dr.setType(Constants.DATALOG_UPDATE);
                    dr.setId(datalogId);
                    dr.setToken(token);

                    if (null == now) {
                        //
                        // We MUST force 'now', otherwise forwarded metrics will not have a
                        // coherent time. This alters the semantics slightly but make it
                        // coherent across the board.
                        //
                        now = TimeSource.getTime();
                    }
                    dr.setNow(Long.toString(now));
                }

                if (null != dr && (!forwarded || (forwarded && this.logforwarded))) {

                    //
                    // Serialize the request
                    //

                    TSerializer ser = new TSerializer(new TCompactProtocol.Factory());

                    byte[] encoded;

                    try {
                        encoded = ser.serialize(dr);
                    } catch (TException te) {
                        throw new IOException(te);
                    }

                    if (null != this.datalogPSK) {
                        encoded = CryptoUtils.wrap(this.datalogPSK, encoded);
                    }

                    encoded = OrderPreservingBase64.encode(encoded);

                    loggingFile = new File(loggingDir, sb.toString());

                    loggingWriter = new PrintWriter(new FileWriterWithEncoding(loggingFile, Charsets.UTF_8));

                    //
                    // Write request
                    //

                    loggingWriter.println(new String(encoded, Charsets.US_ASCII));
                }

                //
                // Force 'now'
                //

                now = Long.parseLong(dr.getNow());
            }

            //
            // Loop on all lines
            //

            GTSEncoder lastencoder = null;
            GTSEncoder encoder = null;

            //
            // Chunk index when archiving
            //

            do {

                String line = br.readLine();

                if (null == line) {
                    break;
                }

                line = line.trim();

                if (0 == line.length()) {
                    continue;
                }

                //
                // Ignore comments
                //

                if ('#' == line.charAt(0)) {
                    continue;
                }

                //
                // Check for pushback
                // TODO(hbs): implement the actual push back if we are over the subscribed limit
                //

                if (count % PUSHBACK_CHECK_INTERVAL == 0) {
                    Sensision.update(
                            SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_DATAPOINTS_RAW,
                            sensisionLabels, count);
                    total += count;
                    count = 0;
                }

                count++;

                try {
                    encoder = GTSHelper.parse(lastencoder, line, extraLabels, now, maxValueSize, false);
                    //nano2 += System.nanoTime() - nano0;
                } catch (ParseException pe) {
                    Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_PARSEERRORS,
                            sensisionLabels, 1);
                    throw new IOException("Parse error at '" + line + "'", pe);
                }

                if (encoder != lastencoder || lastencoder.size() > ENCODER_SIZE_THRESHOLD) {

                    //
                    // Check throttling
                    //

                    if (null != lastencoder) {

                        // 128BITS
                        lastencoder.setClassId(GTSHelper.classId(classKeyLongs, lastencoder.getName()));
                        lastencoder.setLabelsId(
                                GTSHelper.labelsId(labelsKeyLongs, lastencoder.getMetadata().getLabels()));

                        ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application,
                                lastencoder.getClassId(), lastencoder.getLabelsId());
                        ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application,
                                (int) lastencoder.getCount());
                    }

                    //
                    // Build metadata object to push
                    //

                    if (encoder != lastencoder) {
                        Metadata metadata = new Metadata(encoder.getMetadata());
                        metadata.setSource(Configuration.INGRESS_METADATA_SOURCE);
                        //nano6 += System.nanoTime() - nano0;
                        this.directoryClient.register(metadata);
                        //nano5 += System.nanoTime() - nano0;
                    }

                    if (null != lastencoder) {
                        this.storeClient.store(lastencoder);
                    }

                    if (encoder != lastencoder) {
                        lastencoder = encoder;
                    } else {
                        //lastencoder = null
                        //
                        // Allocate a new GTSEncoder and reuse Metadata so we can
                        // correctly handle a continuation line if this is what occurs next
                        //
                        Metadata metadata = lastencoder.getMetadata();
                        lastencoder = new GTSEncoder(0L);
                        lastencoder.setMetadata(metadata);
                    }
                }

                //
                // Write the line last, so we do not write lines which triggered exceptions
                //

                if (null != loggingWriter) {
                    loggingWriter.println(line);
                }
            } while (true);

            br.close();

            if (null != lastencoder && lastencoder.size() > 0) {
                // 128BITS
                lastencoder.setClassId(GTSHelper.classId(classKeyLongs, lastencoder.getName()));
                lastencoder
                        .setLabelsId(GTSHelper.labelsId(labelsKeyLongs, lastencoder.getMetadata().getLabels()));

                ThrottlingManager.checkMADS(lastencoder.getMetadata(), producer, owner, application,
                        lastencoder.getClassId(), lastencoder.getLabelsId());
                ThrottlingManager.checkDDP(lastencoder.getMetadata(), producer, owner, application,
                        (int) lastencoder.getCount());
                this.storeClient.store(lastencoder);
            }

            //
            // TODO(hbs): should we update the count in Sensision periodically so you can't trick the throttling mechanism?
            //
        } catch (WarpException we) {
            throw new IOException(we);
        } finally {
            this.storeClient.store(null);
            this.directoryClient.register(null);
            Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_DATAPOINTS_RAW,
                    sensisionLabels, count);
            Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_REQUESTS,
                    sensisionLabels, 1);
            Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_TIME_US,
                    sensisionLabels, (System.nanoTime() - nano) / 1000);

            if (null != loggingWriter) {
                Map<String, String> labels = new HashMap<String, String>();
                labels.put(SensisionConstants.SENSISION_LABEL_ID, new String(
                        OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8));
                labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType());
                Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_LOGGED, labels, 1);

                loggingWriter.close();
                loggingFile.renameTo(new File(loggingFile.getAbsolutePath() + DatalogForwarder.DATALOG_SUFFIX));
            }

            //
            // Update stats with CDN
            //

            String cdn = request.getHeader(Constants.OVH_CDN_GEO_HEADER);

            if (null != cdn) {
                sensisionLabels.put(SensisionConstants.SENSISION_LABEL_CDN, cdn);
                // Per CDN stat is updated at the end, so update with 'total' + 'count'
                Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_DATAPOINTS_RAW,
                        sensisionLabels, count + total);
                Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_REQUESTS,
                        sensisionLabels, 1);
                Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_UPDATE_TIME_US,
                        sensisionLabels, (System.nanoTime() - nano) / 1000);
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            return;
        }
    }
}

From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java

private void doUnauthorisedAction(final HttpServletResponse httpResponse) throws IOException {
    httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Not authorised to access this resource");
}

From source file:cn.vlabs.duckling.vwb.VWBContext.java

public boolean hasAccess(HttpServletResponse response) {
    boolean allowed = checkPermission(m_command.getRequiredPermission());
    if (!allowed) {
        Principal currentUser = m_session.getCurrentUser();

        try {//w  w w.ja  v  a  2  s. c  o  m
            if (m_session.isAuthenticated()) {
                log.info("User " + currentUser.getName() + " has no access - forbidden (permission="
                        + getRequiredPermission() + ")");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                log.info("User " + currentUser.getName() + " has no access - redirecting (permission="
                        + getRequiredPermission() + ")");

                String pageurl = (m_vp != null) ? Integer.toString(m_vp.getResourceId()) : "";
                String requesturl = (String) m_request.getAttribute(Attributes.REQUEST_URL);
                if (requesturl == null) {
                    requesturl = getRequestURL(m_request);
                }
                m_request.getSession().setAttribute(Attributes.REQUEST_URL, requesturl);
                response.sendRedirect(getURL(VWBContext.LOGIN, pageurl, null, false));
            }
        } catch (IOException e) {
            log.error("Redirect failed for:" + e.getMessage());
            throw new InternalVWBException(e.getMessage());
        }
    }
    return allowed;
}

From source file:org.surfnet.oaaas.auth.AuthorizationServerFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    if (handledCorsPreflightRequest(request, response)) {
        return;//from  w w  w  . ja  v a  2  s .c  o  m
    }
    /*
     * The Access Token from the Client app as documented in
     * http://tools.ietf.org/html/draft-ietf-oauth-v2#section-7
     */
    final String accessToken = getAccessToken(request);
    if (accessToken != null) {
        VerifyTokenResponse tokenResponse = getVerifyTokenResponse(accessToken);
        if (isValidResponse(tokenResponse)) {
            request.setAttribute(VERIFY_TOKEN_RESPONSE, tokenResponse);
            chain.doFilter(request, response);
            return;
        }
    }
    sendError(response, HttpServletResponse.SC_FORBIDDEN, "OAuth2 endpoint");
}

From source file:ch.entwine.weblounge.kernel.site.SiteServlet.java

/**
 * Tries to serve the request as a static resource from the bundle.
 * /*  w  ww  .  j  ava 2s . co  m*/
 * @param request
 *          the http servlet request
 * @param response
 *          the http servlet response
 * @throws ServletException
 *           if serving the request fails
 * @throws IOException
 *           if writing the response back to the client fails
 */
protected void serviceResource(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {

    Http11ResponseType responseType = null;
    String requestPath = request.getPathInfo();

    // There is also a special set of resources that we don't want to expose
    if (isProtected(requestPath)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    String bundlePath = UrlUtils.concat("/site", requestPath);

    // Does the resource exist?
    final URL url = bundle.getResource(bundlePath);
    if (url == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Load the resource from the bundle
    URLConnection connection = url.openConnection();
    String contentEncoding = connection.getContentEncoding();
    long contentLength = connection.getContentLength();
    long lastModified = connection.getLastModified();

    if (contentLength <= 0) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // final Resource resource = Resource.newResource(url);
    // if (!resource.exists()) {
    // response.sendError(HttpServletResponse.SC_NOT_FOUND);
    // return;
    // }

    // We don't allow directory listings
    // if (resource.isDirectory()) {
    // response.sendError(HttpServletResponse.SC_FORBIDDEN);
    // return;
    // }

    String mimeType = tika.detect(bundlePath);

    // Try to get mime type and content encoding from resource
    if (mimeType == null)
        mimeType = connection.getContentType();

    if (mimeType != null) {
        if (contentEncoding != null)
            mimeType += ";" + contentEncoding;
        response.setContentType(mimeType);
    }

    // Send the response back to the client
    InputStream is = connection.getInputStream();
    // InputStream is = resource.getInputStream();
    try {
        logger.debug("Serving {}", url);
        responseType = Http11ProtocolHandler.analyzeRequest(request, lastModified,
                Times.MS_PER_DAY + System.currentTimeMillis(), contentLength);
        if (!Http11ProtocolHandler.generateResponse(response, responseType, is)) {
            logger.warn("I/O error while generating content from {}", url);
        }
    } finally {
        IOUtils.closeQuietly(is);
    }

}

From source file:contestWebsite.EditRegistration.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    UserCookie userCookie = UserCookie.getCookie(req);
    boolean loggedIn = userCookie != null && userCookie.authenticate();
    if (loggedIn && userCookie.isAdmin()) {
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true));
        Key key = KeyFactory.createKey("registration", Long.parseLong(req.getParameter("key")));
        try {/*from ww w . j a  v a 2  s.  c o m*/
            Entity registration = datastore.get(key);
            Map<String, String[]> params = new HashMap<String, String[]>(req.getParameterMap());
            for (Entry<String, String[]> param : params.entrySet()) {
                if (!"studentData".equals(param.getKey())) {
                    param.setValue(new String[] { escapeHtml4(param.getValue()[0]) });
                }
            }

            if (params.get("ajax") != null && "1".equals(params.get("ajax")[0])) {
                String newValue = params.get("newValue")[0].trim();
                String modified = params.get("modified")[0];
                if ("yes".equals(params.get("account")[0]) && ("email".equals(modified)
                        || "schoolName".equals(modified) || "name".equals(modified))) {
                    Query query = new Query("user").setFilter(new FilterPredicate("user-id",
                            FilterOperator.EQUAL, registration.getProperty("email")));
                    Entity user = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0);
                    switch (modified) {
                    case "email":
                        user.setProperty("user-id", newValue.toLowerCase());
                        break;
                    case "schoolName":
                        user.setProperty("school", newValue);
                        break;
                    case "name":
                        user.setProperty("name", newValue);
                    }
                    datastore.put(user);

                    registration.setProperty(modified, newValue);
                } else {
                    registration.setProperty(modified, newValue);
                }
                datastore.put(registration);
                txn.commit();
            } else {
                if (params.containsKey("delete")) {
                    if (registration.getProperty("account").equals("yes")) {
                        Query query = new Query("user").setFilter(new FilterPredicate("user-id",
                                FilterOperator.EQUAL, registration.getProperty("email")));
                        Entity user = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0);
                        datastore.delete(user.getKey());
                    }
                    datastore.delete(registration.getKey());
                } else {
                    String schoolLevel = params.get("schoolLevel")[0];
                    String name = params.get("name")[0].trim();
                    String schoolName = params.get("schoolName")[0].trim();
                    String email = params.containsKey("email") && params.get("email")[0].length() > 0
                            ? params.get("email")[0].toLowerCase().trim()
                            : null;
                    String account = params.containsKey("account") ? params.get("account")[0] : null;

                    if ("yes".equals(registration.getProperty("account")) && "no".equals(account)) {
                        registration.setProperty("account", "no");
                        Query query = new Query("user").setFilter(new FilterPredicate("user-id",
                                FilterOperator.EQUAL, registration.getProperty("email")));
                        Entity user = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0);
                        datastore.delete(user.getKey());
                    } else if ("yes".equals(registration.getProperty("account"))) {
                        Query query = new Query("user").setFilter(new FilterPredicate("user-id",
                                FilterOperator.EQUAL, registration.getProperty("email")));
                        Entity user = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0);
                        user.setProperty("name", name);
                        user.setProperty("school", schoolName);
                        user.setProperty("schoolLevel", schoolLevel);
                        user.setProperty("user-id", email);
                        datastore.put(user);
                    }

                    registration.setProperty("registrationType", params.get("registrationType")[0]);
                    registration.setProperty("schoolName", schoolName);
                    registration.setProperty("schoolLevel", schoolLevel);
                    registration.setProperty("name", name);
                    registration.setProperty("email", email);
                    registration.setProperty("cost", Integer.parseInt(params.get("cost")[0]));
                    registration.setProperty("paid", params.get("paid")[0]);
                    registration.setProperty("classification",
                            params.containsKey("classification") ? params.get("classification")[0] : "");
                    registration.setProperty("studentData", new Text(params.get("studentData")[0]));

                    datastore.put(registration);
                }

                txn.commit();
                resp.sendRedirect("/data/registrations?updated=1");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
        } finally {
            if (txn.isActive()) {
                txn.rollback();
            }
        }
    } else {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                "Contest Administrator privileges required for that operation");
    }
}

From source file:alfio.controller.TicketController.java

@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/download-ticket", method = RequestMethod.GET)
public void generateTicketPdf(@PathVariable("eventName") String eventName,
        @PathVariable("ticketIdentifier") String ticketIdentifier, HttpServletRequest request,
        HttpServletResponse response) throws IOException, WriterException {

    Optional<Triple<Event, TicketReservation, Ticket>> oData = ticketReservationManager
            .fetchCompleteAndAssigned(eventName, ticketIdentifier);
    if (!oData.isPresent()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;/*from   w w w.  j a  v a  2s  . co m*/
    }
    Triple<Event, TicketReservation, Ticket> data = oData.get();

    Ticket ticket = data.getRight();

    response.setContentType("application/pdf");
    response.addHeader("Content-Disposition", "attachment; filename=ticket-" + ticketIdentifier + ".pdf");
    try (OutputStream os = response.getOutputStream()) {
        PdfBoxRenderer renderer = preparePdfTicket(request, data.getLeft(), data.getMiddle(), ticket)
                .generate(ticket);
        if (renderer != null) {
            renderer.createPDF(os);
        }
    }
}

From source file:com.fluidops.iwb.server.SparqlServlet.java

/**
 * Retrieve the query from request, do the token based security check and
 * evaluate the query.// ww w  . j  a  va2 s  .  c o m
 * 
 * @param req
 * @param resp
 * @throws IOException 
 */
protected void handle(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    // for this servlet we do not use XSS Filter, any output must be controlled.
    if (req instanceof XssSafeHttpRequest) {
        req = ((XssSafeHttpRequest) req).getXssUnsafeHttpRequest();
    }

    String queryString = null;
    try {

        ServletOutputStream outputStream = resp.getOutputStream();

        queryString = getQueryFromRequest(req);

        boolean openLocalAccess = Config.getConfig().getOpenSparqlServletForLocalAccess()
                && (req.getRemoteAddr().equals("127.0.0.1") || req.getRemoteAddr().equals("localhost"));

        if (queryString == null) {
            if (!openLocalAccess
                    && !EndpointImpl.api().getUserManager().hasQueryRight(SparqlQueryType.SELECT, null)) {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Not enough rights to execute query.");
                return;
            }

            // Need to check the type of browser, because the Flint SPARQL editor does not support IE 8.0.
            // Added explicitly as a request parameter because
            // by default IE10 uses compatibility mode when accessing an intranet page
            // and it is recognised as IE 8.0 on the server side
            if (!Boolean.valueOf(req.getParameter("useIE8Fallback")))
                printQueryInterface(req, resp, outputStream, "com/fluidops/iwb/server/sparqlinterface");
            else
                printQueryInterface(req, resp, outputStream,
                        "com/fluidops/iwb/server/sparqlinterface-ie8-fallback");
            return;
        }

        //check if the query is about exporting context data
        String qType = req.getParameter("queryType");
        if ("context".equals(qType)) {
            if (!openLocalAccess
                    && !EndpointImpl.api().getUserManager().hasQueryRight(SparqlQueryType.SELECT, null)) {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Not enough rights to execute query.");
                return;
            }
            Boolean exportContextMetaData = Boolean.parseBoolean(req.getParameter("exportContextMetaData"));
            exportContexts(queryString, req, resp, outputStream, exportContextMetaData);
            return;
        }

        //////////////////SECURITY CHECK/////////////////////////
        String securityToken = req.getParameter("st");
        FromStringQueryBuilder<? extends Operation> queryBuilder = QueryBuilder.create(queryString);
        final SparqlQueryType queryType = queryBuilder.getQueryType();
        if (!openLocalAccess && !EndpointImpl.api().getUserManager().hasQueryPrivileges(queryString, queryType,
                securityToken)) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Not enough rights to execute query.");
            return;
        }

        // redirect format=auto to search servlet (for SELECT+CONSTRUCT)
        String format = req.getParameter("format");
        if ("auto".equals(format)
                && (queryType == SparqlQueryType.SELECT || queryType == SparqlQueryType.CONSTRUCT)) {
            handleForward(req, resp);
            return;
        }

        handleQuery(queryBuilder, req, resp, outputStream);

    } catch (MalformedQueryException e) {
        error(resp, 400, "Malformed query: \n\n" + queryString + "\n\n" + e.getMessage());
        return;
    } catch (IOException e) {
        log.error("Error: ", e);
        throw e;
    }
}