Java Code Examples for java.net.HttpURLConnection#HTTP_CREATED

The following examples show how to use java.net.HttpURLConnection#HTTP_CREATED . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpMonitorManager.java    From pre-dem-android with MIT License 6 votes vote down vote up
private boolean sendRequest(String url, String content) {
        LogUtils.d(TAG, "------url = " + url + "\ncontent = " + content);

        try {
            HttpURLConnection httpConn = new HttpURLConnectionBuilder(url)
                    .setRequestMethod("POST")
                    .setHeader("Content-Type", "application/x-gzip")
                    .setHeader("Content-Encoding", "gzip")
                    .setRequestBody(content)
                    .setGzip(true)
                    .build();

            int responseCode = httpConn.getResponseCode();
            boolean successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
            return successful;
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        }
    }
 
Example 2
Source File: ALMRESTConnection.java    From xframium-java with GNU General Public License v3.0 6 votes vote down vote up
private String attachWithOctetStream( String entityUrl, byte[] fileData, String filename ) throws Exception
{

    Map<String, String> requestHeaders = new HashMap<String, String>();
    requestHeaders.put( "Slug", filename );
    requestHeaders.put( "Content-Type", "application/octet-stream" );

    ALMResponse response = httpPost( entityUrl + "/attachments", fileData, requestHeaders );

    if ( response.getStatusCode() != HttpURLConnection.HTTP_CREATED )
    {
        throw new Exception( response.toString() );
    }

    return response.getResponseHeaders().get( "Location" ).iterator().next();
}
 
Example 3
Source File: ConversionAction.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Creates a job for the RDFizer
 * @param addedId Add the ID
 * @throws IOException  Throws a IOException
 * @see
 * @since 1.0
 */
private void createJob(final int addedId) throws IOException {
	Methods m = new Methods();
    m.setLang(getLocale().getISO3Language());
 URL url = new URL(defaults.getString("createJob") + addedId);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod(defaults.getString("requestMethod.put"));
    if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
        setShowRdfizerButton(1);
        getDatsDb();
        getSubsDb();
        graphs = m.getGraphsDb();
        getTemplatesDb();  
        throw new ConnectException(MessageCatalog._00015_HTTP_ERROR_CODE
                + conn.getResponseCode());
    }
    logger.debug(MessageCatalog._00031_CONVERSION_RDFIZE_JOB);
    setShowRdfizerButton(0);
    conn.disconnect();
}
 
Example 4
Source File: GrantCmd.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * This will perform all the http request response processing related to resource creation.
 *
 * @param urlSuffix suffix that needs to be appended to the url.
 * @param payload   message payload needs to be included.
 */
void performResourceCreationOverHttp(String urlSuffix, String payload, String defaultSuccessMessage) {
    Configuration configuration = Utils.getConfiguration(password);
    HttpClient httpClient = new HttpClient(configuration);

    // do POST
    HttpRequest httpRequest = new HttpRequest(urlSuffix, payload);
    HttpResponse response = httpClient.sendHttpRequest(httpRequest, HTTP_POST);

    // handle response
    if (response.getStatusCode() == HttpURLConnection.HTTP_CREATED) {
        Message message = buildResponseMessage(response, defaultSuccessMessage);
        ResponseFormatter.printMessage(message);
    } else {
        ResponseFormatter.handleErrorResponse(buildResponseMessage(response, BROKER_ERROR_MSG));
    }
}
 
Example 5
Source File: CreateCmd.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
/**
 * This will perform all the http request response processing related to resource creation.
 *
 * @param urlSuffix suffix that needs to be appended to the url.
 * @param payload message payload needs to be included.
 */
void performResourceCreationOverHttp(String urlSuffix, String payload) {
    Configuration configuration = Utils.getConfiguration(password);
    HttpClient httpClient = new HttpClient(configuration);

    // do POST
    HttpRequest httpRequest = new HttpRequest(urlSuffix, payload);
    HttpResponse response = httpClient.sendHttpRequest(httpRequest, HTTP_POST);

    // handle response
    if (response.getStatusCode() == HttpURLConnection.HTTP_CREATED) {
        Message message = buildResponseMessage(response, defaultSuccessMessage);
        ResponseFormatter.printMessage(message);
    } else {
        ResponseFormatter.handleErrorResponse(buildResponseMessage(response, BROKER_ERROR_MSG));
    }
}
 
