Example usage for java.net HttpURLConnection HTTP_BAD_REQUEST

List of usage examples for java.net HttpURLConnection HTTP_BAD_REQUEST

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_BAD_REQUEST.

Prototype

int HTTP_BAD_REQUEST

To view the source code for java.net HttpURLConnection HTTP_BAD_REQUEST.

Click Source Link

Document

HTTP Status-Code 400: Bad Request.

Usage

From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java

private Future<Void> uploadMessage(final MqttContext ctx, final String tenant, final String deviceId,
        final Buffer payload, final Future<MessageSender> senderTracker, final String endpointName) {

    if (!isPayloadOfIndicatedType(payload, ctx.contentType())) {
        return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST,
                String.format("Content-Type %s does not match with the payload", ctx.contentType())));
    } else {//from  ww  w  . ja  v  a 2s.c  o  m

        final Future<JsonObject> tokenTracker = getRegistrationAssertion(tenant, deviceId,
                ctx.authenticatedDevice());
        final Future<TenantObject> tenantConfigTracker = getTenantConfiguration(tenant);

        return CompositeFuture.all(tokenTracker, tenantConfigTracker, senderTracker).compose(ok -> {

            if (tenantConfigTracker.result().isAdapterEnabled(getTypeName())) {

                final MessageSender sender = senderTracker.result();
                final Message downstreamMessage = newMessage(
                        ResourceIdentifier.from(endpointName, tenant, deviceId),
                        sender.isRegistrationAssertionRequired(), ctx.message().topicName(), ctx.contentType(),
                        payload, tokenTracker.result(), null);
                customizeDownstreamMessage(downstreamMessage, ctx);

                if (ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) {
                    return sender.sendAndWaitForOutcome(downstreamMessage);
                } else {
                    return sender.send(downstreamMessage);
                }
            } else {
                // this adapter is not enabled for the tenant
                return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN));
            }

        }).compose(delivery -> {

            LOG.trace(
                    "successfully processed message [topic: {}, QoS: {}] for device [tenantId: {}, deviceId: {}]",
                    ctx.message().topicName(), ctx.message().qosLevel(), tenant, deviceId);
            metrics.incrementProcessedMqttMessages(endpointName, tenant);
            onMessageSent(ctx);
            // check that the remote MQTT client is still connected before sending PUBACK
            if (ctx.deviceEndpoint().isConnected() && ctx.message().qosLevel() == MqttQoS.AT_LEAST_ONCE) {
                ctx.deviceEndpoint().publishAcknowledge(ctx.message().messageId());
            }
            return Future.<Void>succeededFuture();

        }).recover(t -> {

            if (ClientErrorException.class.isInstance(t)) {
                final ClientErrorException e = (ClientErrorException) t;
                LOG.debug(
                        "cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]: {} - {}",
                        tenant, deviceId, endpointName, e.getErrorCode(), e.getMessage());
            } else {
                LOG.debug("cannot process message for device [tenantId: {}, deviceId: {}, endpoint: {}]",
                        tenant, deviceId, endpointName, t);
                metrics.incrementUndeliverableMqttMessages(endpointName, tenant);
                onMessageUndeliverable(ctx);
            }
            return Future.failedFuture(t);
        });
    }
}

From source file:rapture.kernel.DocApiImpl.java

@Override
public DocumentMetadata getDocMeta(CallingContext context, String docUri) {
    RaptureURI internalUri = new RaptureURI(docUri, Scheme.DOCUMENT);
    Repository repository = getRepoFromCache(internalUri.getAuthority());
    if (repository == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoSuchRepo", internalUri.toAuthString())); //$NON-NLS-1$
    }//w  w  w  .  j a v  a2  s .  c  o  m
    BaseDirective directive = getDirective(internalUri, repository);
    return repository.getMeta(internalUri.getDocPath(), directive);
}

From source file:rapture.kernel.AdminApiImpl.java

@Override
public void addMetadata(CallingContext context, Map<String, String> values, Boolean overwrite) {
    if ((values == null) || values.isEmpty())
        return;//from w  w  w.j  a v a 2 s  .  c o m

    Map<String, String> metadata = context.getMetadata();
    if (metadata == null)
        metadata = new HashMap<>();
    for (String key : values.keySet()) {
        if (!overwrite && metadata.containsKey(key)) {
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    key + " exists and overwrite was disallowed");
        }
        metadata.put(key, values.get(key));
    }
    context.setMetadata(metadata);
    getEphemeralRepo().addToStage(RaptureConstants.OFFICIAL_STAGE, "session/" + context.getContext(),
            JacksonUtil.jsonFromObject(context), false);
}

From source file:org.eclipse.orion.server.tests.servlets.xfer.TransferTest.java

