Java Code Examples for org.apache.commons.httpclient.methods.PostMethod#addParameter()

The following examples show how to use org.apache.commons.httpclient.methods.PostMethod#addParameter() . 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: RestClient.java    From maven-framework-project with MIT License 6 votes vote down vote up
public void addBook(String bookName, String author) throws Exception {

        String output = null;
        try{
            String url = "http://localhost:8080/bookservice/addbook";
            HttpClient client = new HttpClient();
            PostMethod mPost = new PostMethod(url);
            mPost.addParameter("name", "Naked Sun");
            mPost.addParameter("author", "Issac Asimov");
            Header mtHeader = new Header();
            mtHeader.setName("content-type");
            mtHeader.setValue("application/x-www-form-urlencoded");
            mtHeader.setName("accept");
            mtHeader.setValue("application/xml");
            //mtHeader.setValue("application/json");
            mPost.addRequestHeader(mtHeader);
            client.executeMethod(mPost);
            output = mPost.getResponseBodyAsString( );
            mPost.releaseConnection( );
            System.out.println("output : " + output);
        }catch(Exception e){
            throw new Exception("Exception in adding bucket : " + e);
        }

    }
 
Example 2
Source File: ClusterServiceServletImpl.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public String execute(final ClusterServicePdu pdu) throws RemoteException {

    final HttpClient client = getHttpClient();
    final PostMethod method = new PostMethod(_serviceUrl);

    method.addParameter("method", Integer.toString(RemoteMethodConstants.METHOD_DELIVER_PDU));
    method.addParameter("sourcePeer", pdu.getSourcePeer());
    method.addParameter("destPeer", pdu.getDestPeer());
    method.addParameter("pduSeq", Long.toString(pdu.getSequenceId()));
    method.addParameter("pduAckSeq", Long.toString(pdu.getAckSequenceId()));
    method.addParameter("agentId", Long.toString(pdu.getAgentId()));
    method.addParameter("gsonPackage", pdu.getJsonPackage());
    method.addParameter("stopOnError", pdu.isStopOnError() ? "1" : "0");
    method.addParameter("pduType", Integer.toString(pdu.getPduType()));

    return executePostMethod(client, method);
}
 
Example 3
Source File: ClusterServiceServletImpl.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Override
public String execute(final ClusterServicePdu pdu) throws RemoteException {
    s_logger.info("Executing a PDU: " + pdu);

    final HttpClient client = getHttpClient();
    final PostMethod method = new PostMethod(_serviceUrl);

    method.addParameter("method", Integer.toString(RemoteMethodConstants.METHOD_DELIVER_PDU));
    method.addParameter("sourcePeer", pdu.getSourcePeer());
    method.addParameter("destPeer", pdu.getDestPeer());
    method.addParameter("pduSeq", Long.toString(pdu.getSequenceId()));
    method.addParameter("pduAckSeq", Long.toString(pdu.getAckSequenceId()));
    method.addParameter("agentId", Long.toString(pdu.getAgentId()));
    method.addParameter("gsonPackage", pdu.getJsonPackage());
    method.addParameter("stopOnError", pdu.isStopOnError() ? "1" : "0");
    method.addParameter("pduType", Integer.toString(pdu.getPduType()));

    return executePostMethod(client, method);
}
 
Example 4
Source File: ClusterServiceServletImpl.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Override
public boolean ping(final String callingPeer) throws RemoteException {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Ping at " + _serviceUrl);
    }

    final HttpClient client = getHttpClient();
    final PostMethod method = new PostMethod(_serviceUrl);

    method.addParameter("method", Integer.toString(RemoteMethodConstants.METHOD_PING));
    method.addParameter("callingPeer", callingPeer);

    final String returnVal = executePostMethod(client, method);
    if ("true".equalsIgnoreCase(returnVal)) {
        return true;
    }
    return false;
}
 