Example 6
Source File: AbstractURLHandler.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
protected void validatePutStatusCode(URL dest, int statusCode, String statusMessage)
        throws IOException {
    switch (statusCode) {
        case HttpURLConnection.HTTP_OK:
            /* intentional fallthrough */
        case HttpURLConnection.HTTP_CREATED:
            /* intentional fallthrough */
        case HttpURLConnection.HTTP_ACCEPTED:
            /* intentional fallthrough */
        case HttpURLConnection.HTTP_NO_CONTENT:
            break;
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            /* intentional fallthrough */
        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new IOException("Access to URL " + dest + " was refused by the server"
                    + (statusMessage == null ? "" : ": " + statusMessage));
        default:
            throw new IOException("PUT operation to URL " + dest + " failed with status code "
                    + statusCode + (statusMessage == null ? "" : ": " + statusMessage));
    }
}
 
Example 7
Source File: CloudantStore.java    From todo-apps with Apache License 2.0 6 votes vote down vote up
@Override
public ToDo update(String id, ToDo td) throws ToDoStoreException {
  Response docResp = getRequest(id);
  int status = docResp.getStatus();
  if(status == HttpURLConnection.HTTP_OK) {
    CloudantToDo ctd = docResp.readEntity(CloudantToDo.class);
    CloudantToDo updatedCtd = new CloudantToDo(td);
    updatedCtd.set_rev(ctd.get_rev());
    Response updateReq = target.queryParam(REVISION_PARAM, ctd.get_rev()).path(id).
            request(MediaType.APPLICATION_JSON).put(Entity.entity(updatedCtd, MediaType.APPLICATION_JSON));
    status = updateReq.getStatus();
    if(status == HttpURLConnection.HTTP_CREATED) {
      CloudantPostResponse post = updateReq.readEntity(CloudantPostResponse.class);
      td.setId(post.getId());
      return td;
    } else {
      throw new ToDoStoreException("There was an error POSTing the ToDo to Cloudant. Error "
              + status);
    }
  } else {
    throw new ToDoStoreException("there was an error fetching the ToDo from Cloudant. Error " + status);
  }
}
 
Example 8
Source File: MultipartUtility.java    From patrol-android with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Completes the request and receives response from the server.
 * @return a list of Strings as response in case the server returned
 * status OK, otherwise an exception is thrown.
 * @throws IOException
 */
public List<String> finish() throws IOException {
    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_CREATED) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}
 
Example 9
Source File: GitTest.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
protected JSONObject createProjectOrLink(URI workspaceLocationURI, String projectName, String contentLocation) throws JSONException, IOException, SAXException {
	JSONObject body = new JSONObject();
	if (contentLocation != null) {
		body.put(ProtocolConstants.KEY_CONTENT_LOCATION, contentLocation);
		ServletTestingSupport.allowedPrefixes = contentLocation;
	}
	WebRequest request = new PostMethodWebRequest(workspaceLocationURI.toString(), IOUtilities.toInputStream(body.toString()), "UTF-8");
	if (projectName != null)
		request.setHeaderField(ProtocolConstants.HEADER_SLUG, projectName);
	request.setHeaderField(ProtocolConstants.HEADER_ORION_VERSION, "1");
	setAuthentication(request);
	WebResponse response = webConversation.getResponse(request);
	if (response.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
		String msg = response.getText();
		LogHelper.log(new org.eclipse.core.runtime.Status(IStatus.ERROR, "org.eclipse.orion.server.tests", msg));
		assertTrue("Unexpected failure cloning: " + msg, false);
	}
	JSONObject project = new JSONObject(response.getText());
	assertEquals(projectName, project.getString(ProtocolConstants.KEY_NAME));
	String projectId = project.optString(ProtocolConstants.KEY_ID, null);
	assertNotNull(projectId);
	IPath workspacePath = new Path(workspaceLocationURI.getPath());
	String workspaceId = workspacePath.segment(workspacePath.segmentCount() - 1);
	testProjectBaseLocation = "/" + workspaceId + '/' + projectName;
	testProjectLocalFileLocation = "/" + project.optString(ProtocolConstants.KEY_ID, null);
	return project;
}
 
