Example usage for java.net HttpURLConnection HTTP_GONE

List of usage examples for java.net HttpURLConnection HTTP_GONE

Introduction

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

Prototype

int HTTP_GONE

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

Click Source Link

Document

HTTP Status-Code 410: Gone.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL("http://www.google.coom").openConnection();
    con.setRequestMethod("HEAD");
    System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_GONE);
}

From source file:nz.skytv.example.SwaggerApplication.java

@ApiOperation(value = "Delete a books", notes = "Delete a book.", response = Book.class, tags = { "book" })
@ApiResponses({ @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Book deleted successfully"),
        @ApiResponse(code = HttpURLConnection.HTTP_GONE, message = "Not found") })
@RequestMapping(value = { "/rest/book" }, method = RequestMethod.DELETE)
void deleteBook(@ApiParam(value = "Book isbn", required = true) @RequestParam("isbn") final String isbn) {
    LOG.debug("delete {}", isbn);
}

From source file:com.datos.vfs.provider.http.HttpFileObject.java

/**
 * Determines the type of this file.  Must not return null.  The return
 * value of this method is cached, so the implementation can be expensive.
 *///from  www . j  av  a  2  s  . c o m
@Override
protected FileType doGetType() throws Exception {
    // Use the HEAD method to probe the file.
    final int status = this.getHeadMethod().getStatusCode();
    if (status == HttpURLConnection.HTTP_OK
            || status == HttpURLConnection.HTTP_BAD_METHOD /* method is bad, but resource exist */) {
        return FileType.FILE;
    } else if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_GONE) {
        return FileType.IMAGINARY;
    } else {
        throw new FileSystemException("vfs.provider.http/head.error", getName(), Integer.valueOf(status));
    }
}

From source file:com.datos.vfs.provider.webdav.WebdavFileObject.java

/**
 * Execute a 'Workspace' operation./*from   ww  w  .  j av a 2s. co m*/
 *
 * @param method The DavMethod to invoke.
 * @throws FileSystemException If an error occurs.
 */