Example 5
Source File: ClusterServiceServletImpl.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
@Override
public boolean ping(final String callingPeer) throws RemoteException {
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Ping at " + _serviceUrl);
    }

    final HttpClient client = getHttpClient();
    final PostMethod method = new PostMethod(_serviceUrl);

    method.addParameter("method", Integer.toString(RemoteMethodConstants.METHOD_PING));
    method.addParameter("callingPeer", callingPeer);

    final String returnVal = executePostMethod(client, method);
    if ("true".equalsIgnoreCase(returnVal)) {
        return true;
    }
    return false;
}
 
Example 6
Source File: HttpUtils.java    From Java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 设置请求参数
 * @param method
 * @param params
 */
private static void setParams(PostMethod method,Map<String, String> params) {

	//校验参数
	if(params==null||params.size()==0){
		return;
	}
	
	Set<String> paramsKeys = params.keySet();
	Iterator<String> iterParams = paramsKeys.iterator();
	while(iterParams.hasNext()){
		String key = iterParams.next();
		method.addParameter(key, params.get(key));
	}
	
}
 
Example 7
Source File: MatrixUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
private static PostMethod genPostMethod(String url) {
	String[] matrixInfos = ParamConfig.getAttribute(MATRIX_CALL, 
			"http://www.boubei.com,ANONYMOUS,0211bdae3d86730fe302940832025419").split(",");
	
	PostMethod postMethod = new PostMethod(matrixInfos[0] + url);
   	postMethod.addParameter("uName", matrixInfos[1]);
	postMethod.addParameter("uToken", matrixInfos[2]);
	
	postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
	return postMethod;
}
 
Example 8
Source File: GeoWebCacheCommands.java    From geoserver-shell with MIT License 5 votes vote down vote up
@CliCommand(value = "gwc kill", help = "Kill a seeding operation.")
public boolean kill(
        @CliOption(key = "name", mandatory = false, help = "The layer name") String name,
        @CliOption(key = "tasks", mandatory = false, unspecifiedDefaultValue = "all", help = "Which tasks to kill (all, running, pending)") String tasks
) throws Exception {
    String url = geoserver.getUrl() + "/gwc/rest/seed";
    if (name != null) {
        url += "/" + URLUtil.encode(name);
    }
    PostMethod postMethod = new PostMethod(url);
    postMethod.addParameter("kill_all", tasks);
    String response = HTTPUtils.post(url, postMethod.getRequestEntity(), geoserver.getUser(), geoserver.getPassword());
    return response != null;
}
 
Example 9
Source File: Hc3HttpUtils.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Create an HTTP POST Method.
 * 
 * @param url URL of the request.
 * @param properties Properties to drive the API.
 * @return POST Method
 * @throws URIException Exception if the URL is not correct.
 */
private static PostMethod createHttpPostMethod(
    String url,
    Map<String, String> properties) throws URIException {
  StringBuilder debugUrl = (DEBUG_URL) ? new StringBuilder("POST " + url) : null;
  org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(url, false, "UTF8");
  PostMethod method = new PostMethod();
  method.setURI(uri);
  method.getParams().setSoTimeout(60000);
  method.getParams().setContentCharset("UTF-8");
  method.setRequestHeader("Accept-Encoding", "gzip");
  if (properties != null) {
    boolean first = true;
    Iterator<Map.Entry<String, String>> iter = properties.entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry<String, String> property = iter.next();
      String key = property.getKey();
      String value = property.getValue();
      method.addParameter(key, value);
      first = fillDebugUrl(debugUrl, first, key, value);
    }
  }
  if (DEBUG_URL && (debugUrl != null)) {
    debugText(debugUrl.toString());
  }
  return method;
}
 
Example 10
Source File: Authentication.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, String> login(String authKey, String endpoint) {
  String[] credentials = authKey.split(":");
  if (credentials.length != 2) {
    return Collections.emptyMap();
  }
  PostMethod post = new PostMethod(endpoint);
  post.addRequestHeader("Origin", "http://localhost");
  post.addParameter(new NameValuePair("userName", credentials[0]));
  post.addParameter(new NameValuePair("password", credentials[1]));
  try {
    int code = client.executeMethod(post);
    if (code == HttpStatus.SC_OK) {
      String content = post.getResponseBodyAsString();
      Map<String, Object> resp = gson.fromJson(content, 
          new TypeToken<Map<String, Object>>() {}.getType());
      LOG.info("Received from Zeppelin LoginRestApi : " + content);
      return (Map<String, String>) resp.get("body");
    } else {
      LOG.error("Failed Zeppelin login {}, status code {}", endpoint, code);
      return Collections.emptyMap();
    }
  } catch (IOException e) {
    LOG.error("Cannot login into Zeppelin", e);
    return Collections.emptyMap();
  }
}
 
