text:
/**
 * @file
 * This implements the C accessable version of the SessionPortListener class using
 * function pointers, and a pass-through implementation of SessionPortListener.
 */

/******************************************************************************
 * Copyright (c) 2009-2014 AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/

#include <alljoyn/KeyStoreListener.h>
#include <alljoyn_c/KeyStoreListener.h>
#include <string.h>
#include <assert.h>
#include <qcc/Debug.h>

#define QCC_MODULE "ALLJOYN_C"

namespace ajn {

/**
 * Abstract base class implemented by AllJoyn users and called by AllJoyn to inform
 * users of keystore related events.
 */
class KeyStoreListenerCallbackC : public KeyStoreListener {
  public:
    KeyStoreListenerCallbackC(const alljoyn_keystorelistener_callbacks* in_callbacks, const void* in_context)
    {
        QCC_DbgTrace(("%s", __FUNCTION__));
        memcpy(&callbacks, in_callbacks, sizeof(alljoyn_keystorelistener_callbacks));
        context = in_context;
    }

    virtual QStatus LoadRequest(KeyStore& keyStore)
    {
        QCC_DbgTrace(("%s", __FUNCTION__));
        assert(callbacks.load_request != NULL && "load_request callback required.");
        return callbacks.load_request(context, (alljoyn_keystorelistener) this, (alljoyn_keystore)(&keyStore));
    }

    virtual QStatus StoreRequest(KeyStore& keyStore)
    {
        QCC_DbgTrace(("%s", __FUNCTION__));
        assert(callbacks.store_request != NULL && "store_request callback required.");
        return callbacks.store_request(context, (alljoyn_keystorelistener) this, (alljoyn_keystore)(&keyStore));
    }
  protected:
    alljoyn_keystorelistener_callbacks callbacks;
    const void* context;
};

}

struct _alljoyn_keystorelistener_handle {
    /* Empty by design, this is just to allow the type restrictions to save coders from themselves */
};

alljoyn_keystorelistener AJ_CALL alljoyn_keystorelistener_create(const alljoyn_keystorelistener_callbacks* callbacks, const void* context)
{
    QCC_DbgTrace(("%s", __FUNCTION__));
    assert(callbacks->load_request != NULL && "load_request callback required.");
    assert(callbacks->store_request != NULL && "store_request callback required.");
    return (alljoyn_keystorelistener) new ajn::KeyStoreListenerCallbackC(callbacks, context);
}

void AJ_CALL alljoyn_keystorelistener_destroy(alljoyn_keystorelistener listener)
{
    QCC_DbgTrace(("%s", __FUNCTION__));
    assert(listener != NULL && "listener parameter must not be NULL");
    delete (ajn::KeyStoreListenerCallbackC*)listener;
}

QStatus AJ_CALL alljoyn_keystorelistener_putkeys(alljoyn_keystorelistener listener, alljoyn_keystore keyStore,
                                                 const char* source, const char* password)
{
    QCC_DbgTrace(("%s", __FUNCTION__));
    ajn::KeyStore& ks = *((ajn::KeyStore*)keyStore);
    return ((ajn::KeyStoreListener*)listener)->PutKeys(ks, source, password);
}

QStatus AJ_CALL alljoyn_keystorelistener_getkeys(alljoyn_keystorelistener listener, alljoyn_keystore keyStore,
                                                 char* sink, size_t* sink_sz)
{
    QCC_DbgTrace(("%s", __FUNCTION__));
    qcc::String sinkStr;
    ajn::KeyStore& ks = *((ajn::KeyStore*)keyStore);
    QStatus ret = ((ajn::KeyStoreListener*)listener)->GetKeys(ks, sinkStr);
    if (sink) {
        strncpy(sink, sinkStr.c_str(), *sink_sz);
        //prevent sting not being nul terminated.
        sink[*sink_sz - 1] = '\0';
    }
    if (*sink_sz < sinkStr.length() + 1) {
        ret = ER_BUFFER_TOO_SMALL;
    }
    *sink_sz = sinkStr.length() + 1;
    return ret;
}


text:
Non-Blocking HTTP Multipart parser
=============================