/**
 * Tests attempting to import and unzip a file that is not a zip file.
 *///  w w w.  j  a  v a  2 s  .co  m
@Test
public void testImportUnzipNonZipFile() throws CoreException, IOException, SAXException {
    //create a directory to upload to
    String directoryPath = "sample/testImportWithPost/path" + System.currentTimeMillis();
    createDirectory(directoryPath);

    //start the import
    URL entry = ServerTestsActivator.getContext().getBundle().getEntry("testData/importTest/junk.zip");
    File source = new File(FileLocator.toFileURL(entry).getPath());
    long length = source.length();
    InputStream in = new BufferedInputStream(new FileInputStream(source));
    PostMethodWebRequest request = new PostMethodWebRequest(getImportRequestPath(directoryPath), in,
            "application/zip");
    request.setHeaderField("Content-Length", "" + length);
    request.setHeaderField("Content-Type", "application/zip");
    setAuthentication(request);
    WebResponse postResponse = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, postResponse.getResponseCode());
}

From source file:com.microsoft.aad.adal.Oauth2.java

/**
 * extract AuthenticationResult object from response body if available
 * /*from   w  w  w  . j av a2s.  c o m*/
 * @param webResponse
 * @return
 */
private AuthenticationResult processTokenResponse(HttpWebResponse webResponse) throws AuthenticationException {
    AuthenticationResult result;
    String correlationIdInHeader = null;
    if (webResponse.getResponseHeaders() != null
            && webResponse.getResponseHeaders().containsKey(AuthenticationConstants.AAD.CLIENT_REQUEST_ID)) {
        // headers are returning as a list
        List<String> listOfHeaders = webResponse.getResponseHeaders()
                .get(AuthenticationConstants.AAD.CLIENT_REQUEST_ID);
        if (listOfHeaders != null && listOfHeaders.size() > 0) {
            correlationIdInHeader = listOfHeaders.get(0);
        }
    }

    final int statusCode = webResponse.getStatusCode();
    switch (statusCode) {
    case HttpURLConnection.HTTP_OK:
    case HttpURLConnection.HTTP_BAD_REQUEST:
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        try {
            result = parseJsonResponse(webResponse.getBody());
        } catch (final JSONException jsonException) {
            throw new AuthenticationException(ADALError.SERVER_INVALID_JSON_RESPONSE,
                    "Can't parse server response " + webResponse.getBody(), jsonException);
        }

        break;
    default:
        throw new AuthenticationException(ADALError.SERVER_ERROR,
                "Unexpected server response " + webResponse.getBody());
    }

    // Set correlationId in the result
    if (correlationIdInHeader != null && !correlationIdInHeader.isEmpty()) {
        try {
            UUID correlation = UUID.fromString(correlationIdInHeader);
            if (!correlation.equals(mRequest.getCorrelationId())) {
                Logger.w(TAG, "CorrelationId is not matching", "",
                        ADALError.CORRELATION_ID_NOT_MATCHING_REQUEST_RESPONSE);
            }

            Logger.v(TAG, "Response correlationId:" + correlationIdInHeader);
        } catch (IllegalArgumentException ex) {
            Logger.e(TAG, "Wrong format of the correlation ID:" + correlationIdInHeader, "",
                    ADALError.CORRELATION_ID_FORMAT, ex);
        }
    }

    return result;
}

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Update a badge/*from w  w w. ja v  a2s. c o  m*/
 * @param appId application id
 * @param badgeId badge id
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse returned as JSON object
 */