Example 11
Source File: BaseHttpRequestMaker.java    From MesquiteCore with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean postToServer(String s, String URI, StringBuffer response) {
	HttpClient client = new HttpClient();
	PostMethod method = new PostMethod(URI);
	method.addParameter("OS", StringEscapeUtils.escapeHtml3(System.getProperty("os.name") + "\t" + System.getProperty("os.version")));
	method.addParameter("JVM", StringEscapeUtils.escapeHtml3(System.getProperty("java.version") +"\t" + System.getProperty("java.vendor")));
	NameValuePair post = new NameValuePair();
	post.setName("post");
	post.setValue(StringEscapeUtils.escapeHtml3(s));
	method.addParameter(post);

	method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, 
    		new DefaultHttpMethodRetryHandler(3, false));
	
	return executeMethod(client, method, response);
}
 
Example 12
Source File: MatrixUtil.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
public static void remoteRecord(Object recordID, Map<String, String> params) {
  	String url = "/tss/xdata/api/rid/" + recordID;
  	PostMethod postMethod = genPostMethod(url);

for(String key : params.keySet()) {
	String value = params.get(key);
	postMethod.addParameter(key, EasyUtils.obj2String(value));
}

exePostMethod(postMethod);
  }
 
Example 13
Source File: PSPMockService.java    From development with Apache License 2.0 4 votes vote down vote up
/**
 * Sends the response call with the specified content to the BES servlet
 * handling the PSP registration.
 * 
 * @param sessionParams
 *            The parameters to retrieve the data from.
 * @return The URL to redirect the user to.
 * @throws IOException
 */
private String sendResponseToBesServer(Map<String, ?> sessionParams)
        throws IOException {
    String redirectURL = getParameterValue(sessionParams,
            "FRONTEND.RESPONSE_URL");
    String choice = getParameterValue(sessionParams, "result");

    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(redirectURL);

    Iterator<String> it = sessionParams.keySet().iterator();
    String key;
    while (it.hasNext()) {
        key = it.next();
        postMethod.addParameter(key, getParameterValue(sessionParams, key));
    }

    // set params
    boolean wasCancelled = "Cancel".equals(choice);
    if (wasCancelled) {
        postMethod.addParameter("FRONTEND.REQUEST.CANCELLED", "true");
    }

    postMethod.addParameter("PROCESSING.RESULT", "ACK");
    postMethod.addParameter("PROCESSING.CODE", "000.000.000");
    postMethod.addParameter("PROCESSING.RETURN", "000.000.000");
    postMethod.addParameter("PROCESSING.RETURN.CODE", "000.000.000");
    postMethod.addParameter("PROCESSING.REASON", "90.00");
    postMethod.addParameter("PROCESSING.TIMESTAMP",
            String.valueOf(System.currentTimeMillis()));
    postMethod.addParameter("IDENTIFICATION.UNIQUEID", "12345");

    // some fake account data
    postMethod.addParameter("ACCOUNT.NUMBER", "1100101");
    postMethod.addParameter("ACCOUNT.BRAND", "Mock Platin Card");
    postMethod.addParameter("ACCOUNT.EXPIRY_MONTH", "09");
    postMethod.addParameter("ACCOUNT.EXPIRY_YEAR", "19");
    postMethod.addParameter("ACCOUNT.BANK", "Mock Bank");
    postMethod.addParameter("ACCOUNT.BANKNAME", "08154711");

    // send the request
    httpClient.executeMethod(postMethod);

    String responseURL = postMethod.getResponseBodyAsString();
    return responseURL;
}
 