Example 10
Source File: AS2SenderModule.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void sendMessage(String url, Message msg, MimeBodyPart securedData, String retries) throws Exception {
    URL urlObj = new URL(url);
    InternetHeaders ih = getHttpHeaders(msg, securedData);
    msg.setAttribute(NetAttribute.MA_DESTINATION_IP, urlObj.getHost());
    msg.setAttribute(NetAttribute.MA_DESTINATION_PORT, Integer.toString(urlObj.getPort()));

    if (logger.isInfoEnabled()) {
        logger.info("Connecting to: " + url + msg.getLogMsgID());
    }

    Map<String, String> httpOptions = getHttpOptions();
    httpOptions.put(HTTPUtil.PARAM_HTTP_USER, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_USER));
    httpOptions.put(HTTPUtil.PARAM_HTTP_PWD, msg.getPartnership().getAttribute(HTTPUtil.PARAM_HTTP_PWD));
    long maxSize = msg.getPartnership().getNoChunkedMaxSize();
    ResponseWrapper resp = HTTPUtil.execRequest(HTTPUtil.Method.POST, url, ih.getAllHeaders(), null, securedData.getInputStream(), httpOptions, maxSize);
    if (logger.isInfoEnabled()) {
        logger.info("Message sent and response received in " + resp.getTransferTimeMs() + "ms" + msg.getLogMsgID());
    }

    // Check the HTTP Response code
    int rc = resp.getStatusCode();
    if ((rc != HttpURLConnection.HTTP_OK) && (rc != HttpURLConnection.HTTP_CREATED) && (rc != HttpURLConnection.HTTP_ACCEPTED) && (rc != HttpURLConnection.HTTP_PARTIAL) && (rc != HttpURLConnection.HTTP_NO_CONTENT)) {
        msg.setLogMsg("Error sending message. URL: " + url + " ::: Response Code: " + rc + " " + resp.getStatusPhrase() + " ::: Response Message: " + resp.getBody().toString());
        logger.error(msg);
        throw new HttpResponseException(url, rc, resp.getStatusPhrase());
    }
    // So far so good ...
    processResponse(msg, resp);
}
 
Example 11
Source File: ALMRESTConnection.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
private String attachWithMultipart( String entityUrl, byte[] fileData, String contentType, String filename, String description ) throws Exception
{

    // Note the order - extremely important:
    // Filename and description before file data.
    // Name of file in file part and filename part value MUST MATCH.
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    bytes.write( String.format( fieldTemplate, boundary, "filename", filename ).getBytes() );
    bytes.write( String.format( fieldTemplate, boundary, "description", description ).getBytes() );
    bytes.write( ("\r\n--" + boundary + "--").getBytes() );
    bytes.write( fileData );
    bytes.write( String.format( fileDataPrefixTemplate, boundary, "file", filename, contentType ).getBytes() );
    bytes.close();

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

    requestHeaders.put( "Content-Type", "multipart/form-data; boundary=" + boundary );

    ALMResponse response = httpPost( entityUrl + "/attachments", bytes.toByteArray(), requestHeaders );

    if ( response.getStatusCode() != HttpURLConnection.HTTP_CREATED )
    {
        throw new Exception( response.toString() );
    }

    return response.getResponseHeaders().get( "Location" ).iterator().next();
}
 
Example 12
Source File: M3U8ThreadTaskAdapter.java    From Aria with Apache License 2.0 5 votes vote down vote up
private void handleConn(HttpURLConnection conn) throws IOException {
  ConnectionHelp.setConnectParam(mHttpTaskOption, conn);
  conn.setConnectTimeout(getTaskConfig().getConnectTimeOut());
  conn.setReadTimeout(getTaskConfig().getIOTimeOut());  //设置读取流的等待时间,必须设置该参数

  conn.connect();
  int code = conn.getResponseCode();
  if (code == HttpURLConnection.HTTP_OK) {
    is = new BufferedInputStream(ConnectionHelp.convertInputStream(conn));
    if (mHttpTaskOption.isChunked()) {
      readChunked(is);
    } else if (getThreadConfig().isBlock) {
      readDynamicFile(is);
    }
  } else if (code == HttpURLConnection.HTTP_MOVED_TEMP
      || code == HttpURLConnection.HTTP_MOVED_PERM
      || code == HttpURLConnection.HTTP_SEE_OTHER
      || code == HttpURLConnection.HTTP_CREATED // 201 跳转
      || code == 307) {
    handleUrlReTurn(conn, conn.getHeaderField("Location"));
  } else {
    fail(new AriaM3U8Exception(
            String.format("连接错误,http错误码:%s,url:%s", code, getThreadConfig().url)),
        false);
  }
  conn.disconnect();
}
 