@PUT
@Path("/{appId}/{badgeId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Badge Updated"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error occured"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad request"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })
@ApiOperation(value = "Update a badge", notes = "A method to update a badge with details (badge ID, badge name, badge description, and badge image")
public HttpResponse updateBadge(
        @ApiParam(value = "Application ID to store a new badge", required = true) @PathParam("appId") String appId,
        @PathParam("badgeId") String badgeId,
        @ApiParam(value = "Badge detail in multiple/form-data type", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ContentParam byte[] formData) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "PUT " + "gamification/badges/" + appId + "/" + badgeId);
    long randomLong = new Random().nextLong(); //To be able to match 

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();
    String filename = null;
    byte[] filecontent = null;
    String mimeType = null;
    // Badge ID for the filesystem is appended with app id to make sure it is unique
    String badgename = null;
    String badgedescription = null;
    //boolean badgeusenotification = false;
    String badgenotificationmessage = null;
    Connection conn = null;

    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_18, "" + randomLong);

        try {
            if (!badgeAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot update badge. 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 update badge. 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);
        }
        Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType);

        if (badgeId == null) {
            objResponse.put("message", "Cannot update badge. Badge ID cannot be null");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        BadgeModel currentBadge = badgeAccess.getBadgeWithId(conn, appId, badgeId);
        if (currentBadge == null) {
            // currentBadge is null
            objResponse.put("message", "Cannot update badge. Badge not found");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

        }
        FormDataPart partBadgeName = parts.get("badgename");
        if (partBadgeName != null) {
            badgename = partBadgeName.getContent();
            if (badgename != null) {
                currentBadge.setName(badgename);
            }
        }
        FormDataPart partDescription = parts.get("badgedesc");
        if (partDescription != null) {
            // optional description text input form element
            badgedescription = partDescription.getContent();
            if (badgedescription != null) {
                currentBadge.setDescription(badgedescription);
            }
        }
        FormDataPart partFilecontent = parts.get("badgeimageinput");
        if (partFilecontent != null) {
            // these data belong to the file input form element
            filename = partFilecontent.getHeader(HEADER_CONTENT_DISPOSITION).getParameter("filename");
            byte[] filecontentbefore = partFilecontent.getContentRaw();
            mimeType = partFilecontent.getContentType();
            //                   validate input

            if (filecontentbefore != null) {
                try {
                    // in unit test, resize image will turn the image into null BufferedImage
                    // but, it works in web browser
                    FormDataPart partDev = parts.get("dev");
                    if (partDev != null) {
                        filecontent = filecontentbefore;
                    } else {
                        filecontent = resizeImage(filecontentbefore);
                    }
                    //filecontent = resizeImage(filecontentbefore);
                    storeBadgeDataToSystem(appId, badgeId, filename, filecontent, mimeType, badgedescription);
                    logger.info("upload request (" + filename + ") of mime type '" + mimeType
                            + "' with content length " + filecontent.length);

                } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException
                        | InterruptedException | TimeoutException e) {
                    e.printStackTrace();
                    objResponse.put("message",
                            "Cannot update badge. Failed to upload " + badgeId + ". " + e.getMessage());
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
                } catch (IllegalArgumentException e) {
                    objResponse.put("message",
                            "Cannot update badge. Badge image is not updated. " + e.getMessage());
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

                }
            }
        }
        FormDataPart partNotificationCheck = parts.get("badgenotificationcheck");

        if (partNotificationCheck != null) {
            currentBadge.useNotification(true);

        } else {
            currentBadge.useNotification(false);

        }
        FormDataPart partNotificationMsg = parts.get("badgenotificationmessage");

        if (partNotificationMsg != null) {
            badgenotificationmessage = partNotificationMsg.getContent();
            if (badgenotificationmessage != null) {
                currentBadge.setNotificationMessage(badgenotificationmessage);
            }
        }

        try {
            badgeAccess.updateBadge(conn, appId, currentBadge);
            objResponse.put("message", "Badge updated");
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_19, "" + randomLong);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_28, "" + name);
            L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_29, "" + appId);
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
        } catch (SQLException e) {
            e.printStackTrace();
            objResponse.put("message", "Cannot update badge. Database Error. " + e.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

        }

    } catch (MalformedStreamException e) {
        // the stream failed to follow required syntax
        objResponse.put("message", "Cannot update badge. Failed to upload " + badgeId + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    } catch (IOException e) {
        // a read or write error occurred
        objResponse.put("message", "Cannot update badge. Failed to upload " + badgeId + "." + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (SQLException e1) {
        e1.printStackTrace();
        objResponse.put("message", "Cannot update badge. Database Error. " + e1.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:rapture.kernel.DocApiImpl.java

private BaseDirective getDirective(RaptureURI internalUri, Repository repository) {
    BaseDirective directive = null;//from  ww  w. j  a v a2 s.c om

    if ((internalUri.hasVersion() || internalUri.hasAsOfTime()) && !repository.isVersioned()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("InvalidVersionURI", internalUri.toString())); //$NON-NLS-1$
    }

    if (internalUri.hasVersion()) {
        AbsoluteVersion av = new AbsoluteVersion();
        av.setVersion(internalUri.getVersion());
        directive = av;
    } else if (internalUri.hasAsOfTime()) {
        AsOfTimeDirective asOfTimeDirective = new AsOfTimeDirective();
        asOfTimeDirective.setAsOfTime(internalUri.getAsOfTime());
        directive = asOfTimeDirective;
    }

    return directive;
}

From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java

/**
 * Delete an application data with specified ID
 * @param appId applicationId/*  www  . ja  v a2  s  .co  m*/
 * @return HttpResponse with the returnString
 */
@DELETE
@Path("/data/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Delete Application", notes = "This method deletes an App")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Application Deleted"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Application not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Application not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error checking app ID exist"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database error"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error delete storage"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized") })

public HttpResponse deleteApplication(
        @ApiParam(value = "Application ID", required = true) @PathParam("appId") String appId) {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99,
            "DELETE " + "gamification/applications/data/" + appId);

    JSONObject objResponse = new JSONObject();
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }

    try {
        conn = dbm.getConnection();
        if (!applicationAccess.isAppIdExist(conn, appId)) {
            objResponse.put("message", "Cannot delete Application. App not found.");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
        try {
            if (cleanStorage(appId)) {
                //if(applicationAccess.removeApplicationInfo(appId)){

                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_12, "" + name);
                if (applicationAccess.deleteApplicationDB(conn, appId)) {
                    objResponse.put("message", "Application deleted");
                    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_13, "" + name);
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);
                }
                //}
                objResponse.put("message", "Cannot delete Application. Database error. ");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException | InterruptedException
                | TimeoutException e) {
            e.printStackTrace();
            L2pLogger.logEvent(Event.RMI_FAILED, "Failed to clean storage");
            objResponse.put("message", "RMI error. Failed to clean storage. ");
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

        }
    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot delete Application. Error checking app ID exist. " + 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);
        }
    }

    objResponse.put("message", "Cannot delete Application. Error delete storage.");
    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
}

