Java Code Examples for java.util.StringTokenizer

The following are top voted examples for showing how to use java.util.StringTokenizer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jlibs   File: StringUtil.java View source code Vote up 10 votes
/**
 * Splits given string into tokens with delimiters specified.
 * It uses StringTokenizer for tokenizing.
 *
 * @param str       string to be tokenized
 * @param delim     delimiters used for tokenizing
 * @param trim      trim the tokens
 *
 * @return non-null token array
 */
public static String[] getTokens(String str, String delim, boolean trim){
    StringTokenizer stok = new StringTokenizer(str, delim);
    String tokens[] = new String[stok.countTokens()];
    for(int i=0; i<tokens.length; i++){
        tokens[i] = stok.nextToken();
        if(trim)
            tokens[i] = tokens[i].trim();
    }
    return tokens;
}
 
Example 2
Project: jentrata-msh   File: Disposition.java View source code Vote up 6 votes
private void parseDisposition(String disposition) throws AS2MessageException {
    if (disposition != null) {
        try {
            StringTokenizer tokens = new StringTokenizer(disposition, "/;:", false);

            setActionMode(tokens.nextToken().toLowerCase());
            setSendingMode(tokens.nextToken().toLowerCase());
            setType(tokens.nextToken().trim().toLowerCase());

            if (tokens.hasMoreTokens()) {
                setModifier(tokens.nextToken().toLowerCase());

                if (tokens.hasMoreTokens()) {
                    setDescription(tokens.nextToken().trim()
                            .toLowerCase());
                }
            }
        } catch (Exception nsee) {
            throw new AS2MessageException("Invalid disposition: " + disposition);
        }
    }
}
 
Example 3
Project: aws-toolkit-eclipse   File: TemplateContentAssistProcessor.java View source code Vote up 6 votes
/**
 * Identifies the node in the document for the given path and returns it.
 *
 * @param document
 *            The document associated with the editor.
 * @param path
 *            The path from the Root to the node.
 */
private TemplateNode lookupNodeByPath(TemplateDocument document, String path) {
    TemplateNode node = ((TemplateDocument) document).getModel();

    if (path.startsWith("ROOT"))
        path = path.substring("ROOT".length());
    else
        throw new RuntimeException("Unexpected path encountered");

    StringTokenizer tokenizer = new StringTokenizer(path, "/");

    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();

        if (node != null && node.isObject()) {
            TemplateObjectNode object = (TemplateObjectNode) node;
            node = object.get(token);
        } else {
            throw new RuntimeException("Unexpected node structure");
        }
    }
    return node;
}
 
Example 4
Project: iswc2012metadata   File: ToolString.java View source code Vote up 6 votes
public static Set<String> explode(String delimiter, String szOption) {
	HashSet<String> ret = new HashSet<String>();
	if (ToolSafe.isEmpty(delimiter)|| ToolSafe.isEmpty(szOption))
		return ret;
	
	StringTokenizer st = new StringTokenizer(szOption, delimiter);
	while (st.hasMoreTokens()){
		ret.add(st.nextToken().trim());
	}
	return ret;
}
 
Example 5
Project: dlna   File: HttpServer.java View source code Vote up 6 votes
/**
 * Decodes parameters in percent-encoded URI-format
 * ( e.g. "name=Jack%20Daniels&pass=Single%20Malt" ) and
 * adds them to given Properties. NOTE: this doesn't support multiple
 * identical keys due to the simplicity of Properties -- if you need multiples,
 * you might want to replace the Properties with a Hashtable of Vectors or such.
 */
private void decodeParms( String parms, Properties p )
	throws InterruptedException
{
	if ( parms == null )
		return;

	StringTokenizer st = new StringTokenizer( parms, "&" );
	while ( st.hasMoreTokens())
	{
		String e = st.nextToken();
		int sep = e.indexOf( '=' );
		if ( sep >= 0 )
			p.put( decodePercent( e.substring( 0, sep )).trim(),
				   decodePercent( e.substring( sep+1 )));
	}
}
 
Example 6
Project: netlib   File: DigestAuthentication.java View source code Vote up 6 votes
synchronized void setQop (String qop) {
    if (qop != null) {
        StringTokenizer st = new StringTokenizer (qop, " ");
        while (st.hasMoreTokens()) {
            if (st.nextToken().equalsIgnoreCase ("auth")) {
                serverQop = true;
                return;
            }
        }
    }
    serverQop = false;
}
 
Example 7
Project: JAME   File: SpeedElementXMLImporter.java View source code Vote up 6 votes
/**
 * @see net.sf.jame.core.config.ValueConfigElementXMLImporter#parseValue(java.lang.String)
 */
@Override
protected Speed parseValue(final String value) {
	final StringTokenizer tknz = new StringTokenizer(value, ";");
	if (tknz.hasMoreTokens()) {
		final DoubleVector4D position = DoubleVector4D.valueOf(tknz.nextToken());
		if (tknz.hasMoreTokens()) {
			final DoubleVector4D rotation = DoubleVector4D.valueOf(tknz.nextToken());
			return new Speed(position, rotation);
		}
	}
	throw new RuntimeException("Invalid format: " + value);
}
 
Example 8
Project: UnicentaPOS_AD   File: PaymentGatewayPGNET.java View source code Vote up 6 votes
@Override
    public void execute(PaymentInfoMagcard payinfo) {

// JG 16 May 12 use StringBuilder in place of StringBuilder
        StringBuilder sb = new StringBuilder();
        try {
            
            sb.append("pg_merchant_id=");
            sb.append(m_sCommerceID);

            sb.append("&pg_password=");
            sb.append(m_sCommercePassword);
            
            sb.append("&pg_total_amount=");
            NumberFormat formatter = new DecimalFormat("0000.00");
            String amount = formatter.format(Math.abs(payinfo.getTotal()));
            sb.append(URLEncoder.encode(amount.replace(',', '.'), "UTF-8"));
            
                if (payinfo.getTrack1(true) != null){
                sb.append("&pg_cc_swipe_data=");
                sb.append(URLEncoder.encode(payinfo.getTrack1(true), "UTF-8"));
               }
                else {
                sb.append("&ecom_payment_card_type=");
                sb.append(getCardType(payinfo.getCardNumber()));

                sb.append("&ecom_payment_card_number=");
                sb.append(URLEncoder.encode(payinfo.getCardNumber(), "UTF-8"));

                sb.append("&ecom_payment_card_expdate_month=");
                String tmp = payinfo.getExpirationDate();
                sb.append(tmp.substring(0, 2));

                sb.append("&ecom_payment_card_expdate_year=");
                sb.append(tmp.substring(2, tmp.length()));

                String[] cc_name = payinfo.getHolderName().split(" ");
                sb.append("&ecom_billto_postal_name_first=");
                if (cc_name.length > 0) {
                sb.append(URLEncoder.encode(cc_name[0], "UTF-8"));
                }
                sb.append("&ecom_billto_postal_name_last=");
                if (cc_name.length > 1) {
                sb.append(URLEncoder.encode(cc_name[1], "UTF-8"));
                }

                sb.append("&ecom_payment_card_name=");
                sb.append(payinfo.getHolderName());
             }
 
            //PAYMENT
            if (payinfo.getTotal() >= 0.0) {
                sb.append("&pg_transaction_type=");
                sb.append(SALE);
                //sb.append("&x_card_code=340");
            }
            //REFUND
            else {
                sb.append("&pg_transaction_type=");
                sb.append(REFUND);
            }
            
            sb.append("&endofdata");

            // open secure connection
            URL url = new URL(ENDPOINTADDRESS);

            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            // not necessarily required but fixes a bug with some servers
// JG 16 May 12 use try-with-resources
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
                out.write(sb.toString().getBytes());
                out.flush();
            }

            // process and read the gateway response
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            
            String returned="", aux;
            
            while ((aux = in.readLine()) != null) {
                    returned += "&" + aux;
            }

            payinfo.setReturnMessage(returned);
            in.close();	                     // fin

            Map props = new HashMap();
            StringTokenizer tk = new java.util.StringTokenizer(returned, "&");
            while(tk.hasMoreTokens()) {
                String sToken = tk.nextToken();
                int i = sToken.indexOf('=');
                if (i >= 0) {
                    props.put(URLDecoder.decode(sToken.substring(0, i), "UTF-8"), URLDecoder.decode(sToken.substring(i + 1), "UTF-8"));
                } else {
                    props.put(URLDecoder.decode(sToken, "UTF-8"), null);
                }                   
            }
            
            if (APPROVED.equals(props.get("pg_response_type"))) {
                payinfo.paymentOK((String)props.get("pg_authorization_code"), (String)props.get("pg_trace_number"), returned);
            } else {
                
                String sCode = (String)props.get("pg_response_description");
                sCode = sCode.replace("F01", "\nMANDITORY FIELD MISSING");
                sCode = sCode.replace("F03", "\nINVALID FIELD NAME");
                sCode = sCode.replace("F04", "\nINVALID FIELD VALUE");
                sCode = sCode.replace("F05", "\nDUPLICATE FIELD");
                sCode = sCode.replace("F07", "\nCONFLICTING FIELD");
                                 
                payinfo.paymentError(AppLocal.getIntString("message.paymenterror"), sCode);
            }
            
// JG 16 May 12 use multicatch
        } catch (UnsupportedEncodingException | MalformedURLException eUE) {
            payinfo.paymentError(AppLocal.getIntString("message.paymentexceptionservice"), eUE.getMessage());
        } catch(IOException e){
            payinfo.paymentError(AppLocal.getIntString("message.paymenterror"), e.getMessage());
        }
        
    }
 
