下面列出了java.util.Scanner#useDelimiter ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Processes the data message
* @param inFromClient The input stream from the client
*/
public void processMessage(Scanner inFromClient)
{
inFromClient.useDelimiter(""+Constants.CRLF+"."+Constants.CRLF);
if(inFromClient.hasNext())
{
data = inFromClient.next();
// Clear out buffer
inFromClient.nextLine();
inFromClient.nextLine();
response = "250 OK" + Constants.CRLF;
}
else
{
response = "501 Syntax Error no lines" + Constants.CRLF;
}
}
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response, null if no response
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
String response = null;
if (hasInput) {
response = scanner.next();
}
scanner.close();
return response;
} finally {
urlConnection.disconnect();
}
}
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
/**
* Decodes the query portion of the passed-in URI.
*
* @param encodedURI
* the URI containing the query to decode
* @param results
* a map containing all query parameters. Query parameters that do not have a value will
* map to a null string
*/
static public void DecodeQuery(URI encodedURI, Map<String, String> results) {
Scanner scanner = new Scanner(encodedURI.getRawQuery());
scanner.useDelimiter("&");
try {
while (scanner.hasNext()) {
String param = scanner.next();
String[] valuePair = param.split("=");
String name, value;
if (valuePair.length == 1) {
value = null;
} else if (valuePair.length == 2) {
value = URLDecoder.decode(valuePair[1], "UTF-8");
} else {
throw new IllegalArgumentException("query parameter invalid");
}
name = URLDecoder.decode(valuePair[0], "UTF-8");
results.put(name, value);
}
} catch (UnsupportedEncodingException e) {
// This should never happen.
Log.e(TAG, "UTF-8 Not Recognized as a charset. Device configuration Error.");
}
}
public static Map<String, String> parseQuery(final URI uri, final String encoding) {
if (uri == null || StringUtils.isBlank(uri.getQuery())) {
return Collections.EMPTY_MAP;
}
String query = uri.getRawQuery();
HashMap<String, String> params = new HashMap<String, String>();
@SuppressWarnings("resource")
Scanner scan = new Scanner(query);
scan.useDelimiter(SPLIT);
while (scan.hasNext()) {
String token = scan.next().trim();
String[] pair = token.split(EQUAL);
String key = decode(pair[0], encoding);
String value = null;
if (pair.length == 2) {
value = decode(pair[1], encoding);
}
params.put(key, value);
}
return params;
}
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response, null if no response
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
String response = null;
if (hasInput) {
response = scanner.next();
}
scanner.close();
return response;
} finally {
urlConnection.disconnect();
}
}
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
public static void parse(final HashMap<String, String> parameters, final Scanner scanner, final String encoding) {
scanner.useDelimiter(PARAMETER_SEPARATOR);
while (scanner.hasNext()) {
final String[] nameValue = scanner.next().split(NAME_VALUE_SEPARATOR);
if (nameValue.length == 0 || nameValue.length > 2) {
throw new IllegalArgumentException("bad parameter");
}
final String name = decode(nameValue[0], encoding);
String value = null;
if (nameValue.length == 2) {
value = decode(nameValue[1], encoding);
}
parameters.put(name, value);
}
}
private static void parseStop(DataFile df, String buffer) throws DataParserException {
Scanner vsc = new Scanner(buffer);
vsc.useDelimiter(",");
while (vsc.hasNext()) {
String pair = vsc.next().trim();
try {
if (pair.indexOf('=') < 0) {
throw new Exception("No '=' found");
} else {
float beat = Float.parseFloat(pair.substring(0, pair.indexOf('='))) / 4f;
float value = Float.parseFloat(pair.substring(pair.indexOf('=') + 1)) / 1000f;
df.addStop(beat, value);
}
} catch (Exception e) { // Also catch NumberFormatExceptions
vsc.close();
throw new DataParserException(
e.getClass().getSimpleName(),
"Improperly formatted #FREEZE pair \"" + pair + "\": " +
e.getMessage(), e
);
}
}
vsc.close();
}
public void addDiffsFromFile(String diffName, long addressOffset) throws IOException {
InputStream stream = DiffApplicator.class.getClassLoader().getResourceAsStream(diffName + ".diff");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String currentLine = bufferedReader.readLine();
while(currentLine != null) {
Scanner scanner = new Scanner(currentLine);
scanner.useDelimiter("[\\s\\W]+");
long nextAddress = scanner.nextLong(16);
int existingValue = scanner.nextInt(16);
int newValue = scanner.nextInt(16);
addDiff(new Diff(nextAddress + addressOffset, 1, new byte[] {(byte)(newValue & 0xFF)}, new byte[] {(byte)(existingValue & 0xFF)}));
scanner.close();
currentLine = bufferedReader.readLine();
}
stream.close();
}
public void execute(String[] cmmand, String directory, int type) throws IOException
{
NetInfo netInfo = null;
String sTmp = null;
ProcessBuilder builder = new ProcessBuilder(cmmand);
if (directory != null) {
builder.directory(new File(directory));
}
builder.redirectErrorStream(true);
Process process = builder.start();
InputStream is = process.getInputStream();
Scanner s = new Scanner(is);
s.useDelimiter("\n");
while(s.hasNextLine()){
sTmp = s.nextLine();
netInfo = parseDataNew(sTmp);
if(netInfo!=null) {
netInfo.setType(type);
saveToList(netInfo);
}
}
}
public static void main(String[] args) {
File dataFile = new File("data/Countries.csv");
try {
Scanner input = new Scanner(dataFile);
input.useDelimiter(",|\\s");
String column1 = input.next();
String column2 = input.next();
System.out.printf("%-10s%12s%n", column1, column2);
while (input.hasNext()) {
String country = input.next();
int population = input.nextInt();
System.out.printf("%-10s%,12d%n", country, population);
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
private List<String> getQueries( String queryFile ) throws FileNotFoundException, URISyntaxException
{
URL resource = getClass().getResource( queryFile );
// using new FileReader( ) will assume the platform default encoding, which on Windows is liable to
// be CP1252. This will cause the scanner to split at SectionSign §, but leave the escape
// octet (C2) in the extracted string (appearing as Â).
// Scanner scanner = new Scanner( new FileReader( Paths.get( resource.toURI() ).toFile() ) );
Scanner scanner = new Scanner( Paths.get( resource.toURI() ).toFile() , "UTF-8" );
scanner.useDelimiter( "§\n(//.*\n)*" );
ArrayList<String> queries = new ArrayList<>();
while ( scanner.hasNext() )
{
String next = scanner.next();
queries.add( next );
}
return queries;
}
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
/**
* This method returns the entire result from the HTTP response.
*
* @param url The URL to fetch the HTTP response from.
* @return The contents of the HTTP response.
* @throws IOException Related to network and stream reading
*/
public static String getResponseFromHttpUrl(URL url) throws IOException {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
private String getQuestionContent()
throws Exception
{
String content;
URLConnection connection;
connection = new URL( API_URL ).openConnection();
connection.addRequestProperty( "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" );
Scanner scanner = new Scanner( connection.getInputStream() );
scanner.useDelimiter( "\\Z" );
content = scanner.next();
return content;
}
@Override
public Map<String, String> handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
int statusCode = statusLine.getStatusCode();
if (statusCode == HttpStatus.SC_FORBIDDEN
&& (sp == ServiceProvider.Sina
|| sp == ServiceProvider.NetEase)) {
//在使用XAuth认证方式下,若用户名或密码错误,新浪、网易的响应是403,搜狐的是401,统一为401
statusCode = HttpStatus.SC_UNAUTHORIZED;
}
if (sp == ServiceProvider.Tencent
&& HttpStatus.SC_BAD_REQUEST == statusCode
&& "Bad Request: Unsupported parameter".equals(statusLine.getReasonPhrase())){
statusCode = LibResultCode.OAUTH_TIMESTAMP_REFUSED;
}
throw new LibRuntimeException(statusCode);
}
Map<String, String> resultMap = new HashMap<String, String>();
HttpEntity entity = response.getEntity();
final String responseString = EntityUtils.toString(entity);
Logger.debug("FormEncodedResponseHandler : {}", responseString);
Scanner scanner = new Scanner(responseString);
scanner.useDelimiter("&");
while (scanner.hasNext()) {
final String[] nameValue = scanner.next().split("=");
if (nameValue.length == 0 || nameValue.length > 2){
throw new LibRuntimeException(LibResultCode.E_PARAM_ERROR, "", "Bad Parameter", ServiceProvider.None);
}
final String name = nameValue[0];
String value = null;
if (nameValue.length == 2){
value = nameValue[1];
}
resultMap.put(name, value);
}
return resultMap;
}
@Override
protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException {
try (final BufferedReader in = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8))) {
Host current = null;
String line;
while((line = in.readLine()) != null) {
if(line.startsWith("[")) {
if(current != null) {
this.add(current);
}
current = new Host(protocols.forScheme(Scheme.ftp));
current.getCredentials().setUsername(
PreferencesFactory.get().getProperty("connection.login.anon.name"));
Pattern pattern = Pattern.compile("\\[(.*)\\]");
Matcher matcher = pattern.matcher(line);
if(matcher.matches()) {
current.setNickname(matcher.group(1));
}
}
else {
if(null == current) {
log.warn("Failed to detect start of bookmark");
continue;
}
final Scanner scanner = new Scanner(line);
scanner.useDelimiter("=");
if(!scanner.hasNext()) {
log.warn("Missing key in line:" + line);
continue;
}
final String name = scanner.next().toLowerCase(Locale.ROOT);
if(!scanner.hasNext()) {
log.warn("Missing value in line:" + line);
continue;
}
final String value = scanner.next();
switch(name) {
case "host":
current.setHostname(value);
break;
case "directory":
current.setDefaultPath(value);
break;
case "username":
current.getCredentials().setUsername(value);
break;
default:
log.warn(String.format("Ignore property %s", name));
break;
}
}
}
if(current != null) {
this.add(current);
}
}
catch(IOException e) {
throw new AccessDeniedException(e.getMessage(), e);
}
}
public ExcFile(File f) throws IOException {
srgMethodName2ExcData = new HashMap<String, ExcData>();
srgParamName2ExcData = new HashMap<String, ExcData>();
// example lines:
// net/minecraft/util/ChunkCoordinates=CL_00001555
// net/minecraft/world/chunk/storage/AnvilChunkLoader.func_75816_a(Lnet/minecraft/world/World;Lnet/minecraft/world/chunk/Chunk;)V=net/minecraft/world/MinecraftException,java/io/IOException|p_75816_1_,p_75816_2_
// net/minecraft/world/biome/BiomeGenMutated.func_150571_c(III)I=|p_150571_1_,p_150571_2_,p_150571_3_
// net/minecraft/world/chunk/storage/AnvilChunkLoader.func_75818_b()V=|
// net/minecraft/server/MinecraftServer.func_145747_a(Lnet/minecraft/util/IChatComponent;)V=|p_145747_1_
Scanner in = new Scanner(new FileReader(f));
try {
while (in.hasNextLine()) {
if (in.hasNext("#")) {
in.nextLine();
continue;
}
in.useDelimiter("\\.");
String srgOwner = in.next();
in.useDelimiter("\\(");
if (!in.hasNext()) {
if (in.hasNextLine()) {
in.nextLine();
} else {
break;
}
}
String srgName = in.next().substring(1);
in.useDelimiter("=");
String descriptor = in.next();
in.useDelimiter("\\|");
String excs = in.next().substring(1);
String params = in.nextLine().substring(1);
ExcData toAdd =
new ExcData(
srgOwner,
srgName,
descriptor,
(excs.length() > 0 ? excs.split(",") : new String[0]),
(params.length() > 0 ? params.split(",") : new String[0]));
ExcData existing = srgMethodName2ExcData.get(srgName);
if ((existing == null)
|| (existing.getParameters().length < toAdd.getParameters().length)) {
srgMethodName2ExcData.put(srgName, toAdd);
for (String parameter : toAdd.getParameters()) {
srgParamName2ExcData.put(parameter, toAdd);
}
}
}
} finally {
in.close();
}
}
private void initSoapContextAndHttpHeaders() throws Exception
{
Field[] declaredFields = HttpHeaders.class.getDeclaredFields();
for (Field field : declaredFields) {
if (java.lang.reflect.Modifier.isStatic(field.getModifiers())
&& field.getType().equals(String.class)) {
httpHeaders.put(field.get(null).toString().toLowerCase(), field.get(null).toString());
}
}
File file = null;
if(gatfExecutorConfig.getWsdlLocFile()!=null && !gatfExecutorConfig.getWsdlLocFile().trim().isEmpty())
file = getResourceFile(gatfExecutorConfig.getWsdlLocFile());
if(file!=null)
{
Scanner s = new Scanner(file);
s.useDelimiter("\n");
List<String> list = new ArrayList<String>();
while (s.hasNext()) {
list.add(s.next().replace("\r", ""));
}
s.close();
for (String wsdlLoc : list) {
if(!wsdlLoc.trim().isEmpty())
{
String[] wsdlLocParts = wsdlLoc.split(",");
logger.info("Started Parsing WSDL location - " + wsdlLocParts[1]);
Wsdl wsdl = Wsdl.parse(wsdlLocParts[1]);
for (QName bindingName : wsdl.getBindings()) {
SoapBuilder builder = wsdl.getBuilder(bindingName);
for (SoapOperation operation : builder.getOperations()) {
String request = builder.buildInputMessage(operation);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document soapMessage = db.parse(new ByteArrayInputStream(request.getBytes()));
if(gatfExecutorConfig.isDistributedLoadTests()) {
soapStrMessages.put(wsdlLocParts[0]+operation.getOperationName(), request);
}
soapMessages.put(wsdlLocParts[0]+operation.getOperationName(), soapMessage);
if(operation.getSoapAction()!=null) {
soapActions.put(wsdlLocParts[0]+operation.getOperationName(), operation.getSoapAction());
}
logger.info("Adding message for SOAP operation - " + operation.getOperationName());
}
soapEndpoints.put(wsdlLocParts[0], builder.getServiceUrls().get(0));
logger.info("Adding SOAP Service endpoint - " + builder.getServiceUrls().get(0));
}
logger.info("Done Parsing WSDL location - " + wsdlLocParts[1]);
}
}
}
}