Example 14
Source File: HttpClientUtils.java    From BigApp_Discuz_Android with Apache License 2.0 4 votes vote down vote up
public static String httpPost(String url, Map paramMap, String code) {
    ZogUtils.printLog(HttpClientUtils.class, "request url: " + url);
    String content = null;
    if (url == null || url.trim().length() == 0 || paramMap == null
            || paramMap.isEmpty())
        return null;
    HttpClient httpClient = new HttpClient();
    PostMethod method = new PostMethod(url);

    method.setRequestHeader("Content-Type",
            "application/x-www-form-urlencoded;charset=utf-8");

    Iterator it = paramMap.keySet().iterator();

    while (it.hasNext()) {
        String key = it.next() + "";
        Object o = paramMap.get(key);
        if (o != null && o instanceof String) {
            method.addParameter(new NameValuePair(key, o.toString()));
        }

        System.out.println(key + ":" + o);
        method.addParameter(new NameValuePair(key, o.toString()));

    }
    try {
        httpClient.executeMethod(method);
        ZogUtils.printLog(HttpClientUtils.class, method.getStatusLine()
                + "");
        content = new String(method.getResponseBody(), code);

    } catch (Exception e) {
        ZogUtils.printLog(HttpClientUtils.class, "time out");
        e.printStackTrace();
    } finally {
        if (method != null)
            method.releaseConnection();
        method = null;
        httpClient = null;
    }
    return content;

}
 
Example 15
Source File: SalesforceProvisioningConnector.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
/**
 * authenticate to salesforce API.
 */
private String authenticate() throws IdentityProvisioningException {

    boolean isDebugEnabled = log.isDebugEnabled();

    HttpClient httpclient = new HttpClient();

    String url = configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.OAUTH2_TOKEN_ENDPOINT);

    PostMethod post = new PostMethod(StringUtils.isNotBlank(url) ?
            url : IdentityApplicationConstants.SF_OAUTH2_TOKEN_ENDPOINT);

    post.addParameter(SalesforceConnectorConstants.CLIENT_ID,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.CLIENT_ID));
    post.addParameter(SalesforceConnectorConstants.CLIENT_SECRET,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.CLIENT_SECRET));
    post.addParameter(SalesforceConnectorConstants.PASSWORD,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.PASSWORD));
    post.addParameter(SalesforceConnectorConstants.GRANT_TYPE,
            SalesforceConnectorConstants.GRANT_TYPE_PASSWORD);
    post.addParameter(SalesforceConnectorConstants.USERNAME,
            configHolder.getValue(SalesforceConnectorConstants.PropertyConfig.USERNAME));

    StringBuilder sb = new StringBuilder();
    try {
        // send the request
        int responseStatus = httpclient.executeMethod(post);
        if (isDebugEnabled) {
            log.debug("Authentication to salesforce returned with response code: "
                    + responseStatus);
        }

        sb.append("HTTP status " + post.getStatusCode() + " creating user\n\n");

        if (post.getStatusCode() == HttpStatus.SC_OK) {
            JSONObject response = new JSONObject(new JSONTokener(new InputStreamReader(
                    post.getResponseBodyAsStream())));
            if (isDebugEnabled) {
                log.debug("Authenticate response: " + response.toString(2));
            }

            Object attributeValObj = response.opt("access_token");
            if (attributeValObj instanceof String) {
                if (isDebugEnabled) {
                    log.debug("Access token is : " + (String) attributeValObj);
                }
                return (String) attributeValObj;
            } else {
                log.error("Authentication response type : " + attributeValObj.toString()
                        + " is invalide");
            }
        } else {
            log.error("recieved response status code :" + post.getStatusCode() + " text : "
                    + post.getStatusText());
        }
    } catch (JSONException | IOException e) {
        throw new IdentityProvisioningException("Error in decoding response to JSON", e);
    } finally {
        post.releaseConnection();
    }

    return "";
}
 
Example 16
Source File: TunnelComponent.java    From olat with Apache License 2.0 4 votes vote down vote up
/**
 * @param tuReq
 * @param client
 * @return HttpMethod
 */