private void execute(final DavMethod method) throws FileSystemException {
    try {
        final int status = fileSystem.getClient().executeMethod(method);
        if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_GONE) {
            throw new FileNotFoundException(method.getURI());
        }
        method.checkSuccess();
    } catch (final FileSystemException fse) {
        throw fse;
    } catch (final IOException e) {
        throw new FileSystemException(e);
    } catch (final DavException e) {
        throw ExceptionConverter.generate(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.apache.hadoop.mapred.TestWebUIAuthorization.java

private void checkAuthorizationForJobHistoryPages(Properties props) throws Exception {
    setupGroupsProvider();//from  w  w  w  .  j a v a  2 s .  c  o  m
    props.setProperty("hadoop.http.filter.initializers", DummyFilterInitializer.class.getName());

    props.setProperty(JobConf.MR_ACLS_ENABLED, String.valueOf(true));
    props.setProperty(QueueManager.toFullPropertyName("default", QueueACL.ADMINISTER_JOBS.getAclName()),
            qAdmin);
    props.setProperty(QueueManager.toFullPropertyName("default", QueueACL.SUBMIT_JOB.getAclName()),
            jobSubmitter);

    props.setProperty("dfs.permissions", "false");

    // Let us have history files on HDFS
    props.setProperty("mapred.job.tracker.history.completed.location", "historyDoneFolderOnHDFS");

    props.setProperty(JobConf.MR_ADMINS, mrAdminUser + " " + mrAdminGroup);

    startCluster(true, props);
    MiniMRCluster cluster = getMRCluster();
    int infoPort = cluster.getJobTrackerRunner().getJobTrackerInfoPort();

    JobConf conf = new JobConf(cluster.createJobConf());
    conf.set(JobContext.JOB_ACL_VIEW_JOB, viewColleague + " group3");

    JobTracker jobTracker = getMRCluster().getJobTrackerRunner().getJobTracker();

    //Initialize history server, if need to be started in standalone mode
    String jhUrlPrefix = JobHistoryServer.getHistoryUrlPrefix(jobTracker.conf);
    String jobHistoryUrl;
    if ("false".equals(props.getProperty(JobHistoryServer.MAPRED_HISTORY_SERVER_EMBEDDED, "true"))) {
        JobHistoryServer historyServer = new JobHistoryServer(
                cluster.getJobTrackerRunner().getJobTracker().conf);
        historyServer.start();
        jobHistoryUrl = jhUrlPrefix;
    } else {
        jobHistoryUrl = "http://" + JobHistoryServer.getAddress(jobTracker.conf) + jhUrlPrefix;
    }

    // Let us add group1 and group3 to modify-job-acl. So modifyColleague and
    // viewAndModifyColleague will be able to modify the job
    conf.set(JobContext.JOB_ACL_MODIFY_JOB, " group1,group3");

    final SleepJob sleepJob = new SleepJob();
    final JobConf jobConf = new JobConf(conf);
    sleepJob.setConf(jobConf);
    UserGroupInformation jobSubmitterUGI = UserGroupInformation.createRemoteUser(jobSubmitter);
    RunningJob job = jobSubmitterUGI.doAs(new PrivilegedExceptionAction<RunningJob>() {
        public RunningJob run() throws Exception {
            JobClient jobClient = new JobClient(jobConf);
            SleepJob sleepJob = new SleepJob();
            sleepJob.setConf(jobConf);
            JobConf jobConf = sleepJob.setupJobConf(1, 0, 1000, 1, 1000, 1000);
            RunningJob runningJob = jobClient.runJob(jobConf);
            return runningJob;
        }
    });

    JobID jobid = job.getID();

    JobInProgress jip = jobTracker.getJob(jobid);
    JobConf finalJobConf = jip.getJobConf();
    Path doneDir = JobHistory.getCompletedJobHistoryLocation();

    // Wait for history file to be written
    while (TestJobHistory.getDoneFile(finalJobConf, jobid, doneDir) == null) {
        Thread.sleep(2000);
    }

    Path historyFilePath = new Path(doneDir, JobHistory.JobInfo.getDoneJobHistoryFileName(finalJobConf, jobid));

    String urlEncodedHistoryFileName = URLEncoder.encode(historyFilePath.toString());

    // validate access of jobdetails_history.jsp
    String jobDetailsJSP = jobHistoryUrl + "/jobdetailshistory.jsp?logFile=" + urlEncodedHistoryFileName;
    validateViewJob(jobDetailsJSP, "GET");

    // validate accesses of jobtaskshistory.jsp
    String jobTasksJSP = jobHistoryUrl + "/jobtaskshistory.jsp?logFile=" + urlEncodedHistoryFileName;
    String[] taskTypes = new String[] { "JOb_SETUP", "MAP", "REDUCE", "JOB_CLEANUP" };
    String[] states = new String[] { "all", "SUCCEEDED", "FAILED", "KILLED" };
    for (String taskType : taskTypes) {
        for (String state : states) {
            validateViewJob(jobTasksJSP + "&taskType=" + taskType + "&status=" + state, "GET");
        }
    }

    JobHistory.JobInfo jobInfo = new JobHistory.JobInfo(jobid.toString());

    DefaultJobHistoryParser.JobTasksParseListener l = new DefaultJobHistoryParser.JobTasksParseListener(
            jobInfo);
    JobHistory.parseHistoryFromFS(historyFilePath.toString().substring(5), l,
            historyFilePath.getFileSystem(conf));

    Map<String, org.apache.hadoop.mapred.JobHistory.Task> tipsMap = jobInfo.getAllTasks();

    for (String tip : tipsMap.keySet()) {
        // validate access of taskdetailshistory.jsp
        validateViewJob(jobHistoryUrl + "/taskdetailshistory.jsp?logFile=" + urlEncodedHistoryFileName
                + "&tipid=" + tip.toString(), "GET");

        Map<String, TaskAttempt> attemptsMap = tipsMap.get(tip).getTaskAttempts();
        for (String attempt : attemptsMap.keySet()) {

            // validate access to taskstatshistory.jsp
            validateViewJob(jobHistoryUrl + "/taskstatshistory.jsp?attemptid=" + attempt.toString()
                    + "&logFile=" + urlEncodedHistoryFileName, "GET");

            // validate access to tasklogs
            String taskLogURL = TaskLogServlet.getTaskLogUrl("localhost",
                    attemptsMap.get(attempt).get(Keys.HTTP_PORT), attempt.toString());
            validateViewJob(taskLogURL, "GET");
        }
    }

    // For each tip, let us test the effect of deletion of job-acls.xml file and
    // deletion of task log dir for each of the attempts of the tip.

    // delete job-acls.xml file from the job userlog dir and verify
    // if unauthorized users can view task logs of each attempt.
    Path jobACLsFilePath = new Path(TaskLog.getJobDir(jobid).toString(), TaskTracker.jobACLsFile);
    new File(jobACLsFilePath.toUri().getPath()).delete();

    for (String tip : tipsMap.keySet()) {

        Map<String, TaskAttempt> attemptsMap = tipsMap.get(tip).getTaskAttempts();
        for (String attempt : attemptsMap.keySet()) {

            String taskLogURL = TaskLogServlet.getTaskLogUrl("localhost",
                    attemptsMap.get(attempt).get(Keys.HTTP_PORT), attempt.toString());

            // unauthorized users can view task logs of each attempt because
            // job-acls.xml file is deleted.
            assertEquals("Incorrect return code for " + unauthorizedUser, HttpURLConnection.HTTP_OK,
                    getHttpStatusCode(taskLogURL, unauthorizedUser, "GET"));

            // delete the whole task log dir of attempt and verify that we get
            // correct response code (i.e. HTTP_GONE) when task logs are accessed.
            File attemptLogDir = TaskLog.getAttemptDir(TaskAttemptID.forName(attempt), false);
            FileUtil.fullyDelete(attemptLogDir);
            assertEquals("Incorrect return code for " + jobSubmitter, HttpURLConnection.HTTP_GONE,
                    getHttpStatusCode(taskLogURL, jobSubmitter, "GET"));
        }
    }

    // validate access to analysejobhistory.jsp
    String analyseJobHistoryJSP = jobHistoryUrl + "/analysejobhistory.jsp?logFile=" + urlEncodedHistoryFileName;
    validateViewJob(analyseJobHistoryJSP, "GET");

    // validate access of jobconf_history.jsp
    String jobConfJSP = jobHistoryUrl + "/jobconf_history.jsp?logFile=" + urlEncodedHistoryFileName;
    validateViewJob(jobConfJSP, "GET");
}

From source file:org.forgerock.openam.forgerockrest.IdentityResource.java

private void anonymousUpdate(final ServerContext context, final ActionRequest request,
        final ResultHandler<JsonValue> handler) {
    String tokenID;//w w w  . j a  va2s  .c  o m
    String confirmationId;
    String username;
    String newPassword;
    final JsonValue jVal = request.getContent();

    try {
        tokenID = jVal.get(TOKEN_ID).asString();
        confirmationId = jVal.get(CONFIRMATION_ID).asString();
        username = jVal.get(USERNAME).asString();
        newPassword = jVal.get(USER_PASSWORD).asString();

        if (username == null || username.isEmpty()) {
            throw new BadRequestException("username not provided");
        }
        if (newPassword == null || newPassword.isEmpty()) {
            throw new BadRequestException("new password not provided");
        }

        validateToken(tokenID, realm, username, confirmationId);

        // update Identity
        SSOToken tok = RestUtils.getToken();
        Token admin = new Token();
        admin.setId(tok.getTokenID().toString());

        // Update instance with new password value
        if (updateInstance(admin, json(object(field(USERNAME, username), field(USER_PASSWORD, newPassword))),
                handler)) {
            // Only remove the token if the update was successful, errors will be set in the handler.
            try {
                // Even though the generated token will eventually timeout, delete it after a successful read
                // so that the reset password request cannot be made again using the same token.
                cts.delete(tokenID);
            } catch (DeleteFailedException e) {
                // Catch this rather than letting it stop the process as it is possible that between successfully
                // reading and deleting, the token has expired.
                if (RestDispatcher.debug.messageEnabled()) {
                    RestDispatcher.debug.message("IdentityResource.anonymousUpdate(): Deleting token " + tokenID
                            + " after a successful read failed due to " + e.getMessage(), e);
                }
            }
        }
    } catch (BadRequestException be) {
        RestDispatcher.debug.error("IdentityResource.anonymousUpdate():" + be.getMessage());
        handler.handleError(be);
    } catch (CoreTokenException cte) {
        RestDispatcher.debug.error("IdentityResource.anonymousUpdate():" + cte.getMessage());
        handler.handleError(new NotFoundException(cte.getMessage()));
    } catch (NotFoundException nfe) {
        RestDispatcher.debug.error("IdentityResource.anonymousUpdate():" + nfe.getMessage());
        handler.handleError(ResourceException.getException(HttpURLConnection.HTTP_GONE, nfe.getMessage(), nfe));
    } catch (Exception e) {
        RestDispatcher.debug.error("IdentityResource.anonymousUpdate():" + e.getMessage());
        handler.handleError(new NotFoundException(e.getMessage()));
    }

}

From source file:poisondog.vfs.http.HttpMission.java

@Override
public Integer execute(HttpMethod method) throws FileNotFoundException, IOException {
    if (!mUsername.isEmpty()) {
        mClient.setHttpClient(create(mUsername, mPassword));
    }//w  ww.ja v  a2  s.  co  m
    mClient.getHttpConnectionManager().getParams().setSoTimeout(20000);

    int status = mClient.executeMethod(method);
    if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_GONE) {
        throw new FileNotFoundException();
    }
    return status;
}