[![Master build Status](https://travis-ci.org/synchronoss/nio-multipart.svg?branch=master)](https://travis-ci.org/synchronoss/nio-multipart)

Overview
--------
The NIO Multipart project contains a lightweight, generic java library to process multipart requests and responses in a non blocking way and with a configurable, but constant, memory footprint.
It integrates gracefully with the Servlet 3.1 NIO features but it can be easily used in a blocking IO fashion.
The library is intentionally decoupled from the java servlet APIs and it's based on InputStreams and OutputStreams instead.
This makes the library generic and usable for processing not only Http requests, but also Http responses and potentially other transport protocols.
It is also a good solution for Android given its reduced dependencies tree.

Requires JDK 1.7 or higher.

Latest release
--------------
```xml
<dependency>
    <groupId>org.synchronoss.cloud</groupId>
    <artifactId>nio-multipart-parser</artifactId>
    <version>1.1.0</version>
</dependency>
```
Get started
-----------
The simplest way to get started is using the simple fluent API provided with the library. Instantiating a parser is straightforward:

```java
NioMultipartParser parser = Multipart.multipart(context).forNio(listener);
```

The only two mandatory arguments are a multipart *context*, holding information about the current request/response, and a *listener* that will be notified on the progress of the parsing.
The following line shows how a context can be created from an *HttpServletRequest*:

```java
MultipartContext context = MultipartContext(request.getContentType(), request.getContentLength(), request.getCharacterEncoding())
```

The listener is where application logic starts. The parser notifies the client when something happens via several methods defined by the *NioMultipartParserListener* interface.
Clients can decide to inline the definition (like the example below) or create a class that implements the interface.
What is important is that the client reacts to the events to implement the desired behaviour.

```java
NioMultipartParserListener listener = new NioMultipartParserListener() {

    @Override
    public void onPartFinished(final StreamStorage partBodyStreamStorage, final Map<String, List<String>> headersFromPart) {
        // The parser completed parsing the part.
        // The parsed headers are available in the headersFromPart map
        // The part body can be read from the partBodyStreamStorage which provides an InputStream
    }

    @Override
    public void onNestedPartStarted(final Map<String, List<String>> headersFromParentPart) {
        // The parser identified that the current part contains a nested multipart body
        // The headers are provided in the headersFromParentPart
        // Like for the level 0 parts, the parser will notify the sub parts completion via the methods onPartFinished(...) and onFormFieldPartFinished(...)
        // When the nested multipart body is finished, the parser will call onNestedPartFinished()
    }

    @Override
    public void onNestedPartFinished() {
        // Called when a nested multipart body has been parsed
    }

    @Override
    public void onAllPartsFinished() {
        // Called when the multipart processing finished (encountered the close boundary). No more parts are available!
    }

    @Override
    public void onError(String message, Throwable cause) {
        // An error happened during the parsing.
        // At this point the parser is in an error state and it cannot process any data anymore.
    }
};
```

The final step is to feed the parser with the bytes of the multipart body. In a Servlet 3.1 scenario it could look something like:

```java
final AsyncContext asyncContext = request.startAsync();
final ServletInputStream inputStream = request.getInputStream();

inputStream.setReadListener(new ReadListener() {

    @Override
    public void onDataAvailable() throws IOException {
        int bytesRead;
        byte bytes[] = new byte[1024];
        while (inputStream.isReady()  && (bytesRead = inputStream.read(bytes)) != -1) {
            // Pass the received bytes into the parser.
            // When something is ready the listener will be called!
            parser.write(bytes, 0, bytesRead);
        }
    }

    @Override
    public void onAllDataRead() throws IOException {
        // NOTE - This method might be called before the parser actually finished the parsing, so parser.close() shouldn't be called without ensuring
        // that listener.onAllPartsFinished() or listener.onError(String message, Throwable cause) has been called.
        // An AsyncListener can be used for this (see below)
    }

    @Override
    public void onError(Throwable throwable) {
        // Here the parser should be closed
        parser.close();
    }
});
```

It is important to close the parser after using it. If an error happens, if the client decides to stop the processing or if the parsing finishes correctly, the parser should be closed
to ensure resources are freed.

In a servlet 3.1 environment, an *AsyncListener* can be used to ensure the parser is closed after finishing the process:

```java
    asyncContext.addListener(new AsyncListener() {
        @Override
        public void onComplete(AsyncEvent event) throws IOException {
            parser.close();
        }

        @Override
        public void onTimeout(AsyncEvent event) throws IOException {
            parser.close();
        }

        @Override
        public void onError(AsyncEvent event) throws IOException {
            parser.close();
        }

        @Override
        public void onStartAsync(AsyncEvent event) throws IOException {
            // Nothing to do.
        }
    });
```

Similar events are provided by Spring, like *DeferredResultProcessingInterceptor.afterCompletion(NativeWebRequest request, DeferredResult<T> deferredResult)*

Advanced configuration
----------------------
There are several configuration items that a client can use to tweak or change the parser behaviour:

* Buffer size.
* Headers section max size.
* Threshold after which data collected while parsing a part body is flushed to a temporary file.
* Location of the temporary files.
* Nested multipart limit.

##### Buffer size
The parser to execute its task is using a buffer that by default is 16kb. This buffer has just one requirement: It must be greater than the delimiter + 4.
Every time the buffer is full and it needs to accept more data, it is flushed to an *OutputStream* and in the case of a part body it is usually a *FileOutputStream*.
Increasing the buffer size can reduce the File IO operations.
The recommendation is to stick with the default and adjust it just if it becomes clearly an issue.

##### Headers Section max size
This threshold is a safe-guard to avoid filling the memory if bad clients are sending a header section that is too big.
The parser is reading the entire header section in memory before parsing it and transforming it to a java map.
The headers section max sizes imposes a limit for the size of the headers section and by default is 16kb.
The suggestion is to keep the default value or set it to the value used in the application servers/load balancers used in the production environment.

##### Threshold after which data collected while parsing a part body is flushed to a temporary file
This configuration is only valid if the *DefaultPartBodyStreamStorageFactory* is used (which is the default choice if the user does not specify an alternative).
The *PartBodyStreamStorageFactory* is providing to the parser the *StreamStorage* where to store the part body.
The *DefaultPartBodyStreamStorageFactory* is using the *DeferredFileStreamStorage*, where data is kept in memory until a certain threshold is reached.
If the threshold is reached, the memory is cleared and the data is stored into a temporary file.
This approach allows to limit the creation of temporary files (hence disk IO traffic) if the part body is small (for example if it is a form field)
The default value is 10kb and it can be adjusted based on the amount of memory available and/or the traffic model.
If the value is set to 0 (or negative number) it means that no memory will be used and a temporary file will always be created.

##### Location of the temporary files
Like the configuration above, this setting is is only valid if the *DefaultPartBodyStreamStorageFactory* is used.
By default the temporary files are stored to *${java.io.tmpdir}/nio-file-upload* with a unique name like *nio-body-${uuid}-${part-index}.tmp*.
The path can be changed point to a different location. The folder must be writable otherwise the parser will throw an error.
The *DefaultPartBodyStreamStorageFactory* is trying to keep the disk usage as low as possible and that's why when a file is read, it is deleted.
In other words, the *onPartFinished* event is providing a *StreamStorage* that can be used to retrieve the InputStream for the part body.
When the InputStream is closed the underlying file (if any) is deleted.

##### Nested multipart limit
As already mentioned, the parser supports nested multipart bodies.
This configuration is a safeguard that limits the number of nested multipart bodies that can be processed.
If the limit is reached the parser will finish with an error.
By default is 1 and it is usually sufficient for most of the cases (like http forms with multiple files under the same field).

All the above configurations can be set using the fluent API:

```java
NioMultipartParser parser = Multipart.multipart(context)
                .withBufferSize(8000)// 8kb
                .withHeadersSizeLimit(8000)// 8kb
                .withMaxMemoryUsagePerBodyPart(0) // Always create a temp file
                .saveTemporaryFilesTo("/tmp/file_upload")// Different temp file location
                .limitNestingPartsTo(2) // Allow two level of nesting
                .forNio(listener);
```

Alternatively the constructors can be used (useful if used along with a dependency injection framework).
It is important to keep in mind that a new parser **MUST** be instantiated per each request/response, so it cannot be mapped as a singleton scoped bean.

##### Form parameters
Originally the _NioMultipartParserListener_ had a specific callback for form parameters and it was returning the parameter name and the parameter value as String in the callback.
There was no control over the size of the parameter value and this could have cause memory problems.
The new versions of the library is not exposing the callback anymore, but a form parameter is notified via the _onPartFinished(...)_ method.
Users can rely on utility methods provided by this library or write custom logic to process the form parameters.

Following there is an example of how a user can use the utility methods provided by the library to handle form parameters:
```java
// Create the MultipartContext from the HttpServletRequest
String contentType = request.getContentType();
int contentLength = request.getContentLength();
String charEncoding = request.getCharacterEncoding();
MultipartContext ctx = MultipartContext(contentType, contentLength, charEncoding);

// Create the NioMultipartParserListener with specific logic to handle form parameters.
NioMultipartParserListener listener = new NioMultipartParserListener() {

    @Override
    public void onPartFinished(final StreamStorage partBodyStreamStorage, final Map<String, List<String>> headersFromPart) {
        if (MultipartUtils.isFormField(headersFromPart, ctx)) {

            // The part is a form field, read the parameter name and parameter value.

            final String fieldName = MultipartUtils.getFieldName(headersFromPart);

            // Note that this will consume the partBodyStreamStorage InputStream and load it in memory.
            // Care should be taken by the user to avoid OutOfMemory issues.
            final String fieldValue = MultipartUtils.readFormParameterValue(partBodyStreamStorage, headersFromPart);

        }else{

            // The part is not a form field.

        }
    }
    // ...
}
```

A powerful extension point
--------------------------
As mentioned earlier, the parser uses a *PartBodyStreamStorageFactory* component that is responsible of providing a *StreamStorage* object where the part body can be stored and read back.
By default the parser is using the *DefaultPartBodyStreamStorageFactory* and the *DeferredFileStreamStorage*, but clients with specific needs can provide their own implementations.
Suppose that a client wants to store the file directly to a database based on the presence of a specific header.
Well, this is possible defining a custom *PartBodyStreamStorageFactory*:

```java
public class DBPartBodyStreamStorageFactory extends DefaultPartBodyStreamStorageFactory{

    @Override
    public PartStreams newStreamStorageForPartBody(Map<String, List<String>> headers, int partIndex) {
        if (MultipartUtils.getHeader("x-store-to-database", headers) != null){

            // x-store-to-database header is present, return a StreamStorage capable of storing data into a DB...
            return new StreamStorage() {

                @Override
                public void write(int b) throws IOException {
                    // Write byte into the database!
                }

                @Override
                public InputStream getInputStream() {
                    // Here return null because there is no need to read the body back!
                    return null;
                }
            };
        }else {
            // If the header is not present just use the default...
            return super.newStreamStorageForPartBody(headers, partIndex);
        }
    };
}
```

The code snipped above is an example of how a custom *PartBodyStreamStorageFactory*.
When the parser encounters a part body, it will ask the *PartBodyStreamStorageFactory* for the *StreamStorage* where the data will be written.
In the example if the part header *x-store-to-database* is set, the *StreamStorage* will write to a database (and not to a temporary file).
Once the parser finishes processing the part, it will notify passing back the *StreamStorage* via the callback *onPartFinished*.
The client does not need to read back the data because it's already in the database, so the *getInputStream()* method is returning null.
In the default case, where the *StreamStorage* is a temporary file, reading back the stored body is usually needed.

The custom *PartBodyStreamStorageFactory* can be passed to the parser via the appropriate constructor or using the fluent API (see example)

```java
NioMultipartParser parser = Multipart.multipart(context)
                .usePartBodyStreamStorageFactory(dbPartStreamFactory)
                .forNio(listener);
```

This kind of customization can be used to achieve numerous goals. For example it might be possible to compute the file checksum on fly while data are written to the *StreamStorage*.
Other scenarios can be the on-fly indexing of the content or file metadata extraction.

Still using Blocking IO? No Problem
-----------------------------------
If you are still using blocking IO and for some reason you don't need to (or you cannot) switch to NIO, the library provides an adapter that makes the *NioMultipartParser* working with blocking IO.
The adapter will simply return a *Iterator* over the parts. The *next()* and *hasNext()* methods will block if there is no available data.
The iterator has to be closed to free the resources used by the parser, so the actual type returned by the adapter is a *CloseableIterator*.
To parse a multipart stream in a blocking fashion, the easier way is to use the fluent API:

```java
final InputStream inputStream = request.getInputStream();
CloseableIterator<PartToken> partTokens = Multipart.multipart(context).forBlockingIO(inputStream);

while(partTokens.hasNext()){
    PartToken partToken = parts.next();
    PartItem.Type partTokenType = partToken.getType();
    switch(partTokenType){
        case PART:
            Part part = (Part)partToken;
            final Map<String, List<String>> headers = part.getHeaders();
            final InputStream body = part.getPartBody();
            break;
        case NESTED_START:
            // A marker to keep track of nested multipart and it gives access to the headers...
            NestedStart nestedStart = (NestedStart)partToken;
            final Map<String, List<String>> headers = nestedStart.getHeaders();
            break;
        case NESTED_END:
            // Just a marker but it might be used to keep track of nested multipart...
            break;
        default:
            break;// Impossible
    }
}

partTokens.close();

```

Additional configuration can be added in the same way it can be added when working in NIO mode.
Moreover, if the fluent API is not the best strategy for the use case, the adapter can be instantiated directly (see the *BlockingIOAdapter* class).

As it can be seen in the example above, the *PartItem* is just an interface and there are four different implementations:

* FormParameter: Represents a form parameter and the field name and field value can be extracted directly via getter methods. The part's headers can be obtained as well.
* Attachment: Represents a part that is not a form parameter. In this case the part body can be read using the *InputStream* returned by *getPartBody*.
* NestedStart: Represents a part that is itself a multipart. It provides the headers, while the nested parts will be returned as next items in the iterator.
* NestedEnd: Signals the end of a nested part. This is just a marker and it carries no data, but it can be useful to keep track of the nesting of the multipart messages.

Nio Multipart Parser - Internal Building Blocks
-----------------------------------------------
This section is mainly for Developers that want to get a more detailed view of the internals of the NIO Multipart parser.
The NIO Multipart Parser is build on top of 3 main building blocks:

* A reusable, fixed-size circular buffer.
* A reusable, fixed size End Of Line Buffer.
* A Final State machine.

##### Circular (or Ring) Buffer
A *Circular Buffer* is a data structure where the end of the buffer is connected to the beginning forming a circle.
When data is read from the buffer there is no need to reshuffle its elements and when the buffer is full (if no action is taken) the oldest bytes are overwritten.
The schema below shows how a *Circular Buffer* works
![Circular Buffer](docs/diagrams/nio-multipart-circular-buffer.png)

##### End Of Line Buffer
An *End Of Line Buffer* is built on top of the *Circular Buffer* and at each write it watches for an *End Of Line Sequence*
A few things can happen during a write:

* No End Of Line Sequence is identified and the buffer still has capacity => The data is written to the buffer and a check for the End Of Line Sequence is performed against the new data.
* No End Of Line Sequence is identified, but the buffer is full => Before writing, the buffer data is flushed to an OutputStream. The new data is written and the End Of Line Sequence checking is performed against the new data.
* End Of Line Sequence partially identified and the buffer still has capacity => The data is written to the buffer and a check for the End Of Line Sequence is performed against the new data.
* End Of Line Sequence partially identified and the buffer is full => Before writing, the buffer data (Excluded the EoL sequence) is flushed to an OutputStream. The new data is written and the End Of Line Sequence checking is continued against the new data.
* If the buffer has a partial match of the EoL and the new data written is not matching the rest of the EoL sequence, the state of the EoL matching is re-set.
* If the buffer has a partial match of the EoL and the new data written matches the rest of the EoL sequence it means that an End Of Line Sequence has been identified. The buffer data (End Of Line Sequence excluded) is flushed to the OutputStream and the buffer is than non writable anymore.

The *End Of Line Buffer* is used by the parser to identify the different sections of the multipart (Preamble, Headers, Body, Epilogue).
Each of these section is separated by a well defined End Of Line Sequence (e.g. multipart boundary, CRLF).
The Nio Multipart parser is setting up the *End Of Line Buffer* with the correct End Of Line Sequence for the specific section before starting processing the section.

It should be clear now why the buffer size **MUST** always be bigger than the EoL sequence.
A buffer with not enough capacity for the EoL would end up in a state where the buffer is full but it cannot be flushed because there is a partially matching EoL.

The following diagram shows the *End Of Line Buffer* in action:
![End Of Line Buffer](docs/diagrams/nio-multipart-eol-buffer.png)

##### The Parser Final State Machine
The parsing logic is implemented as a Final State Machine.
While data is written into the parser, the final state machine is executed.
The following diagram shows the states and transitions of the Final State Machine executed by the parser:

![Final State Machine](docs/diagrams/nio-multipart-fsm.png)

In the following schema, the left side is an example of multipart message, while the right side is showing what are the EoL sequences the parser is looking for.
![Multipart Message Structure](docs/diagrams/nio-multipart-message-structure.png)

References
----------
[RFC1867](http://www.ietf.org/rfc/rfc1867.txt)

[RFC1521](http://www.ietf.org/rfc/rfc1521.txt)

[RFC1522](http://www.ietf.org/rfc/rfc1522.txt)

redpajama_set_name: RedPajamaGithub


text:
package com.sherry.common;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sherry.common.util.MyFileUtils;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class Constants {

	public static Logger logger = Logger.getLogger("syx");

	public static String dateTimeToString(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String ret = sdf.format(date);
		return ret;
	}

	public static Date stringToDateTime(String sdate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = null;
		try {
			date = sdf.parse(sdate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}

	public static Date weixinDateStringToDateTime(String wdate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date date = null;
		try {
			date = sdf.parse(wdate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return date;
	}

	public static String dateToString(Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String ret = sdf.format(date);
		return ret;
	}

	public static String longDateToString(long time) {
		Timestamp date = new Timestamp(time);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String ret = sdf.format(date);
		return ret;
	}

	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$");
		return pattern.matcher(str).matches();
	}

	public static String getSmallByOrigin(String name) {
		String name1 = name.substring(0, name.lastIndexOf("."));
		String suffix = name.substring(name.lastIndexOf("."));
		return name1 + "-s" + suffix;
	}

	private static final String STR_FORMAT = "00000";

	public static final String getPatientCode(int reint) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String code = sdf.format(new Date());
		int codeID = reint % 100000;
		DecimalFormat df = new DecimalFormat(STR_FORMAT);
		String codeL = df.format(codeID);
		code = code + codeL;
		return code;

	}

	public static final String testMakJson() {

		ObjectMapper objectMapper = JacksonMapper.getInstance();

		List sellMedicalList = new ArrayList();
		Map sellMedical = new HashMap();
		sellMedical.put("fkUserMedicalId", 2);
		sellMedical.put("changeNum", 1);
		sellMedical.put("changePrice", 1);
		sellMedicalList.add(sellMedical);
		Map sellMedical2 = new HashMap();
		sellMedical2.put("fkUserMedicalId", 4);
		sellMedical2.put("changeNum", 1);
		sellMedical2.put("changePrice", 1);
		sellMedicalList.add(sellMedical2);

		String retStr = "";
		try {
			retStr = objectMapper.writeValueAsString(sellMedicalList);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return retStr;

	}

	public static final void testParseJson(String jsonstr) {

		ObjectMapper objectMapper = JacksonMapper.getInstance();

		try {
			List<HashMap<String, Object>> list = objectMapper.readValue(jsonstr, List.class);
			System.out.println(list.size());
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = list.get(i);
				Set<String> set = map.keySet();
				for (Iterator<String> it = set.iterator(); it.hasNext();) {
					String key = it.next();
					System.out.println(key + ":" + map.get(key));
				}
			}
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static final String saveTwoDimensionCode(String url) {

		String imgPath = null;
		try {
			imgPath = MyFileUtils.getValueFromProperties("savePicUrl")+File.separator+"twoDimension"+File.separator;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String imgName = UUID.randomUUID().toString().trim().replaceAll("-", "")+".png";
		if (!new File(imgPath).exists()) {
			new File(imgPath).mkdirs();
		}

//		TwoDimensionCode handler = new TwoDimensionCode();
//		handler.encoderQRCode(url, imgPath+imgName, "png");

		String ret = null;
		try {
			ret = MyFileUtils.getValueFromProperties("PROJECT_URL")+"/upload/pic/twoDimension/"+imgName;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}

	public static void main(String[] args) {

		String text = "34#4%6*8";
		String questionId = text.substring(0, text.indexOf("#"));
		String optionContent = text.substring(text.indexOf("#") + 1, text.length());

		System.out.println("questionId--" + questionId);
		System.out.println("optionContent--" + optionContent);
		System.out.println("test--" + text.split("\\*")[0]);
		System.out.println("test--" + getPatientCode(12));
		System.out.println("testJson--" + testMakJson());

		String jsonstr = "[{\"fkUserMedicalId\":2,\"changePrice\":1,\"changeNum\":1},{\"fkUserMedicalId\":4,\"changePrice\":1,\"changeNum\":1}]";
		testParseJson(jsonstr);
		System.out.println("timeToHex()--" + timeToHex());

		System.out.println("stringToDateTime()--" + weixinDateStringToDateTime("20141030133525"));

		System.out.println("stringToDateTime()--" + stringToDateTime("2016-06-26 23:00:16").getTime());

		System.out.println("saveTwoDimensionCode--" +saveTwoDimensionCode("http://www.baidu.com"));

		Double x = 0.1;
		Double y = 0.1;
		System.out.println("x==y--" + (x==y));
		System.out.println("x.equals(y)--" + (x.equals(y)));
		System.out.println("double--" + String.valueOf((int)(1*100)));

	}

	/**
	 * 获取8位不重复随机码(取当前时间戳转化为十六进制)
	 *
	 * @author ShelWee
	 * @return
	 */
	public static String timeToHex() {
		return Integer.toHexString((int) (new Date().getTime()));
	}

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindReferences;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.FindAllReferences;
using Microsoft.VisualStudio.Shell.TableManager;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Completion;
using System.Diagnostics;

namespace Microsoft.VisualStudio.LanguageServices.FindReferences
{
    internal partial class StreamingFindReferencesPresenter
    {
        private class TableDataSourceFindReferencesContext :
            FindReferencesContext, ITableDataSource, ITableEntriesSnapshotFactory
        {
            private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();

            private ITableDataSink _tableDataSink;

            public readonly StreamingFindReferencesPresenter Presenter;
            private readonly IFindAllReferencesWindow _findReferencesWindow;

            // Lock which protects _definitionToShoudlShowWithoutReferences,
            // _definitionToBucket, _entries, _lastSnapshot and CurrentVersionNumber
            private readonly object _gate = new object();

            private readonly List<DefinitionItem> _definitions = new List<DefinitionItem>();

            /// <summary>
            /// We will hear about the same definition over and over again.  i.e. for each reference
            /// to a definition, we will be told about the same definition.  However, we only want to
            /// create a single actual <see cref="DefinitionBucket"/> for the definition. To accomplish
            /// this we keep a map from the definition to the task that we're using to create the
            /// bucket for it.  The first time we hear about a definition we'll make a single task
            /// and then always return that for all future references found.
            /// </summary>
            private readonly Dictionary<DefinitionItem, RoslynDefinitionBucket> _definitionToBucket =
                new Dictionary<DefinitionItem, RoslynDefinitionBucket>();

            private ImmutableList<Entry> _entries = ImmutableList<Entry>.Empty;
            private TableEntriesSnapshot _lastSnapshot;
            public int CurrentVersionNumber { get; private set; }

            public TableDataSourceFindReferencesContext(
                 StreamingFindReferencesPresenter presenter,
                 IFindAllReferencesWindow findReferencesWindow)
            {
                presenter.AssertIsForeground();

                Presenter = presenter;
                _findReferencesWindow = findReferencesWindow;

                // If the window is closed, cancel any work we're doing.
                _findReferencesWindow.Closed += (s, e) => CancelSearch();

                // Remove any existing sources in the window.
                foreach (var source in findReferencesWindow.Manager.Sources.ToArray())
                {
                    findReferencesWindow.Manager.RemoveSource(source);
                }

                // And add ourselves as the source of results for the window.
                findReferencesWindow.Manager.AddSource(this);

                // After adding us as the source, the manager should immediately call into us to
                // tell us what the data sink is.
                Debug.Assert(_tableDataSink != null);
            }

            private void CancelSearch()
            {
                Presenter.AssertIsForeground();
                _cancellationTokenSource.Cancel();
            }

            internal void OnSubscriptionDisposed()
            {
                CancelSearch();
            }

            public override CancellationToken CancellationToken => _cancellationTokenSource.Token;

            #region ITableDataSource

            public string DisplayName => "Roslyn Data Source";

            public string Identifier => RoslynFindReferencesTableDataSourceIdentifier;

            public string SourceTypeIdentifier => RoslynFindReferencesTableDataSourceSourceTypeIdentifier;

            public IDisposable Subscribe(ITableDataSink sink)
            {
                Presenter.AssertIsForeground();

                Debug.Assert(_tableDataSink == null);
                _tableDataSink = sink;

                _tableDataSink.AddFactory(this, removeAllFactories: true);
                _tableDataSink.IsStable = false;

                return this;
            }

            #endregion

            #region FindReferencesContext overrides.

            public override void SetSearchLabel(string displayName)
            {
                var labelProperty = _findReferencesWindow.GetType().GetProperty("Label");
                if (labelProperty != null)
                {
                    labelProperty.SetValue(_findReferencesWindow, displayName);
                }
            }

            public override void OnCompleted()
            {
                // Now that we know the search is over, create and display any error messages
                // for definitions that were not found.
                CreateMissingReferenceEntriesIfNecessary();
                CreateNoResultsFoundEntryIfNecessary();

                _tableDataSink.IsStable = true;
            }

            private void CreateNoResultsFoundEntryIfNecessary()
            {
                bool noDefinitions;
                lock(_gate)
                {
                    noDefinitions = this._definitions.Count == 0;
                }

                if (noDefinitions)
                {
                    // Create a fake definition/reference called "search found no results"
                    this.OnEntryFound(NoResultsDefinitionItem,
                        (db, c) => SimpleMessageEntry.CreateAsync(
                            db, ServicesVisualStudioNextResources.Search_found_no_results));
                }
            }

            private static DefinitionItem NoResultsDefinitionItem =
                DefinitionItem.CreateNonNavigableItem(
                    GlyphTags.GetTags(Glyph.StatusInformation),
                    ImmutableArray.Create(new TaggedText(
                        TextTags.Text,
                        ServicesVisualStudioNextResources.Search_found_no_results)));

            private void CreateMissingReferenceEntriesIfNecessary()
            {
                // Go through and add dummy entries for any definitions that
                // that we didn't find any references for.

                var definitions = GetDefinitionsToCreateMissingReferenceItemsFor();
                foreach (var definition in definitions)
                {
                    // Create a fake reference to this definition that says
                    // "no references found to <symbolname>".
                    OnEntryFound(definition,
                        (db, c) => SimpleMessageEntry.CreateAsync(
                            db, GetMessage(db.DefinitionItem)));
                }
            }

            private static string GetMessage(DefinitionItem definition)
            {
                if (definition.IsExternal)
                {
                    return ServicesVisualStudioNextResources.External_reference_found;
                }

                return string.Format(
                    ServicesVisualStudioNextResources.No_references_found_to_0,
                    definition.DisplayParts.JoinText());
            }

            private ImmutableArray<DefinitionItem> GetDefinitionsToCreateMissingReferenceItemsFor()
            {
                lock (_gate)
                {
                    // Find any definitions that we didn't have any references to. But only show
                    // them if they want to be displayed without any references.  This will
                    // ensure that we still see things like overrides and whatnot, but we
                    // won't show property-accessors.
                    var seenDefinitions = this._entries.Select(r => r.DefinitionBucket.DefinitionItem).ToSet();
                    var q = from definition in _definitions
                            where !seenDefinitions.Contains(definition) &&
                                  definition.DisplayIfNoReferences
                            select definition;

                    // If we find at least one of these tyeps of definitions, then just return those.
                    var result = ImmutableArray.CreateRange(q);
                    if (result.Length > 0)
                    {
                        return result;
                    }

                    // We found no definitions that *want* to be displayed.  However, we still
                    // want to show something.  So, if necessary, show at lest the first definition
                    // even if we found no references and even if it would prefer to not be seen.
                    if (_entries.Count == 0 && _definitions.Count > 0)
                    {
                        return ImmutableArray.Create(_definitions.First());
                    }

                    return ImmutableArray<DefinitionItem>.Empty;
                }
            }

            public override void OnDefinitionFound(DefinitionItem definition)
            {
                lock (_gate)
                {
                    _definitions.Add(definition);
                }

                foreach (var location in definition.SourceSpans)
                {
                    OnEntryFound(definition,
                        (db, c) => CreateDocumentLocationEntryAsync(
                            db, location, isDefinitionLocation: true, cancellationToken: c));
                }
            }

            public override void OnReferenceFound(SourceReferenceItem reference)
            {
                OnEntryFound(reference.Definition,
                    (db, c) => CreateDocumentLocationEntryAsync(
                        db, reference.SourceSpan, isDefinitionLocation: false, cancellationToken: c));
            }

            private async void OnEntryFound(
                DefinitionItem definition,
                Func<RoslynDefinitionBucket, CancellationToken, Task<Entry>> createEntryAsync)
            {
                try
                {
                    // We're told about this reference synchronously, but we need to get the
                    // SourceText for the definition/reference's Document so that we can determine
                    // things like it's line/column/text.  We don't want to block this method getting
                    // that data, so instead we just fire off the async work to get the text
                    // and use it.  Because we're starting some async work, let the test harness
                    // know so that it doesn't verify results until this completes.
                    using (var token = Presenter._asyncListener.BeginAsyncOperation(nameof(OnReferenceFound)))
                    {
                        await OnEntryFoundAsync(definition, createEntryAsync).ConfigureAwait(false);
                    }
                }
                catch (Exception e) when (FatalError.ReportWithoutCrashUnlessCanceled(e))
                {
                }
            }

            private async Task OnEntryFoundAsync(
                DefinitionItem definition,
                Func<RoslynDefinitionBucket, CancellationToken, Task<Entry>> createEntryAsync)
            {
                var cancellationToken = _cancellationTokenSource.Token;
                cancellationToken.ThrowIfCancellationRequested();

                // First find the bucket corresponding to our definition. If we can't find/create
                // one, then don't do anything for this reference.
                var definitionBucket = GetOrCreateDefinitionBucket(definition);
                if (definitionBucket == null)
                {
                    return;
                }

                var entry = await createEntryAsync(
                    definitionBucket, cancellationToken).ConfigureAwait(false);
                if (entry == null)
                {
                    return;
                }

                lock (_gate)
                {
                    // Once we can make the new entry, add it to our list.
                    _entries = _entries.Add(entry);
                    CurrentVersionNumber++;
                }

                // Let all our subscriptions know that we've updated.
                _tableDataSink.FactorySnapshotChanged(this);
            }

            private async Task<Entry> CreateDocumentLocationEntryAsync(
                RoslynDefinitionBucket definitionBucket,
                DocumentSpan documentSpan,
                bool isDefinitionLocation,
                CancellationToken cancellationToken)
            {
                var document = documentSpan.Document;

                // The FAR system needs to know the guid for the project that a def/reference is
                // from.  So we only support this for documents from a VSWorkspace.
                var workspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
                if (workspace == null)
                {
                    return null;
                }

                var projectGuid = workspace.GetHostProject(document.Project.Id)?.Guid;
                if (projectGuid == null)
                {
                    return null;
                }

                var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

                var referenceSpan = documentSpan.SourceSpan;
                var lineSpan = GetLineSpanForReference(sourceText, referenceSpan);

                var taggedLineParts = await GetTaggedTextForReferenceAsync(document, referenceSpan, lineSpan, cancellationToken).ConfigureAwait(false);

                return new DocumentSpanEntry(
                    this, workspace, definitionBucket, documentSpan,
                    isDefinitionLocation, projectGuid.Value, sourceText, taggedLineParts);
            }

            private TextSpan GetLineSpanForReference(SourceText sourceText, TextSpan referenceSpan)
            {
                var sourceLine = sourceText.Lines.GetLineFromPosition(referenceSpan.Start);
                var firstNonWhitespacePosition = sourceLine.GetFirstNonWhitespacePosition().Value;

                return TextSpan.FromBounds(firstNonWhitespacePosition, sourceLine.End);
            }

            private TextSpan GetRegionSpanForReference(SourceText sourceText, TextSpan referenceSpan)
            {
                const int AdditionalLineCountPerSide = 3;

                var lineNumber = sourceText.Lines.GetLineFromPosition(referenceSpan.Start).LineNumber;
                var firstLineNumber = Math.Max(0, lineNumber - AdditionalLineCountPerSide);
                var lastLineNumber = Math.Min(sourceText.Lines.Count - 1, lineNumber + AdditionalLineCountPerSide);

                return TextSpan.FromBounds(
                    sourceText.Lines[firstLineNumber].Start,
                    sourceText.Lines[lastLineNumber].End);
            }

            private async Task<TaggedTextAndHighlightSpan> GetTaggedTextForReferenceAsync(
                Document document, TextSpan referenceSpan, TextSpan widenedSpan, CancellationToken cancellationToken)
            {
                var classificationService = document.GetLanguageService<IEditorClassificationService>();
                if (classificationService == null)
                {
                    return new TaggedTextAndHighlightSpan(ImmutableArray<TaggedText>.Empty, new TextSpan());
                }

                // Call out to the individual language to classify the chunk of text around the
                // reference. We'll get both the syntactic and semantic spans for this region.
                // Because the semantic tags may override the semantic ones (for example,
                // "DateTime" might be syntactically an identifier, but semantically a struct
                // name), we'll do a later merging step to get the final correct list of
                // classifications.  For tagging, normally the editor handles this.  But as
                // we're producing the list of Inlines ourselves, we have to handles this here.
                var syntaxSpans = new List<ClassifiedSpan>();
                var semanticSpans = new List<ClassifiedSpan>();

                var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);

                await classificationService.AddSyntacticClassificationsAsync(
                    document, widenedSpan, syntaxSpans, cancellationToken).ConfigureAwait(false);
                await classificationService.AddSemanticClassificationsAsync(
                    document, widenedSpan, semanticSpans, cancellationToken).ConfigureAwait(false);

                var allParts = MergeClassifiedSpans(
                    syntaxSpans, semanticSpans, widenedSpan, sourceText);
                var taggedText = allParts.ToTaggedText();

                var highlightSpan = new TextSpan(
                    start: referenceSpan.Start - widenedSpan.Start,
                    length: referenceSpan.Length);

                return new TaggedTextAndHighlightSpan(taggedText, highlightSpan);
            }

            private List<SymbolDisplayPart> MergeClassifiedSpans(
                List<ClassifiedSpan> syntaxSpans, List<ClassifiedSpan> semanticSpans,
                TextSpan widenedSpan, SourceText sourceText)
            {
                // The spans produced by the language services may not be ordered
                // (indeed, this happens with semantic classification as different
                // providers produce different results in an arbitrary order).  Order
                // them first before proceeding.
                Order(syntaxSpans);
                Order(semanticSpans);

                // Produce SymbolDisplayParts for both sets of ClassifiedSpans.  This will
                // also produce parts for the regions between the sections that the classifiers
                // returned results for (i.e. for things like spaces and plain text).
                var syntaxParts = Classifier.ConvertClassifications(
                    sourceText, widenedSpan.Start, syntaxSpans, insertSourceTextInGaps: true);
                var semanticParts = Classifier.ConvertClassifications(
                    sourceText, widenedSpan.Start, semanticSpans, insertSourceTextInGaps: true);

                // Now merge the lists together, taking all the results from syntaxParts
                // unless they were overridden by results in semanticParts.
                return MergeParts(syntaxParts, semanticParts);
            }

            private void Order(List<ClassifiedSpan> syntaxSpans)
            {
                syntaxSpans.Sort((s1, s2) => s1.TextSpan.Start - s2.TextSpan.Start);
            }

            private List<SymbolDisplayPart> MergeParts(
                List<SymbolDisplayPart> syntaxParts,
                List<SymbolDisplayPart> semanticParts)
            {
                // Take all the syntax parts.  However, if any have been overridden by a
                // semantic part, then choose that one.

                // To make life easier, determine the spans for all the parts in the lists.
                var syntaxPartsAndSpans = AddSpans(syntaxParts);
                var semanticPartsAndSpans = AddSpans(semanticParts);

                var finalParts = new List<SymbolDisplayPart>();
                var lastReplacementIndex = 0;
                for (int i = 0, n = syntaxPartsAndSpans.Count; i < n; i++)
                {
                    var syntaxPartAndSpan = syntaxPartsAndSpans[i];

                    // See if we can find a semantic part to replace this syntax part.
                    var replacementIndex = semanticPartsAndSpans.FindIndex(
                        lastReplacementIndex, t => t.Item2 == syntaxPartAndSpan.Item2);

                    var part = replacementIndex >= 0 && ShouldUseSemanticPart(semanticPartsAndSpans[replacementIndex])
                        ? semanticPartsAndSpans[replacementIndex].Item1
                        : syntaxPartAndSpan.Item1;
                    finalParts.Add(part);

                    if (replacementIndex >= 0)
                    {
                        // If we found a semantic replacement, update the lastIndex.
                        // That way we can start searching from that point instead
                        // of checking all the elements each time.
                        lastReplacementIndex = replacementIndex + 1;
                    }
                }

                return finalParts;
            }

            private bool ShouldUseSemanticPart(ValueTuple<SymbolDisplayPart, TextSpan> partAndSpan)
            {
                // Don't take 'text' from the semantic parts.  We'll get those for the
                // spaces between the actual interesting semantic spans, and we don't
                // want them to override actual good syntax spans.
                return partAndSpan.Item1.Kind != SymbolDisplayPartKind.Text;
            }

            private List<ValueTuple<SymbolDisplayPart, TextSpan>> AddSpans(
                List<SymbolDisplayPart> parts)
            {
                var result = new List<ValueTuple<SymbolDisplayPart, TextSpan>>(parts.Count);
                var position = 0;

                foreach (var part in parts)
                {
                    var partLength = part.ToString().Length;
                    result.Add(ValueTuple.Create(part, new TextSpan(position, partLength)));

                    position += partLength;
                }

                return result;
            }

            private RoslynDefinitionBucket GetOrCreateDefinitionBucket(DefinitionItem definition)
            {
                lock (_gate)
                {
                    RoslynDefinitionBucket bucket;
                    if (!_definitionToBucket.TryGetValue(definition, out bucket))
                    {
                        bucket = new RoslynDefinitionBucket(Presenter, this, definition);
                        _definitionToBucket.Add(definition, bucket);
                    }

                    return bucket;
                }
            }

            public override void ReportProgress(int current, int maximum)
            {
                //var progress = maximum == 0 ? 0 : ((double)current / maximum);
                //_findReferencesWindow.SetProgress(progress);
            }

            #endregion

            #region ITableEntriesSnapshotFactory

            public ITableEntriesSnapshot GetCurrentSnapshot()
            {
                lock (_gate)
                {
                    // If our last cached snapshot matches our current version number, then we
                    // can just return it.  Otherwise, we need to make a snapshot that matches
                    // our version.
                    if (_lastSnapshot?.VersionNumber != CurrentVersionNumber)
                    {
                        _lastSnapshot = new TableEntriesSnapshot(_entries, CurrentVersionNumber);
                    }

                    return _lastSnapshot;
                }
            }

            public ITableEntriesSnapshot GetSnapshot(int versionNumber)
            {
                lock (_gate)
                {
                    if (_lastSnapshot?.VersionNumber == versionNumber)
                    {
                        return _lastSnapshot;
                    }

                    if (versionNumber == CurrentVersionNumber)
                    {
                        return GetCurrentSnapshot();
                    }
                }

                // We didn't have this version.  Notify the sinks that something must have changed
                // so that they call back into us with the latest version.
                _tableDataSink.FactorySnapshotChanged(this);
                return null;
            }

            void IDisposable.Dispose()
            {
                CancelSearch();
            }

            #endregion
        }
    }
}


text:
BoxParser.syncSampleGroupEntry.prototype.parse = function(stream, length) {
	var tmp_byte = stream.readUint8();
	this.NAL_unit_type = tmp_byte & 0x3F;
}