public HttpMethod fetch(final TURequest tuReq, final HttpClient client) {

    final String modulePath = tuReq.getUri();

    HttpMethod meth = null;
    final String method = tuReq.getMethod();
    if (method.equals("GET")) {
        final GetMethod cmeth = new GetMethod(modulePath);
        final String queryString = tuReq.getQueryString();
        if (queryString != null) {
            cmeth.setQueryString(queryString);
        }
        meth = cmeth;
        if (meth == null) {
            return null;
        }
        // if response is a redirect, follow it
        meth.setFollowRedirects(true);

    } else if (method.equals("POST")) {
        final String type = tuReq.getContentType();
        if (type == null || type.equals("application/x-www-form-urlencoded")) {
            // regular post, no file upload
        }

        final PostMethod pmeth = new PostMethod(modulePath);
        final Set postKeys = tuReq.getParameterMap().keySet();
        for (final Iterator iter = postKeys.iterator(); iter.hasNext();) {
            final String key = (String) iter.next();
            final String vals[] = (String[]) tuReq.getParameterMap().get(key);
            for (int i = 0; i < vals.length; i++) {
                pmeth.addParameter(key, vals[i]);
            }
            meth = pmeth;
        }
        if (meth == null) {
            return null;
            // Redirects are not supported when using POST method!
            // See RFC 2616, section 10.3.3, page 62
        }
    }

    // Add olat specific headers to the request, can be used by external
    // applications to identify user and to get other params
    // test page e.g. http://cgi.algonet.se/htbin/cgiwrap/ug/test.py
    meth.addRequestHeader("X-OLAT-USERNAME", tuReq.getUserName());
    meth.addRequestHeader("X-OLAT-LASTNAME", tuReq.getLastName());
    meth.addRequestHeader("X-OLAT-FIRSTNAME", tuReq.getFirstName());
    meth.addRequestHeader("X-OLAT-EMAIL", tuReq.getEmail());

    try {
        client.executeMethod(meth);
        return meth;
    } catch (final Exception e) {
        meth.releaseConnection();
    }
    return null;
}
 
Example 17
Source File: KafkaAvroSchemaRegistry.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/**
 * Register a schema to the Kafka schema registry
 *
 * @param schema
 * @return schema ID of the registered schema
 * @throws SchemaRegistryException if registration failed
 */
@Override
public synchronized String register(Schema schema) throws SchemaRegistryException {

  // Change namespace if override specified
  if (this.namespaceOverride.isPresent()) {
    schema = AvroUtils.switchNamespace(schema, this.namespaceOverride.get());
  }

  LOG.info("Registering schema " + schema.toString());

  PostMethod post = new PostMethod(url);
  post.addParameter("schema", schema.toString());

  HttpClient httpClient = this.borrowClient();
  try {
    LOG.debug("Loading: " + post.getURI());
    int statusCode = httpClient.executeMethod(post);
    if (statusCode != HttpStatus.SC_CREATED) {
      throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode);
    }

    String response;
    response = post.getResponseBodyAsString();
    if (response != null) {
      LOG.info("Received response " + response);
    }

    String schemaKey;
    Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME);
    if (headers.length != 1) {
      throw new SchemaRegistryException(
          "Error reading schema id returned by registerSchema call: headers.length = " + headers.length);
    } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) {
      throw new SchemaRegistryException(
          "Error parsing schema id returned by registerSchema call: header = " + headers[0].getValue());
    } else {
      LOG.info("Registered schema successfully");
      schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length());
    }

    return schemaKey;
  } catch (Throwable t) {
    throw new SchemaRegistryException(t);
  } finally {
    post.releaseConnection();
    this.httpClientPool.returnObject(httpClient);
  }
}
 
Example 18
Source File: LiKafkaSchemaRegistry.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/**
 * Register a schema to the Kafka schema registry
 *
 * @param schema
 * @param post
 * @return schema ID of the registered schema
 * @throws SchemaRegistryException if registration failed
 */
