org.apache.commons.httpclient.util.DateUtil Java Examples

The following examples show how to use org.apache.commons.httpclient.util.DateUtil. 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: RedisService.java    From xmfcn-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * getOnlyNo(获取唯一编号)
 *
 * @param type
 * @return
 */
@RequestMapping("getOnlyNo")
public String getOnlyNo(String prefix) {
    logger.info("getOnlyNo(获取唯一编号) 开始:" + prefix);
    String onlyNo = null;
    if (StringUtil.isBlank(prefix)) {
        return onlyNo;
    }
    String key = DateUtil.formatDate(new Date(), "yyyyMMdd");
    if (!exists(key)) {
        saveCache(key, "100000", 60 * 60 * 24);
    }
    RedisConnection conn = getRedisConnection();
    if (conn == null) {
        return onlyNo;
    }
    long number = -1;
    try {
        number = conn.incr(key.getBytes());
    } catch (Exception e) {
        logger.error(StringUtil.getExceptionMsg(e));
    }
    onlyNo = prefix + DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + number;
    logger.info("getOnlyNo(获取唯一编号) 结束  :" + onlyNo);
    return onlyNo;
}
 
Example #2
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public long getHeaderFieldDate(String key, long def) throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader(key);

  if (head == null) {
    return def;
  }

  try {
    Date date = DateUtil.parseDate(head.getValue());
    return date.getTime();

  } catch (DateParseException e) {
    return def;
  }
}
 
Example #3
Source File: CacheableScanRuleUnitTest.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotCauseExceptionWhenExpiresHeaderHasZeroValue()
        throws URIException, HttpMalformedHeaderException {
    // Given
    HttpMessage msg = createMessage();
    msg.setResponseHeader(
            "HTTP/1.1 200 OK\r\n"
                    + "Cache-Control: must-revalidate,private\r\n"
                    + "Pragma: must-revalidate,no-cache\r\n"
                    + "Content-Type: text/xml;charset=UTF-8\r\n"
                    + "Expires: 0\r\n"
                    + // http-date expected, Ex: "Wed, 21 Oct 2015 07:28:00 GMT"
                    "Date: "
                    + DateUtil.formatDate(new Date())
                    + "\r\n\r\n");
    // When
    scanHttpResponseReceive(msg);
    // Then
    assertThat(alertsRaised.size(), equalTo(1));
}
 
Example #4
Source File: ARC2WCDX.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
protected static void appendTimeField(StringBuilder builder, Object obj) {
    if(builder.length()>0) {
        // prepend with delimiter
        builder.append(' ');
    }
    if(obj==null) {
        builder.append("-");
        return;
    }
    if(obj instanceof Header) {
        String s = ((Header)obj).getValue().trim();
        try {
            Date date = DateUtil.parseDate(s);
            String d = ArchiveUtils.get14DigitDate(date);
            if(d.startsWith("209")) {
                d = "199"+d.substring(3);
            }
            obj = d;
        } catch (DateParseException e) {
            builder.append('e');
            return;
        }

    }
    builder.append(obj);
}
 
Example #5
Source File: TestAPC.java    From rainbow with Apache License 2.0 5 votes vote down vote up
@Test
public void test () throws IOException, InterruptedException
{
    BufferedReader reader = new BufferedReader(new FileReader(
            "H:\\SelfLearning\\SAI\\DBIIR\\rainbows\\workload.txt"));
    String line = null;
    int i = 0, j = 0;
    Random random = new Random(System.currentTimeMillis());
    AccessPatternCache APC = new AccessPatternCache(100000, 0.1);
    System.out.println(DateUtil.formatDate(new Date()));
    while ((line = reader.readLine()) != null)
    {
        i++;
        String[] tokens = line.split("\t");
        double weight = Double.parseDouble(tokens[1]);
        AccessPattern pattern = new AccessPattern(tokens[0], weight);
        for (String column : tokens[2].split(","))
        {
            pattern.addColumn(column);
        }

        if (APC.cache(pattern))
        {
            System.out.println(DateUtil.formatDate(new Date()));
            System.out.println(i + ", trigger layout optimization.");
            j++;
            APC.saveAsWorkloadFile("H:\\SelfLearning\\SAI\\DBIIR\\rainbows\\workload_"+j+".txt");
            System.out.println(DateUtil.formatDate(new Date()));
        }
        Thread.sleep(random.nextInt(500));
    }
}
 
Example #6
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public long getDate() throws IOException {
  final HttpMethod res = getResult(true);
  final Header head = res.getResponseHeader("Date");

  if (head == null) {
    return 0;
  }

  try {
    return DateUtil.parseDate(head.getValue()).getTime();
  } catch (DateParseException e) {
    return 0;
  }
}
 