Example 13
Source File: RDF4JProtocolSession.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public synchronized void beginTransaction(IsolationLevel isolationLevel)
		throws RDF4JException, IOException, UnauthorizedException {
	checkRepositoryURL();

	if (transactionURL != null) {
		throw new IllegalStateException("Transaction URL is already set");
	}

	HttpPost method = applyAdditionalHeaders(new HttpPost(Protocol.getTransactionsLocation(getRepositoryURL())));

	try {
		method.setHeader("Content-Type", Protocol.FORM_MIME_TYPE + "; charset=utf-8");

		List<NameValuePair> params = new ArrayList<>();
		if (isolationLevel != null) {
			params.add(new BasicNameValuePair(Protocol.ISOLATION_LEVEL_PARAM_NAME,
					isolationLevel.getURI().stringValue()));
		}

		method.setEntity(new UrlEncodedFormEntity(params, UTF8));
		HttpResponse response = execute(method);
		try {
			int code = response.getStatusLine().getStatusCode();

			if (code == HttpURLConnection.HTTP_CREATED) {
				transactionURL = response.getFirstHeader("Location").getValue();
				if (transactionURL == null) {
					throw new RepositoryException("no valid transaction ID received in server response.");
				} else {
					pingTransaction();
				}
			} else {
				throw new RepositoryException("unable to start transaction. HTTP error code " + code);
			}
		} finally {
			EntityUtils.consume(response.getEntity());
		}
	} finally {
		method.reset();
	}
}
 
Example 14
Source File: RemoteBounceProxyFacade.java    From joynr with Apache License 2.0 4 votes vote down vote up
private URI sendCreateChannelHttpRequest(ControlledBounceProxyInformation bpInfo,
                                         String ccid,
                                         String trackingId) throws IOException, JoynrProtocolException {

    // TODO jsessionid handling
    final String url = bpInfo.getLocationForBpc().toString() + "channels/?ccid=" + ccid;

    logger.debug("Using bounce proxy channel service URL: {}", url);

    HttpPost postCreateChannel = new HttpPost(url.trim());
    postCreateChannel.addHeader(ChannelServiceConstants.X_ATMOSPHERE_TRACKING_ID, trackingId);

    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(postCreateChannel);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == HttpURLConnection.HTTP_CREATED) {
            // the channel was created successfully

            // check if bounce proxy ID header was sent correctly
            if (response.containsHeader("bp")) {
                String bounceProxyId = response.getFirstHeader("bp").getValue();
                if (bounceProxyId == null || !bounceProxyId.equals(bpInfo.getId())) {
                    throw new JoynrProtocolException("Bounce proxy ID '" + bounceProxyId
                            + "' returned by bounce proxy '" + bpInfo.getId() + "' does not match.");
                }
            } else {
                throw new JoynrProtocolException("No bounce proxy ID returned by bounce proxy '" + bpInfo.getId()
                        + "'");
            }

            // get URI of newly created channel
            if (!response.containsHeader("Location")) {
                throw new JoynrProtocolException("No channel location returned by bounce proxy '" + bpInfo.getId()
                        + "'");
            }

            String locationValue = response.getFirstHeader("Location").getValue();

            if (locationValue == null || locationValue.isEmpty()) {
                throw new JoynrProtocolException("Bounce proxy '" + bpInfo.getId()
                        + "' didn't return a channel location.");
            }
            try {
                URI channelLocation = new URI(locationValue);

                logger.info("Successfully created channel '{}' on bounce proxy '{}'", ccid, bpInfo.getId());
                return channelLocation;
            } catch (Exception e) {
                throw new JoynrProtocolException("Cannot parse channel location '" + locationValue
                        + "' returned by bounce proxy '" + bpInfo.getId() + "'", e);
            }
        }

        // the bounce proxy is not excepted to reject this call as it was
        // chosen based on performance measurements sent by it
        logger.error("Failed to create channel on bounce proxy '{}'. Response: {}", bpInfo.getId(), response);
        throw new JoynrProtocolException("Bounce Proxy " + bpInfo.getId() + " rejected channel creation (Response: "
                + response + ")");

    } finally {
        if (response != null) {
            response.close();
        }
    }
}
 