Example 9
Project: speechalyzer   File: AudioFileManager.java View source code Vote up 6 votes
/**
 * Add/Append labels to audiofiles.
 * 
 * @param fileList
 */
public void addLabels(String fileList) {
	int index = 0;
	try {
		Vector<String> tmp = FileUtil.getFileLines(fileList);
		for (Iterator<String> iterator = tmp.iterator(); iterator.hasNext();) {
			String line = iterator.next();
			if (!FileUtil.isCommentOrEmpty(line)) {
				StringTokenizer st = new StringTokenizer(line);
				String path = st.nextToken();
				String labString = "";
				while (st.hasMoreTokens()) {
					labString += st.nextToken() + " ";
				}
				labString = labString.trim();
				if (labString.length() > 0) {
					RecFile recFile = findAudioFile(path);
					if (recFile != null) {
						index++;
						recFile.addLabel(labString);
					} else {
						_logger.error("recfile not found: " + path);
					}
				}
				if (index % 10 == 0) {
					System.err.print(".");
				}
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	_logger.info("AFM: added " + index + " labels to audio files");
}
 
Example 10
Project: Grinnell-DB-Android   File: RequestTask.java View source code Vote up 6 votes
private String onCampusParse(StringTokenizer strTok) {
	//Skip stuff we don't need
	String stringBeingParsed;
	String curTok, picurl, firstName, lastName, username, dept, phonenum, campusaddress, boxno, stufacstatus, sgapos;

	for (int i = 0; i < 58; i++) {
		strTok.nextToken();
	}
	int numOfResults = Integer.parseInt(numberParser(strTok.nextToken()));


	for (int i = 0; i < 43; i++) {
		strTok.nextToken();
	}

	for (int i = 0; i < numOfResults; i++) {
		stringBeingParsed = strTok.nextToken();

		String[] nameEmailRole = nameEmailRoleParser(stringBeingParsed);
		String fullName = nameEmailRole[0].trim();
		firstName = fullName.substring(fullName.indexOf(','), fullName.length());
		lastName = fullName.substring(0, fullName.indexOf(','));
		username = nameEmailRole[1];
		stufacstatus = nameEmailRole[2];


	}



	return null;
}
 
Example 11
Project: aws-toolkit-eclipse   File: TemplateContentAssistProcessor.java View source code Vote up 6 votes
/**
 * Identifies the set of resources to be shown for auto completion.
 *
 * @param offset
 *            The current cursor position.
 * @param document
 *            The document associated with the editor.
 * @param path
 *            Path from the root of the JSON object to the current cursor
 *            position.
 * @param proposals
 *            List of auto completion proposals.
 */
private void provideResourceTypes(int offset, TemplateDocument document,
        String path, List<ICompletionProposal> proposals) {

    if (!(path.startsWith(resourcesPath))) {
        throw new RuntimeException("Unexpected path encountered");
    }

    String stringToReplace = DocumentUtils.readToPreviousQuote(document,
            offset);
    char nextChar = DocumentUtils.readToNextChar(document, offset);

    boolean needsQuotes = nextChar != '"';

    path = path.substring(resourcesPath.length());

    Set<String> resourceTypes = schemaRules.getResourceTypeNames();

    StringTokenizer tokenizer = new StringTokenizer(path, "/");

    String nextToken;
    if (tokenizer.countTokens() == 2) {
        // Skipping the resource name
        tokenizer.nextToken();
        // Fetching the next Token.
        nextToken = tokenizer.nextToken();

        if (nextToken.equals(RESOURCE_TYPE)) {
            addListToProposals(offset,
                    new ArrayList<String>(resourceTypes), proposals,
                    stringToReplace, needsQuotes, null);
        }
    }
}
 
Example 12
Project: dlna   File: HttpServer.java View source code Vote up 6 votes
/**
 * URL-encodes everything between "/"-characters.
 * Encodes spaces as '%20' instead of '+'.
 */
private String encodeUri( String uri )
{
	String newUri = "";
	StringTokenizer st = new StringTokenizer( uri, "/ ", true );
	while ( st.hasMoreTokens())
	{
		String tok = st.nextToken();
		if ( tok.equals( "/" ))
			newUri += "/";
		else if ( tok.equals( " " ))
			newUri += "%20";
		else
		{
			newUri += URLEncoder.encode( tok );
			// For Java 1.4 you'll want to use this instead:
			// try { newUri += URLEncoder.encode( tok, "UTF-8" ); } catch ( java.io.UnsupportedEncodingException uee ) {}
		}
	}
	return newUri;
}
 
Example 13
Project: speechalyzer   File: AudioFileManager.java View source code Vote up 6 votes
public void importTranscriptions(String file) {
	_recordingDir = null;
	_fileList = file;
	_audioFiles = new Vector<RecFile>();
	if (_fileList.length() > 0) {
		_logger.info("loading audio files with transcriptions from "
				+ _fileList + "...");
		try {
			int index = 0;
			Vector<String> tmp = FileUtil.getFileLines(_fileList,
					_config.getString("charEnc"));
			for (Iterator<String> iterator = tmp.iterator(); iterator
					.hasNext();) {
				String line = iterator.next();
				_logger.debug("loading line: " + line);
				if (!FileUtil.isCommentOrEmpty(line)) {
					StringTokenizer st = new StringTokenizer(line);
					String path = st.nextToken();
					if (path.endsWith("." + _audioExtension)) {
						if (!isAudioFileContained(path)) {
							_logger.warn("AFM: file, line " + line
									+ ", doesnt exist, creating it.");
							String transcription = StringUtil
									.getRestOfLine(st);
							RecFile recFile = new RecFile(path, _config);
							recFile.storeTranscript(transcription);
							_logger.debug("adding file " + path
									+ " with transcript: " + transcription);
							_audioFiles.add(recFile);
						}
					}
					// indicate progress while loading
					if (index % 10 == 0) {
						System.err.print(".");
					}
					index++;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			_logger.error("invalid filelist: " + e.getMessage());
			System.exit(1);
		}
	}

}
 
Example 14
Project: speechalyzer   File: AudioFileManager.java View source code Vote up 6 votes
public void addSympaResults(String fileList) {
	int index = 0;
	try {
		Vector<String> tmp = FileUtil.getFileLines(fileList);
		for (Iterator<String> iterator = tmp.iterator(); iterator.hasNext();) {
			String line = iterator.next();
			StringTokenizer st = new StringTokenizer(line);
			String path = st.nextToken();
			st.nextToken();
			double na = Double.parseDouble(st.nextToken());
			double ha = Double.parseDouble(st.nextToken());
			RecFile recFile = findAudioFile(path);
			ClassificationResult cr = new ClassificationResult();
			cr.addResult("N", na);
			cr.addResult("A", ha);
			if (recFile != null) {
				index++;
				recFile.storePred(cr);
			} else {
				_logger.error("recfile not found: " + path);
			}
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	_logger.info("AFM: added sympalog Results to " + index + " audio files");
}
 
Example 15
Project: speechalyzer   File: RecFile.java View source code Vote up 6 votes
private void fillLabelArrayFromString(String labelString) {
	StringTokenizer st = new StringTokenizer(labelString, ";");
	_lab = new Emotion[st.countTokens()];
	int i = 0;
	while (st.hasMoreTokens()) {
		String label = st.nextToken();
		_lab[i++] = Emotion.parseEmotion(_config, label);
	}
}
 
Example 16
Project: speechalyzer   File: Util.java View source code Vote up 6 votes
/**
 * return the tokens of a string.
 * 
 * @param s
 * @return
 */
public static String[] stringToArray(String s) {
	String ret[] = null;
	StringTokenizer st = new StringTokenizer(s);
	ret = new String[st.countTokens()];
	int i = 0;
	while (st.hasMoreTokens()) {
		ret[i++] = st.nextToken();
	}
	return ret;
}
 
Example 17
Project: cassandra-dev   File: AbstractColumnFactory.java View source code Vote up 6 votes
static String[] getSuperColumnAndColumn(String cName)
{
    StringTokenizer st = new StringTokenizer(cName, ":");
    String[] values = new String[st.countTokens()];
    int i = 0;
    while ( st.hasMoreElements() )
    {
        values[i++] = (String)st.nextElement();
    }
    return values;
}
 
Example 18
Project: ftp4j   File: FTPClient.java View source code Vote up 6 votes
/**
 * If a local address for active data transfers has been supplied through
 * the [email protected] FTPKeys#ACTIVE_DT_HOST_ADDRESS}, it returns it as a 4 elements
 * integer array; otherwise it returns null.
 * 
 * @return The forced local address, or null.
 */
private int[] pickForcedLocalAddress() {
	int[] ret = null;
	String aux = System.getProperty(FTPKeys.ACTIVE_DT_HOST_ADDRESS);
	if (aux != null) {
		boolean valid = false;
		StringTokenizer st = new StringTokenizer(aux, ".");
		if (st.countTokens() == 4) {
			valid = true;
			int[] arr = new int[4];
			for (int i = 0; i < 4; i++) {
				String tk = st.nextToken();
				try {
					arr[i] = Integer.parseInt(tk);
				} catch (NumberFormatException e) {
					arr[i] = -1;
				}
				if (arr[i] < 0 || arr[i] > 255) {
					valid = false;
					break;
				}
			}
			if (valid) {
				ret = arr;
			}
		}
		if (!valid) {
			// warning to the developer
			System.err.println("WARNING: invalid value \"" + aux
					+ "\" for the " + FTPKeys.ACTIVE_DT_HOST_ADDRESS
					+ " system property. The value should "
					+ "be in the x.x.x.x form.");
		}
	}
	return ret;
}
 
Example 19
Project: ftp4j   File: NVTASCIIWriter.java View source code Vote up 6 votes
/**
 * Writes a line in the stream.
 * 
 * @param str
 *            The line.
 * @throws IOException
 *             If an I/O error occurs.
 */
public void writeLine(String str) throws IOException {
	StringBuffer buffer = new StringBuffer();
	boolean atLeastOne = false;
	StringTokenizer st = new StringTokenizer(str, LINE_SEPARATOR);
	int count = st.countTokens();
	for (int i = 0; i < count; i++) {
		String line = st.nextToken();
		if (line.length() > 0) {
			if (atLeastOne) {
				buffer.append('\r');
				buffer.append((char) 0);
			}
			buffer.append(line);
			atLeastOne = true;
		}
	}
	if (buffer.length() > 0) {
		String statement = buffer.toString();
		// Sends the statement to the server.
		writer.write(statement);
		writer.write(LINE_SEPARATOR);
		writer.flush();
	}
}
 
Example 20
Project: aipo   File: StringUtils.java View source code Vote up 6 votes
/**
  *  Converts a delimited string into an array of string tokens.
  *                    
  * @param String[] The 'separator' separated string.
  * @param String The string separator.
  * @return String A string array of the original tokens.
  */
public static final String[] stringToArray(String str, String separators)
{
    StringTokenizer tokenizer;
    String[] array = null;
    int count = 0;

    if (str == null)
        return array;

    if (separators == null)
        separators = ",";

    tokenizer = new StringTokenizer(str, separators);
    if ((count = tokenizer.countTokens()) <= 0) {
        return array;
    }
    
    array = new String[count];
    
    int ix = 0;
    while (tokenizer.hasMoreTokens()) 
    {
        array[ix] = tokenizer.nextToken();
        ix++;
    }

    return array;
}
 
Example 21
Project: aipo   File: ALLocalMailMessage.java View source code Vote up 6 votes
/**
 * TO?CC?BCC ?????????????????? strict = false
 * 
 * @param recipienttype
 * @param strict
 * @return
 * @throws MessagingException
 */
public Address[] getRecipients(
    javax.mail.Message.RecipientType recipienttype, boolean strict)
    throws MessagingException {
  if (strict) {
    return getRecipients(recipienttype);
  } else {
    Address[] addresses;
    try {
      addresses = super.getRecipients(recipienttype);
    } catch (AddressException e) {
      String recipients =
        MailUtility
          .decodeText(this.getHeader(recipienttype.toString(), null));
      if (recipients == null) {
        return super.getRecipients(recipienttype);
      }
      int index = 0;
      String token = null;
      StringTokenizer st = new StringTokenizer(recipients, ",;");
      addresses = new InternetAddress[st.countTokens()];
      while (st.hasMoreTokens()) {
        token = st.nextToken();
        try {
          addresses[index] = new InternetAddress(token, false);
        } catch (AddressException ae) {
          addresses[index] = new InternetAddress();
          ((InternetAddress) addresses[index]).setAddress(token);
        }
        index++;
      }
    }
    return addresses;
  }
}
 
Example 22
Project: speechalyzer   File: ClassificationResult.java View source code Vote up 6 votes
public ClassificationResult(String resultsDescr) {
	if (resultsDescr.compareTo(NULL) == 0) {
		isNull = true;
	} else {
		try {
			StringTokenizer st = new StringTokenizer(resultsDescr);
			while (st.hasMoreElements()) {
				String className = (String) st.nextElement();
				double prob = Double.parseDouble((String) st.nextElement());
				addResult(className, prob);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
 
Example 23
Project: virgo.kernel   File: ParsingUtils.java View source code Vote up 6 votes
private static String[] getArguments(String buffer) {
    
    List<String> arguments = new ArrayList<String>();
    
    StringTokenizer tokenizer = new StringTokenizer(buffer, DELIMITER, true);        
    while (tokenizer.hasMoreElements()) {
        String token = tokenizer.nextToken();
        
        if (DELIMITER.equals(token)) {
            if (!tokenizer.hasMoreElements()) {
                arguments.add(EMPTY_STRING);
            }
        } else {
            arguments.add(token);
        }
    }
    
    return arguments.toArray(new String[arguments.size()]);
}
 
Example 24
Project: webstart   File: VersionString.java View source code Vote up 6 votes
/**
 * Constructs a VersionString object from string
 */
public VersionString( String vs )
{
    _versionIds = new ArrayList<VersionID>();
    if ( vs != null )
    {
        StringTokenizer st = new StringTokenizer( vs, " ", false );
        while ( st.hasMoreElements() )
        {
            // Note: The VersionID class takes care of a postfixed '+'
            _versionIds.add( new VersionID( st.nextToken() ) );
        }
    }
}
 
Example 25
Project: xapi   File: ModelMagic.java View source code Vote up 6 votes
public String mangleName(final String fqcn, final boolean minify) {
  String minified = nameMap.get(fqcn);
  if (minified == null) {
    if (minify) {
      minified = nextId();
    } else {
      final StringTokenizer tokens = new StringTokenizer(fqcn, ".");
      final StringBuilder b = new StringBuilder('M');
      while (tokens.hasMoreElements()) {
        b.append(tokens.nextToken().charAt(0)).append('_');
      }
      minified = b+fqcn.substring(fqcn.lastIndexOf('.')+1);
    }
    nameMap.put(fqcn, minified);
  }
  return minified;
}
 
Example 26
Project: Pure-File-Manager   File: StorageHelper.java View source code Vote up 6 votes
/**
 * Checks whether the path contains one of the directories
 *
 * For example, if path is /one/two, it returns true input is "one" or
 * "two". Will return false if the input is one of "one/two", "/one" or
 * "/two"
 *
 * @param path
 *            path to check for a directory
 * @param dirs
 *            directories to find
 * @return true, if the path contains one of the directories
 */
private static boolean pathContainsDir(final String path, final String[] dirs) {
    final StringTokenizer tokens = new StringTokenizer(path, File.separator);
    while (tokens.hasMoreElements()) {
        final String next = tokens.nextToken();
        for (final String dir : dirs) {
            if (next.equals(dir)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 27
Project: ilarkesto   File: DateAndTime.java View source code Vote up 6 votes
public DateAndTime(String s) {
	StringTokenizer tok = new StringTokenizer(s, " ");
	if (!tok.hasMoreElements()) throw new RuntimeException("Invalid DateAndTime format: " + s);
	date = new Date(tok.nextToken());
	if (tok.hasMoreElements()) {
		time = new Time(tok.nextToken());
	} else {
		time = new Time(0, 0);
	}
}
 
Example 28
Project: Thud   File: MUMapAction.java View source code Vote up 6 votes
public void zoomin (String sAction, Thud thud, MUMapComponent map)
{
	int		iFactor = 5;
	StringTokenizer		tk = new StringTokenizer (sAction, " ");
	
	tk.nextToken ();
	if (tk.hasMoreElements ())
	{
		String	sToken = tk.nextToken ();
		iFactor = Integer.parseInt(sToken);
	}
	
	map.setHexHeight (map.getHexHeight () + iFactor);
	map.repaint ();
}
 
Example 29
Project: goworks   File: CompletionSettings.java View source code Vote up 6 votes
private static Dimension parseDimension(String s, Dimension d) {
    int arr[] = new int[2];
    int i = 0;
    
    if (s != null) {
        StringTokenizer st = new StringTokenizer(s, ","); // NOI18N

        while (st.hasMoreElements()) {
            if (i > 1) {
                return d;
            }
            try {
                arr[i] = Integer.parseInt(st.nextToken());
            } catch (NumberFormatException nfe) {
                LOG.log(Level.WARNING, null, nfe);
                return d;
            }
            i++;
        }
    }
    
    if (i != 2) {
        return d;
    } else {
        return new Dimension(arr[0], arr[1]);
    }
}
 
Example 30
Project: fiji   File: CLI_.java View source code Vote up 6 votes
void putTokens(String from, String separator, ArrayList al) {
	StringTokenizer st = new StringTokenizer(from, separator);
	while(st.hasMoreElements()) {
		String token = st.nextToken();
		if (null != token && 0 != token.length()) {
			al.add(token);
		}
	}
}
 
Example 31
Project: modern-jogl-examples   File: Attribute.java View source code Vote up 6 votes
public Attribute(Element element) {

        index = Integer.parseInt(element.getAttribute("index"));

        type = element.getAttribute("type");

        size = Integer.parseInt(element.getAttribute("size"));

//        System.out.println("index: " + index + " type: " + type + " size: " + size);

        String textContent = element.getTextContent();

        StringTokenizer stringTokenizer = new StringTokenizer(textContent);

        int numberOfObjects = 0;
        while (stringTokenizer.hasMoreElements()) {
            numberOfObjects++;
            stringTokenizer.nextElement();
        }

        content = new float[numberOfObjects];

        stringTokenizer = new StringTokenizer(textContent);

        for (int i = 0; i < numberOfObjects; i++) {
            String s = (String) stringTokenizer.nextElement();
//            System.out.println("s[" + i + "]: " + s);
            content[i] = Float.parseFloat(s);
        }
    }
 
Example 32
Project: hivemall   File: TokenizeUDF.java View source code Vote up 6 votes
public List<Text> evaluate(Text input, boolean toLowerCase) {
    final List<Text> tokens = new ArrayList<Text>();
    final StringTokenizer tokenizer = new StringTokenizer(input.toString(), DELIM);
    while(tokenizer.hasMoreElements()) {
        String word = tokenizer.nextToken();
        if(toLowerCase) {
            word = word.toLowerCase();
        }
        tokens.add(new Text(word));
    }
    return tokens;
}
 
Example 33
Project: OpenClinica   File: StudyBean.java View source code Vote up 6 votes
/**
 * @return Returns the interventions, using the internationalized version of
 *         the intervention type.
 */
public String getInterventions() {
    StringTokenizer st = new StringTokenizer(interventions, ",");
    StringBuffer sb = new StringBuffer();
    String intervention, name;
    while (st.hasMoreElements()) {
        StringTokenizer inter = new StringTokenizer(st.nextToken().toString(), "/");
        intervention = inter.nextToken();
        sb.append(ResourceBundleProvider.getResAdmin(intervention));
        sb.append("/");
        name = inter.nextToken();
        sb.append(name);
        sb.append(",");
    }
    if (sb.length() != 0)
        sb.deleteCharAt(sb.lastIndexOf(","));
    return sb.toString();
}
 
Example 34
Project: JerseyTest   File: JsonXmlStreamReaderWriterTest.java View source code Vote up 6 votes
private void addStringsToCollection(String strings, Collection<String> collection) {
    if ((null == strings) || (null == collection)) {
        return;
    }
    StringTokenizer stringTokenizer = new StringTokenizer(strings);
    while (stringTokenizer.hasMoreElements()) {
        collection.add(stringTokenizer.nextToken());
    }
}
 
Example 35
Project: JFugue-for-Android   File: Parser.java View source code Vote up 6 votes
/**
    * SAX2: Receive notification of a processing instruction.
    *       These require special handling for stylesheet PIs.
    */
   public void processingInstruction(String name, String value) {
// We only handle the <?xml-stylesheet ...?> PI
if ((_target == null) && (name.equals("xml-stylesheet"))) {

    String href = null;    // URI of stylesheet found
    String media = null;   // Media of stylesheet found
    String title = null;   // Title of stylesheet found
    String charset = null; // Charset of stylesheet found

    // Get the attributes from the processing instruction
    StringTokenizer tokens = new StringTokenizer(value);
    while (tokens.hasMoreElements()) {
	String token = (String)tokens.nextElement();
	if (token.startsWith("href"))
	    href = getTokenValue(token);
	else if (token.startsWith("media"))
	    media = getTokenValue(token);
	else if (token.startsWith("title"))
	    title = getTokenValue(token);
	else if (token.startsWith("charset"))
	    charset = getTokenValue(token);
    }

    // Set the target to this PI's href if the parameters are
    // null or match the corresponding attributes of this PI.
    if ( ((_PImedia == null) || (_PImedia.equals(media))) &&
	 ((_PItitle == null) || (_PImedia.equals(title))) &&
	 ((_PIcharset == null) || (_PImedia.equals(charset))) ) {
	_target = href;
    }
}
   }
 
Example 36
Project: org.openscience.cdk   File: CDKConvention.java View source code Vote up 6 votes
public void characterData(CMLStack xpath, char ch[], int start, int length) {
        String s = new String(ch, start, length).trim();
        if (isBond) {
            logger.debug("CharData (bond): " + s);
            StringTokenizer st = new StringTokenizer(s);
            while (st.hasMoreElements()) {
                String border = (String)st.nextElement();
                logger.debug("new bond order: " + border);
                // assume cdk bond object has already started
//                cdo.setObjectProperty("Bond", "order", border);
                currentBond.setOrder(
                	BondManipulator.createBondOrder(Double.parseDouble(border))
                );
            }
        } else {
            super.characterData(xpath, ch, start, length);
        }
    }
 
Example 37
Project: BetterBatteryStats   File: StatsProvider.java View source code Vote up 6 votes
/**
 * translate the stat type (see arrays.xml) to the corresponding label
 * 
 * @param position
 *            the spinner position
 * @return the stat type
 */
public String statTypeToUrl(int statType)
{
	String strRet = statTypeToLabel(statType);

	// remove spaces
	StringTokenizer st = new StringTokenizer(strRet, " ", false);

	String strCleaned = "";
	while (st.hasMoreElements())
	{
		strCleaned += st.nextElement();
	}
	return strCleaned;
}
 
Example 38
Project: bpel   File: JavaScriptSource.java View source code Vote up 6 votes
static private void addReserved (String s) 
{
    StringTokenizer tokenizer = new StringTokenizer(s,",;");
    while (tokenizer.hasMoreElements()) {
        String next = (String) tokenizer.nextElement();    
        String nextTrim = next.trim();
        if (nextTrim.length() < 1) {
            continue;
        }
        R.put(nextTrim, Boolean.TRUE);
    }
}
 
Example 39
Project: log4jdbc-remix   File: Slf4jSpyLogDelegator.java View source code Vote up 6 votes
/**
 * Break an SQL statement up into multiple lines in an attempt to make it
 * more readable
 *
 * @param sql SQL to break up.
 * @return SQL broken up into multiple lines
 */
private String processSql(String sql)
{
  if (sql==null)
  {
    return null;
  }

  sql = sql.trim();

  StringBuffer output = new StringBuffer();

  if (DriverSpy.DumpSqlMaxLineLength <= 0)
  {
    output.append(sql);
  }
  else
  {
    // insert line breaks into sql to make it more readable
    StringTokenizer st = new StringTokenizer(sql);
    String token;
    int linelength = 0;

    while (st.hasMoreElements())
    {
      token = (String) st.nextElement();

      output.append(token);
      linelength += token.length();
      output.append(" ");
      linelength++;
      if (linelength > DriverSpy.DumpSqlMaxLineLength)
      {
        output.append("\n");
        linelength = 0;
      }
    }
  }

  if (DriverSpy.DumpSqlAddSemicolon)
  {
    output.append(";");
  }

  return output.toString();
}
 
Example 40
Project: cloudtm-data-platform   File: BaseWordCountMapReduceTest.java View source code Vote up 6 votes
@Override
public void map(String key, String value, Collector<String, Integer> collector) {
   StringTokenizer tokens = new StringTokenizer(value);
   while (tokens.hasMoreElements()) {
      String s = (String) tokens.nextElement();
      collector.emit(s, 1);
   }         
}
 
Example 41
Project: codjo-standalone-common   File: ConfigurationFileTest.java View source code Vote up 6 votes
private String slashDubbler(String str) {
    String slash = "\\";
    StringTokenizer tokenizer = new StringTokenizer(str, slash, true);
    String slashDubbled = "";
    String element;
    while (tokenizer.hasMoreElements()) {
        element = (String)tokenizer.nextElement();
        if (slash.equals(element)) {
            slashDubbled += slash;
        }
        slashDubbled += element;
    }
    return slashDubbled;
}
 
Example 42
Project: jade_agents   File: ACLPropertyList.java View source code Vote up 6 votes
/**
 *  Description of the Method
 *
 * @param  entry  Description of Parameter
 * @return        Description of the Returned Value
 */
String filterEntry(String entry) {
  String result = "<?>";
  try {
    StringTokenizer stok = new StringTokenizer(entry, "=");
    result = (String)stok.nextElement();
  }
  catch (Exception ex) {
    ex.printStackTrace();
  }
  return result;
}
 
Example 43
Project: teiid-designer   File: WsdlLoader.java View source code Vote up 6 votes
protected void doProcess( final SoapFault fault,
                          final Element element ) {
    final String namespace = element.getAttributeValue(Soap.FAULT_NAMESPACE);
    fault.setNamespace(namespace);

    final String styles = element.getAttributeValue(Soap.FAULT_ENCODINGSTYLE);
    if (styles != null && styles.trim().length() != 0) {
        final List styleList = fault.getEncodingStyles();
        final StringTokenizer tokenizer2 = new StringTokenizer(styles, ANYURI_DELIM);
        while (tokenizer2.hasMoreElements()) {
            final String token = (String)tokenizer2.nextElement();
            if (token != null && token.length() != 0) {
                styleList.add(token);
            }
        }
    }

    final String use = element.getAttributeValue(Soap.FAULT_USE);
    if (Soap.ENUM_USE_ENCODED.equals(use)) {
        fault.setUse(SoapUseType.ENCODED_LITERAL);
    } else if (Soap.ENUM_USE_LITERAL.equals(use)) {
        fault.setUse(SoapUseType.LITERAL_LITERAL);
    }
}
 
Example 44
Project: Grinnell-DB-Android   File: RequestTask.java View source code Vote up 5 votes
private boolean parseResponse() {
		if (responseString == null) {
			errorCode = NO_RESPONSE_STRING;
			return false;
		}
		// Set up the tokenizer, seperating by token '\n'. You should find out
		// what a tokenizer is.
		StringTokenizer strTok = new StringTokenizer(responseString, "\n");
		String curTok, picurl, firstName, lastName, username, dept, phonenum, campusaddress, boxno, stufacstatus, sgapos;
		// boolean indicating if there exists a next page.
		boolean anotherPage = false;
		boolean onCampus = false;

		if (!responseString.contains("off campus viewers")) {
			onCampus = true;
			strTok.nextToken();
			curTok = strTok.nextToken();
		}

        curTok = strTok.nextToken();
        while (!curTok.contains("<p>")) {
            curTok = strTok.nextToken();
        }

        if (curTok.contains("pages")) {
            errorCode = TOO_MANY_ENTRIES;
            return false;
        } else if (curTok.contains("<strong>no</strong>")) {
            errorCode = NO_ENTRIES;
            return false;
        }

		// skip useless information
		for (int i = 0; i < 9; i++) {
            strTok.nextToken();
        }
		curTok = strTok.nextToken();


		// If line 88 contains these strings, there were 0 results or too many
		// results

//			// skip useless information
//			for (int i = 0; i < 8; i++)
//				curTok = strTok.nextToken();
//            if (onCampus) {
//                curTok = strTok.nextToken();
//                curTok = strTok.nextToken();
//            }


            // If a next page button exsts, then there is a next page.
			// Grab URL of next pageand set return value of method to true.
			if (curTok.contains("Next Page")) {
				anotherPage = true;
				currentUri = "https://itwebapps.grinnell.edu"
						+ curTok.substring(53, curTok.length() - 38);
				for (int i = 0; i < 22; i++)
					strTok.nextToken();
				curTok = strTok.nextToken();
			} else {
				anotherPage = false;
				for (int i = 0; i < 20; i++) {
                    strTok.nextToken();
                }
				curTok = strTok.nextToken();
			}

			// loop, keeps adding entries to profileList until there are none.
			do {
				if (onCampus) {
					// parse entries
					// parse image URL. If no image, save " ".
					if (curTok.contains("image1"))
						picurl = curTok.substring(
								curTok.indexOf("img src=\"") + 9,
								curTok.indexOf("\" alt=\""));
					else
						picurl = "";
					curTok = strTok.nextToken();
				} else {
					picurl = "";
					curTok = strTok.nextToken();
				}
				String fullName;
				// parse full name
				if (onCampus) {
					fullName = curTok.substring(
							curTok.substring(40).indexOf('>') + 41, curTok
									.substring(40).indexOf('<') + 40);
				} else {
                    String rawName = dataParser(curTok);
                    fullName = rawName;
//					fullName = curTok.substring(35, curTok.indexOf("</TD>"));
				}
				if (fullName == null) {
					errorCode = NO_ENTRIES;
					return false;
				}
				firstName = fullName.substring(0, fullName.indexOf(','));
				lastName = fullName.substring(fullName.indexOf(',') + 2);
				curTok = strTok.nextToken();

				if (onCampus) {
					// parse student major or faculty department
					dept = curTok.substring(35, curTok.indexOf("</td>"));
					String smallerdeptString = curTok.substring(curTok
							.indexOf("tny") + 6);
					// some faculty/staff have multiple titles
					if (dept.contains("tny")) {
						dept = facStaffTitle(dept);
					}
					// dept += smallerdeptString.substring(0,
					// smallerdeptString.indexOf("<"));
					curTok = strTok.nextToken();

					// parse phone number, username, campus address, box #,
					// student/faculty status
					if (curTok.charAt(37) != '<') {
						phonenum = curTok.substring(37, 41);
						if (phonenum.contains("-")) {
						    phonenum = "";
						}
					} else {
						phonenum = "";
					}
				} else {
					dept = UNAVAILABLE;
					phonenum = UNAVAILABLE;
					curTok = strTok.nextToken();
				}
				curTok = strTok.nextToken();

				if (!curTok.contains("&nbsp")) {
					username = curTok.substring(53, curTok.indexOf('@'));
				} else {
					username = "";
				}
				strTok.nextToken();
				curTok = strTok.nextToken();

				if (onCampus) {
					campusaddress = curTok
							.substring(0, curTok.indexOf("</TD>"));
					campusaddress = campusaddress.trim();
					curTok = strTok.nextToken();
					boxno = curTok.substring(36, curTok.indexOf("</TD>"));
					if (boxno.equals("&nbsp;"))
						boxno = "Not Available";
					curTok = strTok.nextToken();
					stufacstatus = curTok.substring(37,
							curTok.indexOf(" </TD>"));
					strTok.nextToken();
				} else {
					campusaddress = UNAVAILABLE;
					boxno = UNAVAILABLE;
					stufacstatus = UNAVAILABLE;
					curTok = strTok.nextToken();
					curTok = strTok.nextToken();
					curTok = strTok.nextToken();
				}
				curTok = strTok.nextToken();

				// parse SGA status
				sgapos = "";
				if (curTok.equals("<tr>\r")) {
					// senator
					for (int i = 0; i < 3; i++)
						curTok = strTok.nextToken();
					sgapos = curTok.substring(18, curTok.indexOf("</span>"));
					while (!curTok.contains("window.open") && !curTok.contains("New Search") && !curTok.contains("style=\"text-align:center;\"")) {
					    curTok = strTok.nextToken();
					}
				}

				// Adds a new Profile to profileList containing all the newly
				// parsed information
				profileList.add(new Profile(picurl, firstName, lastName,
						username, dept, phonenum, campusaddress, boxno,
						stufacstatus, sgapos));

			} while (curTok.contains("&nbsp")); // determine if there is another
			// entry to be parsed

			return anotherPage;// returns boolean indicating if there exists a
			// next page.

			/*
			 * if(anotherPage){ for(int i=0; i<6; i++) strTok.nextToken();
			 * curTok = strTok.nextToken();
			 * 
			 * String beginningOfURL = curTok.substring(66); return
			 * "https://itwebapps.grinnell.edu" + beginningOfURL.substring(0,
			 * beginningOfURL.indexOf('"'));
			 * 
			 * }
			 */
	}
 
Example 45
Project: iswc2012metadata   File: ToolURI.java View source code Vote up 5 votes
/**
 * check if the URL is crawler-trap, throw IWSharedException when
 * encountered one.
 * 
 * http://crawler.archive.org/faq.html#traps
 * 
 * What are crawler traps? Traps are infinite page sources put up to occupy
 * ('trap') a crawler. Traps may be as innocent as a calendar that returns
 * pages years into the future or not-so-innocent
 * http://spiders.must.die.net/. Traps are created by CGIs/server-side code
 * that dynamically conjures 'nonsense' pages or else exploits combination
 * of soft and relative links to generate URI paths of infinite variety and
 * depth. Once identified, use filters to guard against falling in. Another
 * trap that works by feeding documents of infinite sizes to the crawler is
 * http://yahoo.domain.com.au/tools/spiderbait.aspx* as in
 * http://yahoo.domain.com.au/tools/spiderbait.aspx?state=vic or
 * http://yahoo.domain.com.au/tools/spiderbait.aspx?state=nsw. To filter out
 * infinite document size traps, add a maximum doc. size filter to your
 * crawl order.
 * 
 * What do I do to avoid crawling "junk"? In the past crawls were stopped
 * when we ran into "junk." An example of what we mean by "junk" is the
 * crawler stuck in a web calendar crawling the year 2020. Nowadays, if
 * "junk" is detected, we'll pause the crawl and set filters to eliminate
 * "junk" and then resume (Eliminated URIs will show in the logs. Helps when
 * doing post-crawl analysis). To help guard against the crawling of "junk"
 * setup the pathological and path-depth filters. This will also help the
 * crawler avoid traps. Recommended values for pathological filter is 3
 * repetitions of same pattern -- e.g. /images/images/images/... -- and for
 * path-depth, a value of 20.
 * 
 * @param szURL
 */
public static void validateUri_crawlerTrap(String szURL) throws Sw4jException {
	// case 1
	string2url(szURL);

	// type 2: special cases
	final String[] aryBadSegment = new String[] { "/..", "/text/text/", };
	for (int i = 0; i < aryBadSegment.length; i++) {
		if (szURL.indexOf(aryBadSegment[i]) > 0) {
			throw new Sw4jException( Sw4jMessage.STATE_ERROR, ERROR_BAD_URI_CRAWLER_TRAP, "found "+ aryBadSegment[i]+ " in URL "+ szURL);
		}
	}

	// type 2: repeated path fragments
	StringTokenizer st = new StringTokenizer(szURL, "/");
	String[] lastTokens = new String[10];
	int[] trap_depth = new int[lastTokens.length];
	for (int i = 0; i < lastTokens.length; i++) {
		lastTokens[i] = "";
		trap_depth[i] = 0;
	}
	int path_depth = 0;
	while (st.hasMoreTokens()) {
		String token = st.nextToken();

		// check pattern trap
		for (int i = 0; i < lastTokens.length; i++) {
			if (token.equals(lastTokens[i])) {
				trap_depth[i]++;
			} else {
				trap_depth[i] = 0; // reset
			}

			if (trap_depth[i] >= 2) {
				throw new Sw4jException( Sw4jMessage.STATE_ERROR, ERROR_BAD_URI_CRAWLER_TRAP,
						"repeated pattern - " + (i + 3) + " " + token
								+ " in " + szURL);
			}
		}

		// update last Tokens
		for (int i = 0; i < lastTokens.length - 1; i++) {
			lastTokens[i + 1] = lastTokens[i];
		}
		lastTokens[0] = token;

		// check absolute path depth
		path_depth++;
		if (path_depth > 20) {
				throw new Sw4jException( Sw4jMessage.STATE_ERROR, ERROR_BAD_URI_CRAWLER_TRAP,
					"path_depth too long - " + path_depth + " in " + szURL);
		}
	}
}
 
Example 46
Project: netlib   File: HttpURLConnection.java View source code Vote up 5 votes
/**
 * establish a tunnel through proxy server
 */
public synchronized void doTunneling() throws IOException {
    int retryTunnel = 0;
    String statusLine = "";
    int respCode = 0;
    AuthenticationInfo proxyAuthentication = null;
    String proxyHost = null;
    int proxyPort = -1;

    // save current requests so that they can be restored after tunnel is setup.
    MessageHeader savedRequests = requests;
    requests = new MessageHeader();

    // Read comments labeled "Failed Negotiate" for details.
    boolean inNegotiateProxy = false;

    try {
        /* Actively setting up a tunnel */
        setTunnelState(TunnelState.SETUP);

        do {
            if (!checkReuseConnection()) {
                proxiedConnect(url, proxyHost, proxyPort, false);
            }
            // send the "CONNECT" request to establish a tunnel
            // through proxy server
            sendCONNECTRequest();
            responses.reset();

            // There is no need to track progress in HTTP Tunneling,
            // so ProgressSource is null.
            http.parseHTTP(responses, null, this);

            /* Log the response to the CONNECT */
            logger.fine(responses.toString());

            statusLine = responses.getValue(0);
            StringTokenizer st = new StringTokenizer(statusLine);
            st.nextToken();
            respCode = Integer.parseInt(st.nextToken().trim());
            if (respCode == HTTP_PROXY_AUTH) {
                // Read comments labeled "Failed Negotiate" for details.
                boolean dontUseNegotiate = false;
                Iterator iter = responses.multiValueIterator("Proxy-Authenticate");
                while (iter.hasNext()) {
                    String value = ((String)iter.next()).trim();
                    if (value.equalsIgnoreCase("Negotiate") ||
                            value.equalsIgnoreCase("Kerberos")) {
                        if (!inNegotiateProxy) {
                            inNegotiateProxy = true;
                        } else {
                            dontUseNegotiate = true;
                            doingNTLMp2ndStage = false;
                            proxyAuthentication = null;
                        }
                        break;
                    }
                }

                AuthenticationHeader authhdr = new AuthenticationHeader (
                        "Proxy-Authenticate", responses,
                        http.getProxyHostUsed() /*, dontUseNegotiate*/
                );
                if (!doingNTLMp2ndStage) {
                    proxyAuthentication =
                        resetProxyAuthentication(proxyAuthentication, authhdr);
                    if (proxyAuthentication != null) {
                        proxyHost = http.getProxyHostUsed();
                        proxyPort = http.getProxyPortUsed();
                        disconnectInternal();
                        retryTunnel++;
                        continue;
                    }
                } else {
                    String raw = responses.findValue ("Proxy-Authenticate");
                    reset ();
                    if (!proxyAuthentication.setHeaders(this,
                                            authhdr.headerParser(), raw)) {
                        proxyHost = http.getProxyHostUsed();
                        proxyPort = http.getProxyPortUsed();
                        disconnectInternal();
                        throw new IOException ("Authentication failure");
                    }
                    authObj = null;
                    doingNTLMp2ndStage = false;
                    continue;
                }
            }
            // cache proxy authentication info
            if (proxyAuthentication != null) {
                // cache auth info on success, domain header not relevant.
                proxyAuthentication.addToCache();
            }

            if (respCode == HTTP_OK) {
                setTunnelState(TunnelState.TUNNELING);
                break;
            }
            // we don't know how to deal with other response code
            // so disconnect and report error
            disconnectInternal();
            setTunnelState(TunnelState.NONE);
            break;
        } while (retryTunnel < maxRedirects);

        if (retryTunnel >= maxRedirects || (respCode != HTTP_OK)) {
            throw new IOException("Unable to tunnel through proxy."+
                                  " Proxy returns \"" +
                                  statusLine + "\"");
        }
    } finally  {
        if (respCode == HTTP_PROXY_AUTH && proxyAuthentication != null) {
            proxyAuthentication.endAuthRequest();
        }
    }

    // restore original request headers
    requests = savedRequests;

    // reset responses
    responses.reset();
}
 
Example 47
Project: UnicentaPOS_AD   File: PaymentGatewayPlanetauthorize.java View source code Vote up 5 votes
@Override
public void execute(PaymentInfoMagcard payinfo) {
    StringBuilder sb = new StringBuilder();
    
    try {
        sb.append("username="); //test=demo
        sb.append(m_sCommerceID);

        sb.append("&password="); //test=password
        sb.append(m_sCommercePassword);

        sb.append("&amount=");
        NumberFormat formatter = new DecimalFormat("0000.00");
        String amount = formatter.format(Math.abs(payinfo.getTotal()));
        sb.append(URLEncoder.encode(amount.replace(',', '.'), "UTF-8"));

        //sb.append("&cvv="); //card security code
        
        if (payinfo.getTrack1(true) == null){
            sb.append("&ccnumber="); //test=4111111111111111 (visa)
            sb.append(URLEncoder.encode(payinfo.getCardNumber(), "UTF-8"));

            sb.append("&ccexp="); //expiration date  (MM/YY)
            sb.append(payinfo.getExpirationDate());

            String[] cc_name = payinfo.getHolderName().split(" ");
            sb.append("&firstname=");
            if (cc_name.length > 0) {
                sb.append(URLEncoder.encode(cc_name[0], "UTF-8"));
            }
            sb.append("&lastname=");
            if (cc_name.length > 1) {
                sb.append(URLEncoder.encode(cc_name[1], "UTF-8"));
            }
            
        } else {             
            //String track_1 = "%B4111111111111111^PADILLA VISDOMINE/LUIS ^0509120000000000000000999000000?";
            //String track_2 = ";4111111111111111=05091200333300000000?";
            //String track_3 = ";4111111111111111=7247241000000000000303009046040400005090=111111234564568798543654==1=0000000000000000?";
            sb.append("&track_1="+ URLEncoder.encode(payinfo.getTrack1(true),"UTF-8"));
            sb.append("&track_2=" + URLEncoder.encode(payinfo.getTrack2(true), "UTF-8"));
            
        }
        
        if (payinfo.getTotal() > 0.0) { //SALE
            sb.append("&type=");
            sb.append(OPERATIONVALIDATE);
            
        } else { // REFUND
            sb.append("&type=");
            sb.append(OPERATIONREFUND);
            sb.append("&transactionid="); //transaction ID
            sb.append(payinfo.getTransactionID());
            //payinfo.paymentError(AppLocal.getIntString("message.paymentrefundsnotsupported"));
        }

    // open secure connection
    URL url = new URL(ENDPOINTADDRESS);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);

    // not necessarily required but fixes a bug with some servers
    connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

    // POST the data in the string buffer
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.write(sb.toString().getBytes());
    out.flush();
    out.close();

    // process and read the gateway response
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    String returned = in.readLine();
    
    //RESPONSE
    //response=1&responsetext=SUCCESS&authcode=123456&transactionid=849066017&avsresponse=&cvvresponse=M&orderid=&type=sale&response_code=100
    payinfo.setReturnMessage(returned);
    in.close(); // fin
    
    if (returned == null) {
        payinfo.paymentError(AppLocal.getIntString("message.paymenterror"), "Response empty.");
    } else {
        Map props = new HashMap();
        StringTokenizer tk = new StringTokenizer(returned, "?&");
        while(tk.hasMoreTokens()) {
            String sToken = tk.nextToken();
            int i = sToken.indexOf('=');
            if (i >= 0) {
                props.put(URLDecoder.decode(sToken.substring(0, i), "UTF-8"), URLDecoder.decode(sToken.substring(i + 1), "UTF-8"));
            } else {
                props.put(URLDecoder.decode(sToken, "UTF-8"), null);
            }                   
        }

        if ("100".equals(props.get("response_code"))){
            //Transaction approved
            payinfo.paymentOK((String)props.get("authcode"), (String)props.get("transactionid"), returned);
        } else {
            //Transaction declined
            payinfo.paymentError(AppLocal.getIntString("message.paymenterror"), (String)props.get("responsetext"));
        }
    }
} catch (UnsupportedEncodingException eUE) {
    //no pasa nunca
    payinfo.paymentError(AppLocal.getIntString("message.paymentexceptionservice"), eUE.getMessage());
} catch (MalformedURLException eMURL) {
    // no pasa nunca    
    payinfo.paymentError(AppLocal.getIntString("message.paymentexceptionservice"), eMURL.getMessage());
} catch(IOException e){
    payinfo.paymentError(AppLocal.getIntString("message.paymenterror"), e.getMessage());
}
    
}
 
Example 48
Project: grails-ide   File: GSPTagJavaDocParser.java View source code Vote up 5 votes
private void fragmentsToAttrText(TagElement tagElt,
        Map<String, String> attrs, Map<String, String> attrsInDescription, Set<String> requiredAttrs) {
    String simpleString = tagElt.toString();
    StringTokenizer tokenizer = new StringTokenizer(simpleString, " \t\n\r\f*");
    StringBuilder sb = new StringBuilder();
    StringBuilder sb2 = new StringBuilder();
    
    if (tokenizer.hasMoreElements()) {
        // first element is @attr
        tokenizer.nextElement();
    }
    
    String attrName = null;
    if (tokenizer.hasMoreElements()) {
        attrName = tokenizer.nextToken();
        sb.append(STRONG + attrName + STRONG_END);
        sb2.append(STRONG + attrName + STRONG_END);
    }
    boolean isRequired;
    if (tokenizer.hasMoreElements()) {
        String maybeRequired = tokenizer.nextToken();
        isRequired = maybeRequired.compareToIgnoreCase(REQUIRED) == 0;
        sb2.append(" : ");
        if (isRequired) {
            sb.append(BR + ENDL + REQUIRED_STRONG);
            sb2.append(REQUIRED_STRONG);
        }
        sb.append(BR + BR + ENDL);
        if (!isRequired) {
            sb.append(maybeRequired);
            sb2.append(maybeRequired);
        }
    } else {
        isRequired = false;
    }
    while (tokenizer.hasMoreElements()) {
        if (sb.charAt(sb.length()-1) != ' ' && sb.charAt(sb.length()-1) != '\n') {
            sb.append(" ");
            sb2.append(" ");
        }
        String token = tokenizer.nextToken();
        sb.append(token);
        sb2.append(token);
    }
    sb2.append(BR + ENDL);
    if (attrName != null) {
        attrs.put(attrName, sb.toString());
        attrsInDescription.put(attrName, sb2.toString());
        if (isRequired) {
            requiredAttrs.add(attrName);
        }
    }
}
 
Example 49
Project: cryptoapplet   File: FirmaXML.java View source code Vote up 5 votes
/**
 * Este método realiza la implementación de la firma XADES-BES
 * 
 * @param doc Documento de firma
 * @param firmaID Identificador del nodo de firma
 * @param firmaCertificado Certificado que realiza la firma
 * @param elementoPrincipalFirma Elemento principal del nodo de firma
 * @return Documento de firma con formato XADES-BES
 * @throws AddXadesException En caso de error
 */
private Document addXades(Document doc,
        String firmaID,
        X509Certificate firmaCertificado,
        Element elementoPrincipalFirma) throws AddXadesException
        {

	// Creamos el QualifyingProperties
    Element elemntQualifyingProperties = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + QUALIFYING_PROPERTIES);

    // Creamos los atributos de QualifyingProperties
    elemntQualifyingProperties.setAttributeNS(null, TARGET , ALMOHADILLA + firmaID);
    
    // Creamos el elemento SignedProperties
    Element propiedadesFirmadasElemento = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + SIGNED_PROPERTIES);

    // Creamos los atributos de SignedProperties
    propiedadesFirmadasElemento.setAttributeNS(null, ID, firmaID  + GUION_SIGNED_PROPERTIES);

    // Creamos el xades:SignedSignatureProperties
    Element propiedadesFirmadasElementoFirma = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + SIGNED_SIGNATURE_PROPERTIES);
    
    // Creamos el xades:SigningTime
    
    Element tiempoFirmaElemento = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + SIGNING_TIME);

    // Formatemos la fecha de acuerdo al estándar
    // http://www.w3.org/TR/2001/REC-xmlschema-2-20010502/#dateTime

    String tiempoFecha = UtilidadFechas.formatFechaXML(new Date());
    tiempoFirmaElemento.appendChild(doc.createTextNode(tiempoFecha));
 // Creamos el xades:SigningCertificate
    Element certificadoFirmaElemento = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + SIGNING_CERTIFICATE);

    // Creamos el xades:Cert
    Element certificadoElemento = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + CERT);

    // Creamos el xades:CertDigest
    Element resumenCertificadoElemento = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + CERT_DIGEST);


    // Creamos el xades:DigestMethod
    Element metodoResumenElemento = doc.createElementNS(SCHEMA_DSIG, xmldsigNS + DOS_PUNTOS + DIGEST_METHOD);
    metodoResumenElemento.setAttributeNS(null, ALGORITHM, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1);

    // Creamos el xades:DigestValue
    String resumenCertificado =CADENA_VACIA;
    
    try {
        MessageDigest resumenCertificadoTemp = MessageDigest.getInstance(SHA_1);
        byte[] byteMessageDigest =resumenCertificadoTemp.digest(firmaCertificado.getEncoded());
        resumenCertificado = new String(Base64Coder.encode(byteMessageDigest));
    }
    catch (NoSuchAlgorithmException nsae)
    {
        throw new AddXadesException(I18n.getResource(LIBRERIAXADES_FIRMAXML_ERROR_16));
    }
    catch (CertificateEncodingException cee)
    {
    	throw new AddXadesException(I18n.getResource(LIBRERIAXADES_FIRMAXML_ERROR_17));
    }

    Element elementDigestValue = doc.createElementNS(SCHEMA_DSIG, xmldsigNS + DOS_PUNTOS + DIGEST_VALUE);
    elementDigestValue.appendChild(doc.createTextNode(resumenCertificado));

    // Creamos el xades:IssuerSerial
    Element elementoEmisorSerial = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + ISSUER_SERIAL );

    // Creamos el xades:X509IssuerName
    Element elementoX509EmisorNombre = doc.createElementNS(SCHEMA_DSIG, xmldsigNS + DOS_PUNTOS + X_509_ISSUER_NAME);
    elementoX509EmisorNombre.appendChild(doc.createTextNode(firmaCertificado.getIssuerX500Principal().getName()));

    // Creamos el xades:X509SerialNumber
    Element elementoX509NumeroSerial = doc.createElementNS(SCHEMA_DSIG, xmldsigNS + DOS_PUNTOS + X_509_SERIAL_NUMBER);
    elementoX509NumeroSerial.appendChild(doc.createTextNode(firmaCertificado.getSerialNumber().toString()));

    // Creamos el xades:SignerRole. Para ello consultamos en el fichero de propiedades
    String rolesFirmante = configuracion.getValor(SIGNER_ROLES);
    boolean roleFirmante = false;
    Element elementoRoleFirmanteElemento = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + SIGNER_ROLE);
    
    if(!Configuracion.isEmpty(rolesFirmante))
    {
    	Element elementoRolesDemandadosElementos = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + CLAIMED_ROLES);
    	elementoRoleFirmanteElemento.appendChild(elementoRolesDemandadosElementos);

    	
    	// Añadimos un nuevo elemento SignerRoles
    	StringTokenizer roles = new StringTokenizer(rolesFirmante, COMA);
    	boolean valor = roles.hasMoreElements();
     while(valor){
     	String role = (String) roles.nextElement();
     	Element elementClaimedRoleElement = doc.createElementNS(xadesSchema, xadesNS + DOS_PUNTOS + CLAIMED_ROLE);
     	elementClaimedRoleElement.appendChild(doc.createTextNode(role.trim()));
     	elementoRolesDemandadosElementos.appendChild(elementClaimedRoleElement);
     	valor = roles.hasMoreElements();
     }
     roleFirmante = true;
 }
    
    propiedadesFirmadasElementoFirma.appendChild(tiempoFirmaElemento);
    propiedadesFirmadasElemento.appendChild(propiedadesFirmadasElementoFirma);

    resumenCertificadoElemento.appendChild(metodoResumenElemento);
    resumenCertificadoElemento.appendChild(elementDigestValue);

    certificadoElemento.appendChild(resumenCertificadoElemento);

    elementoEmisorSerial.appendChild(elementoX509EmisorNombre);
    elementoEmisorSerial.appendChild(elementoX509NumeroSerial);

    certificadoElemento.appendChild(elementoEmisorSerial);


    certificadoFirmaElemento.appendChild(certificadoElemento);

    propiedadesFirmadasElementoFirma.appendChild(certificadoFirmaElemento);


    if(roleFirmante)
    {
    	propiedadesFirmadasElementoFirma.appendChild(elementoRoleFirmanteElemento);
    }
    elemntQualifyingProperties.appendChild(propiedadesFirmadasElemento);

    // Añadimos el objeto final
    Element elementoObjeto = doc.createElementNS(SCHEMA_DSIG, xmldsigNS + DOS_PUNTOS + OBJECT);
    elementoObjeto.setAttributeNS(null, ID, firmaID + GUION_OBJECT );

    elementoObjeto.appendChild(elemntQualifyingProperties);

    elementoPrincipalFirma.appendChild(elementoObjeto) ;
    return null;
}