Java Code Examples for java.util.Scanner#useDelimiter()

The following examples show how to use java.util.Scanner#useDelimiter() . 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: DataHandler.java    From OrigamiSMTP with MIT License 6 votes vote down vote up
/** 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;
	}
	
	
}
 
Example 2
Source File: NetworkUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 3
Source File: NetworkUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 4
Source File: Antlr4ParserTest.java    From openCypher with Apache License 2.0 6 votes vote down vote up
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;
    }
 
Example 5
Source File: ReadingCSVFiles.java    From Java-Data-Analysis with MIT License 6 votes vote down vote up
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);
    }
}
 
Example 6
Source File: NetFile.java    From IP-Monitor with GNU General Public License v2.0 6 votes vote down vote up
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);
		}
	}
}
 
Example 7
Source File: DiffCompiler.java    From Universal-FE-Randomizer with MIT License 6 votes vote down vote up
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();
}
 
Example 8
Source File: DataParserDWI.java    From Beats with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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();
}
 
Example 9
Source File: YoutubeUtils.java    From YoutubeDown with MIT License 6 votes vote down vote up
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);
    }
}
 
Example 10
Source File: NetworkUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 11
Source File: NetworkUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 12
Source File: UriUtils.java    From canal-1.1.3 with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 13
Source File: URIQueryDecoder.java    From PiracyChecker with Apache License 2.0 6 votes vote down vote up
/**
 * 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.");
    }
}
 
Example 14
Source File: NetworkUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 15
Source File: NetworkUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 16
Source File: Trivia.java    From VileBot with MIT License 5 votes vote down vote up
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;
}
 
Example 17
Source File: ExcFile.java    From ForgeHax with MIT License 4 votes vote down vote up
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();
  }
}
 
Example 18
Source File: TotalCommanderBookmarkCollection.java    From cyberduck with GNU General Public License v3.0 4 votes vote down vote up
@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);
    }
}
 
Example 19
Source File: OAuthAuthorizeHelper.java    From YiBo with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 20
Source File: AcceptanceTestContext.java    From gatf with Apache License 2.0 4 votes vote down vote up
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]);
			}
		}
	}
}