Example 15
Source File: PrintLogger.java    From pre-dem-android with MIT License 4 votes vote down vote up
private void report(String filename, String key) {
        //3、上报服务器
        HttpURLConnection url = null;
        boolean successful = false;
        try {
            JSONObject parameters = new JSONObject();

            parameters.put("app_bundle_id", AppBean.APP_PACKAGE);
            parameters.put("app_name", AppBean.APP_NAME);
            parameters.put("app_version", AppBean.APP_VERSION);
            parameters.put("device_model", AppBean.PHONE_MODEL);
            parameters.put("os_platform", AppBean.ANDROID_PLATFORM);
            parameters.put("os_version", AppBean.ANDROID_VERSION);
            parameters.put("os_build", AppBean.ANDROID_BUILD);
            parameters.put("sdk_version", AppBean.SDK_VERSION);
            parameters.put("sdk_id", AppBean.SDK_ID);
            parameters.put("device_id", AppBean.DEVICE_IDENTIFIER);
            parameters.put("tag", AppBean.APP_TAG);
            parameters.put("manufacturer", AppBean.PHONE_MANUFACTURER);
            parameters.put("start_time", mStartTime);
            parameters.put("end_time", mEndTime);
            parameters.put("log_key", key);
            parameters.put("log_tags", "");
            parameters.put("error_count", 0);

            url = new HttpURLConnectionBuilder(Configuration.getLogcatUrl())
                    .setRequestMethod("POST")
                    .setHeader("Content-Type", "application/json")
                    .setRequestBody(parameters.toString())
                    .build();

            int responseCode = url.getResponseCode();

            successful = (responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_CREATED || responseCode == HttpURLConnection.HTTP_OK);
        } catch (Exception e) {
            LogUtils.e(TAG, "----" + e.toString());
//            e.printStackTrace();
        } finally {
            if (url != null) {
                url.disconnect();
            }
            if (successful) {
                mContext.deleteFile(filename);
            } else {
                LogUtils.d("-----Transmission failed, will retry on next register() call");
            }
        }
    }
 
Example 16
Source File: PartitionController.java    From metacat with Apache License 2.0 4 votes vote down vote up
/**
 * Add/update partitions to the given table.
 *
 * @param catalogName              catalog name
 * @param databaseName             database name
 * @param tableName                table name
 * @param partitionsSaveRequestDto partition request containing the list of partitions to be added/updated
 * @return Response with the number of partitions added/updated
 */
@RequestMapping(
    method = RequestMethod.POST,
    path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}",
    consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
    position = 5,
    value = "Add/update partitions to the given table",
    notes = "Add/update partitions to the given table"
)
@ApiResponses(
    {
        @ApiResponse(
            code = HttpURLConnection.HTTP_CREATED,
            message = "The partitions were successfully saved"
        ),
        @ApiResponse(
            code = HttpURLConnection.HTTP_NOT_FOUND,
            message = "The requested catalog or database or table cannot be located"
        )
    }
)
@Override
public PartitionsSaveResponseDto savePartitions(
    @ApiParam(value = "The name of the catalog", required = true)
    @PathVariable("catalog-name") final String catalogName,
    @ApiParam(value = "The name of the database", required = true)
    @PathVariable("database-name") final String databaseName,
    @ApiParam(value = "The name of the table", required = true)
    @PathVariable("table-name") final String tableName,
    @ApiParam(value = "Request containing the list of partitions", required = true)
    @RequestBody final PartitionsSaveRequestDto partitionsSaveRequestDto
) {
    final QualifiedName name = QualifiedName.ofTable(catalogName, databaseName, tableName);
    return this.requestWrapper.processRequest(
        name,
        "saveTablePartition",
        () -> {
            final PartitionsSaveResponseDto result;
            if (partitionsSaveRequestDto.getPartitions() == null
                || partitionsSaveRequestDto.getPartitions().isEmpty()) {
                result = new PartitionsSaveResponseDto();
            } else {
                result = this.partitionService.save(name, partitionsSaveRequestDto);

                // This metadata is actually for the table, if it is present update that
                if (partitionsSaveRequestDto.getDefinitionMetadata() != null
                    || partitionsSaveRequestDto.getDataMetadata() != null) {
                    final TableDto dto = new TableDto();
                    dto.setName(name);
                    dto.setDefinitionMetadata(partitionsSaveRequestDto.getDefinitionMetadata());
                    dto.setDataMetadata(partitionsSaveRequestDto.getDataMetadata());
                    this.v1.updateTable(catalogName, databaseName, tableName, dto);
                }
            }
            return result;
        }
    );
}
 