Example #7
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public long getExpiration() throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader("Expires");

  if (head == null) {
    return 0;
  }

  try {
    return DateUtil.parseDate(head.getValue()).getTime();
  } catch (DateParseException e) {
    return 0;
  }
}
 
Example #8
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public long getLastModified() throws IOException {
  HttpMethod res = getResult(true);
  Header head = res.getResponseHeader("Last-Modified");

  if (head != null) {
    try {
      return DateUtil.parseDate(head.getValue()).getTime();
    } catch (DateParseException e) {
      return 0;
    }
  }

  return 0;
}
 
Example #9
Source File: CacheableScanRule.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
private Date parseDate(String dateStr) {
    Date newDate = null;
    try {
        newDate = DateUtil.parseDate(dateStr);
    } catch (DateParseException dpe) {
        // There was an error parsing the date, leave the var null
    }
    return newDate;
}
 
Example #10
Source File: WebdavFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the last modified time of this file. Is only called if {@link #doGetType} does not return
 * {@link FileType#IMAGINARY}.
 */
@Override
protected long doGetLastModifiedTime() throws Exception {
    final DavProperty property = getProperty((URLFileName) getName(), DavConstants.PROPERTY_GETLASTMODIFIED);
    if (property != null) {
        final String value = (String) property.getValue();
        return DateUtil.parseDate(value).getTime();
    }
    return 0;
}
 
Example #11
Source File: HttpFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the last modified time of this file.
 * <p>
 * This implementation throws an exception.
 * </p>
 */
@Override
protected long doGetLastModifiedTime() throws Exception {
    final Header header = method.getResponseHeader("last-modified");
    FileSystemException.requireNonNull(header, "vfs.provider.http/last-modified.error", getName());
    return DateUtil.parseDate(header.getValue()).getTime();
}
 
Example #12
Source File: Listener.java    From oneops with Apache License 2.0 4 votes vote down vote up
private void postExecTags(CmsWorkOrderSimpleBase wo) {
  wo.putSearchTag(
      CmsConstants.RESPONSE_ENQUE_TS, DateUtil.formatDate(new Date(), SEARCH_TS_PATTERN));
}
 
Example #13
Source File: WorkOrderExecutor.java    From oneops with Apache License 2.0 4 votes vote down vote up
/**
 * Process work-order and return message to be put in the controller response queue.
 *
 * @param o CmsWorkOrderSimpleBase
 * @param correlationId JMS correlation Id
 * @returns response message map.
 */
@Override
public Map<String, String> process(CmsWorkOrderSimpleBase o, String correlationId) {
  CmsWorkOrderSimple wo = (CmsWorkOrderSimple) o;

  // compute::replace will do a delete and add - only for old pre-versioned compute
  String[] classParts = wo.getRfcCi().getCiClassName().split("\\.");
  if (classParts.length < 3 && isWorkOrderOfCompute(wo) && isAction(wo, REPLACE)) {
    logger.info("compute::replace - delete then add");
    wo.getRfcCi().setRfcAction(DELETE);
    process(wo, correlationId);

    if (wo.getDpmtRecordState().equals(COMPLETE)) {
      if (wo.getRfcCi().getCiAttributes().containsKey("instance_id")) {
        wo.getRfcCi().getCiAttributes().remove("instance_id");
      }
      wo.getRfcCi().setRfcAction(ADD);
    } else {
      logger.info("compute::replace - delete failed");
      return buildResponseMessage(wo, correlationId);
    }
  }

  long startTime = System.currentTimeMillis();
  if (config.isCloudStubbed(wo)) {
    String fileName = config.getDataDir() + "/" + wo.getDpmtRecordId() + ".json";
    writeChefRequest(wo, fileName);
    processStubbedCloud(wo);
    logger.warn("completing wo without doing anything because cloud is stubbed");
  } else {
    // skip fqdn workorder if dns is disabled
    if (config.isDnsDisabled() && wo.getRfcCi().getCiClassName()
        .matches(BOM_CLASS_PREFIX + "Fqdn")) {
      wo.setDpmtRecordState(COMPLETE);
      CmsCISimple resultCi = new CmsCISimple();
      mergeRfcToResult(wo.getRfcCi(), resultCi);
      wo.setResultCi(resultCi);
      logger.info("completing wo without doing anything because dns is off");
    } else {
      // creates the json chefRequest and exec's chef to run chef local or remote via ssh/mc
      runWorkOrder(wo);
    }
  }

  long endTime = System.currentTimeMillis();
  int duration = Math.round((endTime - startTime) / 1000);
  logger.info(format("%s %s %s %s took: %d sec",
      wo.getRfcCi().getRfcAction(),
      wo.getRfcCi().getImpl(),
      wo.getRfcCi().getCiClassName(),
      wo.getRfcCi().getCiName(),
      duration));

  setTotalExecutionTime(wo, endTime - startTime);
  wo.putSearchTag(RESPONSE_ENQUE_TS, DateUtil.formatDate(new Date(), SEARCH_TS_PATTERN));
  return buildResponseMessage(wo, correlationId);
}
 
Example #14
Source File: AbstractOrderExecutor.java    From oneops with Apache License 2.0 4 votes vote down vote up
private long getTimeElapsed(CmsWorkOrderSimpleBase wo) throws DateParseException {
  return System.currentTimeMillis() - DateUtil
      .parseDate(getSearchTag(wo, REQUEST_DEQUE_TS), SEARCH_TS_FORMATS).getTime();
}
 
Example #15
Source File: SOLRAPIClient.java    From SearchServices with GNU Lesser General Public License v3.0 4 votes vote down vote up
public GetTextContentResponse getTextContent(Long nodeId, QName propertyQName, Long modifiedSince) throws AuthenticationException, IOException {
    StringBuilder url = new StringBuilder(128);
    url.append(GET_CONTENT);
    
    StringBuilder args = new StringBuilder(128);
    if(nodeId != null)
    {
        args.append("?");
        args.append("nodeId");
        args.append("=");
        args.append(nodeId);            
    }
    else
    {
        throw new NullPointerException("getTextContent(): nodeId cannot be null.");
    }
    if(propertyQName != null)
    {
        if(args.length() == 0)
        {
            args.append("?");
        }
        else
        {
            args.append("&");
        }
        args.append("propertyQName");
        args.append("=");
        args.append(URLEncoder.encode(propertyQName.toString()));
    }
    
    url.append(args);
    
    GetRequest req = new GetRequest(url.toString());
    
    Map<String, String> headers = new HashMap<>();
    if(modifiedSince != null)
    {
        headers.put("If-Modified-Since", String.valueOf(DateUtil.formatDate(new Date(modifiedSince))));
    }
    if (compression)
    {
        headers.put("Accept-Encoding", "gzip");
    }
    req.setHeaders(headers);
    
    Response response = repositoryHttpClient.sendRequest(req);
    
    if(response.getStatus() != Status.STATUS_NOT_MODIFIED && response.getStatus() != Status.STATUS_NO_CONTENT && response.getStatus() != Status.STATUS_OK)
    {
        int status = response.getStatus();
        response.release();
        throw new AlfrescoRuntimeException("GetTextContentResponse return status is " + status);
    }

    return new GetTextContentResponse(response);
}
 
Example #16
Source File: CookieSpecBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
  * Parse the cookie attribute and update the corresponsing {@link Cookie}
  * properties.
  *
  * @param attribute {@link HeaderElement} cookie attribute from the
  * <tt>Set- Cookie</tt>
  * @param cookie {@link Cookie} to be updated
  * @throws MalformedCookieException if an exception occurs during parsing
  */

public void parseAttribute(
    final NameValuePair attribute, final Cookie cookie)
    throws MalformedCookieException {
        
    if (attribute == null) {
        throw new IllegalArgumentException("Attribute may not be null.");
    }
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null.");
    }
    final String paramName = attribute.getName().toLowerCase();
    String paramValue = attribute.getValue();

    if (paramName.equals("path")) {

        if ((paramValue == null) || (paramValue.trim().equals(""))) {
            paramValue = "/";
        }
        cookie.setPath(paramValue);
        cookie.setPathAttributeSpecified(true);

    } else if (paramName.equals("domain")) {

        if (paramValue == null) {
            throw new MalformedCookieException(
                "Missing value for domain attribute");
        }
        if (paramValue.trim().equals("")) {
            throw new MalformedCookieException(
                "Blank value for domain attribute");
        }
        cookie.setDomain(paramValue);
        cookie.setDomainAttributeSpecified(true);

    } else if (paramName.equals("max-age")) {

        if (paramValue == null) {
            throw new MalformedCookieException(
                "Missing value for max-age attribute");
        }
        int age;
        try {
            age = Integer.parseInt(paramValue);
        } catch (NumberFormatException e) {
            throw new MalformedCookieException ("Invalid max-age "
                + "attribute: " + e.getMessage());
        }
        cookie.setExpiryDate(
            new Date(System.currentTimeMillis() + age * 1000L));

    } else if (paramName.equals("secure")) {

        cookie.setSecure(true);

    } else if (paramName.equals("comment")) {

        cookie.setComment(paramValue);

    } else if (paramName.equals("expires")) {

        if (paramValue == null) {
            throw new MalformedCookieException(
                "Missing value for expires attribute");
        }

        try {
            cookie.setExpiryDate(DateUtil.parseDate(paramValue, this.datepatterns));
        } catch (DateParseException dpe) {
            LOG.debug("Error parsing cookie date", dpe);
            throw new MalformedCookieException(
                "Unable to parse expiration date parameter: " 
                + paramValue);
        }
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unrecognized cookie attribute: " 
                + attribute.toString());
        }
    }
}