下面列出了怎么用org.apache.commons.httpclient.util.DateUtil的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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;
}
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;
}
}
@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));
}
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);
}
@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));
}
}
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;
}
}
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;
}
}
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;
}
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;
}
/**
* 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;
}
/**
* 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();
}
private void postExecTags(CmsWorkOrderSimpleBase wo) {
wo.putSearchTag(
CmsConstants.RESPONSE_ENQUE_TS, DateUtil.formatDate(new Date(), SEARCH_TS_PATTERN));
}
/**
* 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);
}
private long getTimeElapsed(CmsWorkOrderSimpleBase wo) throws DateParseException {
return System.currentTimeMillis() - DateUtil
.parseDate(getSearchTag(wo, REQUEST_DEQUE_TS), SEARCH_TS_FORMATS).getTime();
}
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);
}
/**
* 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());
}
}
}