Example 17
Source File: PartitionController.java    From metacat with Apache License 2.0 4 votes vote down vote up
/**
 * Add/update partitions to the given metacat view.
 *
 * @param catalogName              catalog name
 * @param databaseName             database name
 * @param tableName                table name
 * @param viewName                 view name
 * @param partitionsSaveRequestDto partition request containing the list of partitions to be added/updated
 * @return Response with the number of partitions added/updated
 */
@RequestMapping(
    method = RequestMethod.POST,
    path = "/catalog/{catalog-name}/database/{database-name}/table/{table-name}/mview/{view-name}",
    consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
    position = 5,
    value = "Add/update partitions to the given table",
    notes = "Add/update partitions to the given table"
)
@ApiResponses(
    {
        @ApiResponse(
            code = HttpURLConnection.HTTP_CREATED,
            message = "The partitions were successfully saved"
        ),
        @ApiResponse(
            code = HttpURLConnection.HTTP_NOT_FOUND,
            message = "The requested catalog or database or table cannot be located"
        )
    }
)
public PartitionsSaveResponseDto savePartitions(
    @ApiParam(value = "The name of the catalog", required = true)
    @PathVariable("catalog-name") final String catalogName,
    @ApiParam(value = "The name of the database", required = true)
    @PathVariable("database-name") final String databaseName,
    @ApiParam(value = "The name of the table", required = true)
    @PathVariable("table-name") final String tableName,
    @ApiParam(value = "The name of the view", required = true)
    @PathVariable("view-name") final String viewName,
    @ApiParam(value = "Request containing the list of partitions", required = true)
    @RequestBody final PartitionsSaveRequestDto partitionsSaveRequestDto
) {
    final QualifiedName name = this.requestWrapper.qualifyName(
        () -> QualifiedName.ofView(catalogName, databaseName, tableName, viewName)
    );
    return this.requestWrapper.processRequest(
        name,
        "saveMViewPartition",
        () -> {
            final PartitionsSaveResponseDto result;
            if (partitionsSaveRequestDto.getPartitions() == null
                || partitionsSaveRequestDto.getPartitions().isEmpty()) {
                result = new PartitionsSaveResponseDto();
            } else {
                result = mViewService.savePartitions(name, partitionsSaveRequestDto, true);
                // This metadata is actually for the view, if it is present update that
                if (partitionsSaveRequestDto.getDefinitionMetadata() != null
                    || partitionsSaveRequestDto.getDataMetadata() != null) {
                    final TableDto dto = new TableDto();
                    dto.setName(name);
                    dto.setDefinitionMetadata(partitionsSaveRequestDto.getDefinitionMetadata());
                    dto.setDataMetadata(partitionsSaveRequestDto.getDataMetadata());
                    this.v1.updateMView(catalogName, databaseName, tableName, viewName, dto);
                }
            }
            return result;
        }
    );
}
 
Example 18
Source File: MetacatController.java    From metacat with Apache License 2.0 4 votes vote down vote up
/**
 * Creates the given database in the given catalog.
 *
 * @param catalogName              catalog name
 * @param databaseName             database name
 * @param databaseCreateRequestDto database create request
 */
@RequestMapping(
    method = RequestMethod.POST,
    path = "/catalog/{catalog-name}/database/{database-name}",
    consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
    position = 2,
    value = "Creates the given database in the given catalog",
    notes = "Given a catalog and a database name, creates the database in the catalog"
)
@ApiResponses(
    {
        @ApiResponse(
            code = HttpURLConnection.HTTP_CREATED,
            message = "The database was created"
        ),
        @ApiResponse(
            code = HttpURLConnection.HTTP_NOT_FOUND,
            message = "The requested catalog or database cannot be located"
        )
    }
)
@Override
public void createDatabase(
    @ApiParam(value = "The name of the catalog", required = true)
    @PathVariable("catalog-name") final String catalogName,
    @ApiParam(value = "The name of the database", required = true)
    @PathVariable("database-name") final String databaseName,
    @ApiParam(value = "The database information")
    @Nullable @RequestBody(required = false) final DatabaseCreateRequestDto databaseCreateRequestDto
) {
    final QualifiedName name = this.requestWrapper.qualifyName(
        () -> QualifiedName.ofDatabase(catalogName, databaseName)
    );
    this.requestWrapper.processRequest(
        name,
        "createDatabase",
        () -> {
            final DatabaseDto newDto = new DatabaseDto();
            newDto.setName(name);
            if (databaseCreateRequestDto != null) {
                newDto.setUri(databaseCreateRequestDto.getUri());
                newDto.setMetadata(databaseCreateRequestDto.getMetadata());
                newDto.setDefinitionMetadata(databaseCreateRequestDto.getDefinitionMetadata());
            }
            this.databaseService.create(name, newDto);
            return null;
        }
    );
}
 