public synchronized MD5Digest register(Schema schema, PostMethod post) throws SchemaRegistryException {

  // Change namespace if override specified
  if (this.namespaceOverride.isPresent()) {
    schema = AvroUtils.switchNamespace(schema, this.namespaceOverride.get());
  }

  LOG.info("Registering schema " + schema.toString());

  post.addParameter("schema", schema.toString());

  HttpClient httpClient = this.borrowClient();
  try {
    LOG.debug("Loading: " + post.getURI());
    int statusCode = httpClient.executeMethod(post);
    if (statusCode != HttpStatus.SC_CREATED) {
      throw new SchemaRegistryException("Error occurred while trying to register schema: " + statusCode);
    }

    String response;
    response = post.getResponseBodyAsString();
    if (response != null) {
      LOG.info("Received response " + response);
    }

    String schemaKey;
    Header[] headers = post.getResponseHeaders(SCHEMA_ID_HEADER_NAME);
    if (headers.length != 1) {
      throw new SchemaRegistryException(
          "Error reading schema id returned by registerSchema call: headers.length = " + headers.length);
    } else if (!headers[0].getValue().startsWith(SCHEMA_ID_HEADER_PREFIX)) {
      throw new SchemaRegistryException(
          "Error parsing schema id returned by registerSchema call: header = " + headers[0].getValue());
    } else {
      LOG.info("Registered schema successfully");
      schemaKey = headers[0].getValue().substring(SCHEMA_ID_HEADER_PREFIX.length());
    }
    MD5Digest schemaId = MD5Digest.fromString(schemaKey);
    return schemaId;
  } catch (Throwable t) {
    throw new SchemaRegistryException(t);
  } finally {
    post.releaseConnection();
    this.httpClientPool.returnObject(httpClient);
  }
}
 
Example 19
Source File: CitationParser.java    From bluima with Apache License 2.0 4 votes vote down vote up
public Citation parse(String citationStr) throws HttpException,
        IOException, ParserConfigurationException, SAXException {

    PostMethod method = new PostMethod(url);
    method.addRequestHeader("accept", "text/xml");
    method.addParameter("citation", citationStr);

    int statusCode = client.executeMethod(method);

    if (statusCode != -1) {
        InputStream in = method.getResponseBodyAsStream();

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory
                .newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(in);
        doc.getDocumentElement().normalize();

        NodeList nodes = doc.getElementsByTagName("citation");

        // for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(0);

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;

            String isValid = element.getAttribute("valid");
            if (isValid.equals("true")) {
                Citation citation = new Citation();

                citation.setTitle(getValue("title", element));
                citation.setYear(new Integer(getValue("year", element)));

                NodeList authors = element.getElementsByTagName("author");
                for (int j = 0; j < authors.getLength(); j++) {
                    Node author = authors.item(j);
                    citation.addAuthor(author.getTextContent());
                }
                return citation;
            }
        }
    }
    return null;
}
 
Example 20
Source File: LiKafkaSchemaRegistry.java    From incubator-gobblin with Apache License 2.0 3 votes vote down vote up
/**
 * Register a schema to the Kafka schema registry under the provided input name. This method will change the name
 * of the schema to the provided name if configured to do so. This is useful because certain services (like Gobblin kafka adaptor and
 * Camus) get the schema for a topic by querying for the latest schema with the topic name, requiring the topic
 * name and schema name to match for all topics. If it is not configured to switch names, this is useful for the case
 * where the Kafka topic and Avro schema names do not match. This method registers the schema to the schema registry in such a
 * way that any schema can be written to any topic.
 *
 * @param schema {@link org.apache.avro.Schema} to register.
 * @param name Name of the schema when registerd to the schema registry. This name should match the name
 *                     of the topic where instances will be published.
 * @return schema ID of the registered schema.
 * @throws SchemaRegistryException if registration failed
 */
@Override
public MD5Digest register(String name, Schema schema) throws SchemaRegistryException {
  PostMethod post = new PostMethod(url);
  if (this.switchTopicNames) {
    return register(AvroUtils.switchName(schema, name), post);
  } else {
    post.addParameter("name", name);
    return register(schema, post);
  }
}