From source file:org.betaconceptframework.astroboa.resourceapi.resource.TaxonomyResource.java

private Response getTaxonomy(String taxonomyIdOrName, Output output, String callback, String prettyPrint,
        FetchLevel fetchLevel) {/*from   w  ww .j a  v  a  2  s  .c o  m*/

    if (StringUtils.isBlank(taxonomyIdOrName)) {
        logger.warn("No Taxonomy Name provided");
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }

    try {
        String taxonomyXmlorJson = retrieveTaxonomyXMLorJSONByIdOrSystemName(taxonomyIdOrName, output,
                prettyPrint, fetchLevel);

        StringBuilder resourceRepresentation = new StringBuilder();

        if (StringUtils.isBlank(callback)) {
            resourceRepresentation.append(taxonomyXmlorJson);
        } else {
            switch (output) {
            case XML: {
                ContentApiUtils.generateXMLP(resourceRepresentation, taxonomyXmlorJson, callback);
                break;
            }
            case JSON:
                ContentApiUtils.generateJSONP(resourceRepresentation, taxonomyXmlorJson, callback);
                break;
            default: {
                ContentApiUtils.generateXMLP(resourceRepresentation, taxonomyXmlorJson, callback);
                break;
            }
            }

        }

        return ContentApiUtils.createResponse(resourceRepresentation, output, callback, null);
    } catch (Exception e) {
        logger.error("Taxonomy IdOrName: " + taxonomyIdOrName, e);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }

}

From source file:org.betaconceptframework.astroboa.resourceapi.resource.TopicResource.java

private Response getTopicInternal(String topicIdOrName, Output output, String callback, String prettyPrint,
        FetchLevel fetchLevel) {/*w w w  .  j  ava  2 s . c  o  m*/

    //OLD Method
    //return generateTopicResponseUsingTopicInstance(topicIdOrName, output,   callback);

    boolean prettyPrintEnabled = ContentApiUtils.isPrettyPrintEnabled(prettyPrint);

    try {

        StringBuilder topicAsXMLOrJSONBuilder = new StringBuilder();

        switch (output) {
        case XML: {
            String topicXML = astroboaClient.getTopicService().getTopic(topicIdOrName,
                    ResourceRepresentationType.XML, fetchLevel, prettyPrintEnabled);

            if (StringUtils.isBlank(topicXML)) {
                throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
            }

            if (StringUtils.isBlank(callback)) {
                topicAsXMLOrJSONBuilder.append(topicXML);
            } else {
                ContentApiUtils.generateXMLP(topicAsXMLOrJSONBuilder, topicXML, callback);
            }
            break;
        }
        case JSON: {
            String topicJSON = astroboaClient.getTopicService().getTopic(topicIdOrName,
                    ResourceRepresentationType.JSON, fetchLevel, prettyPrintEnabled);

            if (StringUtils.isBlank(topicJSON)) {
                throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
            }
            if (StringUtils.isBlank(callback)) {
                topicAsXMLOrJSONBuilder.append(topicJSON);
            } else {
                ContentApiUtils.generateJSONP(topicAsXMLOrJSONBuilder, topicJSON, callback);
            }
            break;
        }
        }

        return ContentApiUtils.createResponse(topicAsXMLOrJSONBuilder, output, callback, null);

    } catch (WebApplicationException wae) {
        throw wae;
    } catch (Exception e) {
        logger.error("Topic IdOrName: " + topicIdOrName, e);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }

}