Example 19
Source File: Sentry.java    From Sentry-Android with MIT License 4 votes vote down vote up
/**
 * Map from HTTP status code to reason description.
 * Sentry HTTP breadcrumbs expect a text description of the HTTP status-code.
 * This function implements a look-up table with a default value for unknown status-codes.
 * @param statusCode an integer HTTP status code, expected to be in the range [200,505].
 * @return a non-empty string in all cases.
 */
private static String httpReason(int statusCode) {
    switch (statusCode) {
        // 2xx
        case HttpURLConnection.HTTP_OK: return "OK";
        case HttpURLConnection.HTTP_CREATED: return "Created";
        case HttpURLConnection.HTTP_ACCEPTED: return "Accepted";
        case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: return "Non-Authoritative Information";
        case HttpURLConnection.HTTP_NO_CONTENT: return "No Content";
        case HttpURLConnection.HTTP_RESET: return "Reset Content";
        case HttpURLConnection.HTTP_PARTIAL: return "Partial Content";

        // 3xx
        case HttpURLConnection.HTTP_MULT_CHOICE: return "Multiple Choices";
        case HttpURLConnection.HTTP_MOVED_PERM: return "Moved Permanently";
        case HttpURLConnection.HTTP_MOVED_TEMP: return "Temporary Redirect";
        case HttpURLConnection.HTTP_SEE_OTHER: return "See Other";
        case HttpURLConnection.HTTP_NOT_MODIFIED: return "Not Modified";
        case HttpURLConnection.HTTP_USE_PROXY: return "Use Proxy";

        // 4xx
        case HttpURLConnection.HTTP_BAD_REQUEST: return "Bad Request";
        case HttpURLConnection.HTTP_UNAUTHORIZED: return "Unauthorized";
        case HttpURLConnection.HTTP_PAYMENT_REQUIRED: return "Payment Required";
        case HttpURLConnection.HTTP_FORBIDDEN: return "Forbidden";
        case HttpURLConnection.HTTP_NOT_FOUND: return "Not Found";
        case HttpURLConnection.HTTP_BAD_METHOD: return "Method Not Allowed";
        case HttpURLConnection.HTTP_NOT_ACCEPTABLE: return "Not Acceptable";
        case HttpURLConnection.HTTP_PROXY_AUTH: return "Proxy Authentication Required";
        case HttpURLConnection.HTTP_CLIENT_TIMEOUT: return "Request Time-Out";
        case HttpURLConnection.HTTP_CONFLICT: return "Conflict";
        case HttpURLConnection.HTTP_GONE: return "Gone";
        case HttpURLConnection.HTTP_LENGTH_REQUIRED: return "Length Required";
        case HttpURLConnection.HTTP_PRECON_FAILED: return "Precondition Failed";
        case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: return "Request Entity Too Large";
        case HttpURLConnection.HTTP_REQ_TOO_LONG: return "Request-URI Too Large";
        case HttpURLConnection.HTTP_UNSUPPORTED_TYPE: return "Unsupported Media Type";

        // 5xx
        case HttpURLConnection.HTTP_INTERNAL_ERROR: return "Internal Server Error";
        case HttpURLConnection.HTTP_NOT_IMPLEMENTED: return "Not Implemented";
        case HttpURLConnection.HTTP_BAD_GATEWAY: return "Bad Gateway";
        case HttpURLConnection.HTTP_UNAVAILABLE: return "Service Unavailable";
        case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return "Gateway Timeout";
        case HttpURLConnection.HTTP_VERSION: return "Version Not Supported";

        default: return "unknown";
    }
}
 
Example 20
Source File: HttpResponse.java    From steady with Apache License 2.0 2 votes vote down vote up
/**
 * <p>isCreated.</p>
 *
 * @return a boolean.
 */
public boolean isCreated() { return this.status==HttpURLConnection.HTTP_CREATED; }