Java Code Examples for java.util.Enumeration

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project AceWiki, under directory /src/ch/uzh/ifi/attempto/aceeditor/.

Source file: ACEEditorServlet.java

  18 
vote

@SuppressWarnings("rawtypes") private Map<String,String> getInitParameters(){
  Map<String,String> initParameters=new HashMap<String,String>();
  Enumeration paramEnum=getInitParameterNames();
  while (paramEnum.hasMoreElements()) {
    String paramName=paramEnum.nextElement().toString();
    initParameters.put(paramName,getInitParameter(paramName));
  }
  return initParameters;
}
 

Example 2

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source file: WebdavServlet.java

  18 
vote

/** 
 * Get a String representation of this lock token.
 */
public String toString(){
  String result="Type:" + type + "\n";
  result+="Scope:" + scope + "\n";
  result+="Depth:" + depth + "\n";
  result+="Owner:" + owner + "\n";
  result+="Expiration:" + org.apache.tomcat.util.http.FastHttpDateFormat.formatDate(expiresAt,null) + "\n";
  Enumeration tokensList=tokens.elements();
  while (tokensList.hasMoreElements()) {
    result+="Token:" + tokensList.nextElement() + "\n";
  }
  return result;
}
 

Example 3

From project alfredo, under directory /alfredo/src/main/java/com/cloudera/alfredo/server/.

Source file: AuthenticationFilter.java

  18 
vote

/** 
 * Returns the filtered configuration (only properties starting with the specified prefix). The property keys are also trimmed from the prefix. The returned <code>Properties</code> object is used to initialized the {@link AuthenticationHandler}. <p/> This method can be overriden by subclasses to obtain the configuration from other configuration source than the web.xml file.
 * @param configPrefix configuration prefix to use for extracting configuration properties.
 * @param filterConfig filter configuration object
 * @return the configuration to be used with the {@link AuthenticationHandler} instance.
 * @throws ServletException thrown if the configuration could not be created.
 */
protected Properties getConfiguration(String configPrefix,FilterConfig filterConfig) throws ServletException {
  Properties props=new Properties();
  Enumeration names=filterConfig.getInitParameterNames();
  while (names.hasMoreElements()) {
    String name=(String)names.nextElement();
    if (name.startsWith(configPrefix)) {
      String value=filterConfig.getInitParameter(name);
      props.put(name.substring(configPrefix.length()),value);
    }
  }
  return props;
}
 

Example 4

From project alphaportal_dev, under directory /sys-src/alphaportal/web/src/main/java/alpha/portal/webapp/controller/.

Source file: CardFormController.java

  18 
vote

/** 
 * shows the card form.
 * @param request the request
 * @return ModelView
 * @see cardform.jsp
 */
@SuppressWarnings("unchecked") @ModelAttribute("alphacard") @RequestMapping(method=RequestMethod.GET) protected String showForm(final HttpServletRequest request){
  this.log.fatal("This fallback Method should not be called");
  final Enumeration params=request.getParameterNames();
  while (params.hasMoreElements()) {
    this.log.error(params.nextElement().toString());
  }
  return "redirect:/caseMenu";
}
 

Example 5

From project Android_1, under directory /org.eclipse.ecf.android/src/org/eclipse/ecf/android/.

Source file: RemoteServiceRegistrationImpl.java

  18 
vote

/** 
 * Get the list of key names for the service's properties.
 * @return The list of property key names.
 */
protected synchronized String[] getPropertyKeys(){
  final int size=size();
  final String[] keynames=new String[size];
  final Enumeration keysEnum=keys();
  for (int i=0; i < size; i++) {
    keynames[i]=(String)keysEnum.nextElement();
  }
  return (keynames);
}
 

Example 6

From project android_external_tagsoup, under directory /src/org/ccil/cowan/tagsoup/.

Source file: XMLWriter.java

  18 
vote

/** 
 * Force all Namespaces to be declared. This method is used on the root element to ensure that the predeclared Namespaces all appear.
 */
private void forceNSDecls(){
  Enumeration prefixes=forcedDeclTable.keys();
  while (prefixes.hasMoreElements()) {
    String prefix=(String)prefixes.nextElement();
    doPrefix(prefix,null,true);
  }
}
 

Example 7

From project artifactory-plugin, under directory /src/main/java/org/jfrog/hudson/release/gradle/.

Source file: GradleReleaseAction.java

  18 
vote

@Override protected void doPerModuleVersioning(StaplerRequest req){
  releaseVersionPerModule=Maps.newHashMap();
  nextVersionPerModule=Maps.newHashMap();
  Enumeration params=req.getParameterNames();
  while (params.hasMoreElements()) {
    String key=(String)params.nextElement();
    if (key.startsWith("release.")) {
      releaseVersionPerModule.put(StringUtils.removeStart(key,"release."),req.getParameter(key));
    }
 else     if (key.startsWith("next.")) {
      nextVersionPerModule.put(StringUtils.removeStart(key,"next."),req.getParameter(key));
    }
  }
}
 

Example 8

From project beanmill_1, under directory /src/main/java/com/traxel/lumbermill/event/.

Source file: ColumnSet.java

  18 
vote

/** 
 * DOCUMENT ME!
 * @param column  DOCUMENT ME!
 * @return  DOCUMENT ME!
 */
boolean contains(final Column column){
  if (column == null) {
    return false;
  }
  final Enumeration enumeration;
  enumeration=getColumns();
  while (enumeration.hasMoreElements()) {
    if (column.equals(enumeration.nextElement())) {
      return true;
    }
  }
  return false;
}
 

Example 9

From project blog_1, under directory /stat4j/src/net/sourceforge/stat4j/util/.

Source file: Util.java

  18 
vote

public static Properties createProperties(String context){
  Properties p=new Properties();
  Enumeration keys=bundle.getKeys();
  while (keys.hasMoreElements()) {
    String key=(String)keys.nextElement();
    if (key.startsWith(context)) {
      String k=key.substring(context.length());
      String value=bundle.getString(key);
      p.put(k,value);
    }
  }
  return p;
}
 

Example 10

From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/utils/.

Source file: JavaUtils.java

  18 
vote

public static void copy(Dictionary destination,Dictionary source){
  Enumeration e=source.keys();
  while (e.hasMoreElements()) {
    Object key=e.nextElement();
    Object value=source.get(key);
    destination.put(key,value);
  }
}
 

Example 11

From project brightberry, under directory /src/org/json/me/.

Source file: JSONObject.java

  18 
vote

/** 
 * Construct a JSONObject from a Map.
 * @param map A map object that can be used to initialize the contents ofthe JSONObject.
 */
public JSONObject(Hashtable map){
  if (map == null) {
    this.myHashMap=new Hashtable();
  }
 else {
    this.myHashMap=new Hashtable(map.size());
    Enumeration keys=map.keys();
    while (keys.hasMoreElements()) {
      Object key=keys.nextElement();
      this.myHashMap.put(key,map.get(key));
    }
  }
}
 

Example 12

From project camel-osgi, under directory /component/src/main/java/org/apache/camel/osgi/service/util/.

Source file: BundleDelegatingClassLoader.java

  18 
vote

@SuppressWarnings("unchecked") protected Enumeration findResources(String name) throws IOException {
  Enumeration resources=bundle.getResources(name);
  if (classLoader != null && (resources == null || !resources.hasMoreElements())) {
    resources=classLoader.getResources(name);
  }
  return resources;
}
 

Example 13

From project Carolina-Digital-Repository, under directory /admin/src/main/java/edu/unc/lib/dl/util/.

Source file: Log4JManager.java

  18 
vote

/** 
 * Gets the names of the the currently active loggers.
 * @return an array of the names of the currently active loggers.
 */
public String[] getCurrentLoggers(){
  List<String> loggers=new ArrayList<String>();
  Enumeration en=LogManager.getLoggerRepository().getCurrentLoggers();
  while (en.hasMoreElements()) {
    Logger l=(Logger)en.nextElement();
    loggers.add(l.getName());
  }
  Collections.sort(loggers);
  return loggers.toArray(new String[loggers.size()]);
}
 

Example 14

From project caustic, under directory /core/src/net/caustic/http/.

Source file: BasicCookieManager.java

  18 
vote

public String[] getCookiesFor(String urlStr,Hashtable requestHeaders) throws BadURLException {
  Hashtable cookiesForDomain=getCookies(urlStr);
  final Vector result=new Vector();
  Enumeration e=cookiesForDomain.keys();
  while (e.hasMoreElements()) {
    String name=(String)e.nextElement();
    result.addElement(name + "=" + cookiesForDomain.get(name));
  }
  String[] resultAry=new String[result.size()];
  result.copyInto(resultAry);
  return resultAry;
}
 

Example 15

From project cellar, under directory /config/src/main/java/net/cellar/config/.

Source file: ConfigurationSupport.java

  18 
vote

/** 
 * Reads a  {@code Dictionary} object and creates a property object out of it.
 * @param dictionary
 * @return
 */
public Properties dictionaryToProperties(Dictionary dictionary){
  Properties properties=new Properties();
  if (dictionary != null && dictionary.keys() != null) {
    Enumeration keys=dictionary.keys();
    while (keys.hasMoreElements()) {
      String key=(String)keys.nextElement();
      if (key != null && dictionary.get(key) != null) {
        String value=(String)dictionary.get(key);
        properties.put(key,dictionary.get(key));
      }
    }
  }
  return properties;
}
 

Example 16

From project activemq-apollo, under directory /apollo-distro/src/main/release/examples/openwire/jms-example-message-browser/src/main/java/example/browser/.

Source file: Browser.java

  17 
vote

public static void main(String[] args){
  ActiveMQConnectionFactory connectionFactory=new ActiveMQConnectionFactory("admin","password",BROKER_URL);
  Connection connection=null;
  try {
    connection=connectionFactory.createConnection();
    connection.start();
    Session session=connection.createSession(NON_TRANSACTED,Session.AUTO_ACKNOWLEDGE);
    Queue destination=session.createQueue("test-queue");
    QueueBrowser browser=session.createBrowser(destination);
    Enumeration enumeration=browser.getEnumeration();
    while (enumeration.hasMoreElements()) {
      TextMessage message=(TextMessage)enumeration.nextElement();
      System.out.println("Browsing: " + message);
      TimeUnit.MILLISECONDS.sleep(DELAY);
    }
    session.close();
  }
 catch (  Exception e) {
    System.out.println("Caught exception!");
  }
 finally {
    if (connection != null) {
      try {
        connection.close();
      }
 catch (      JMSException e) {
        System.out.println("Could not close an open connection...");
      }
    }
  }
}
 

Example 17

From project AlbiteREADER, under directory /src/org/albite/dictionary/.

Source file: DictionaryManager.java

  17 
vote

public final void reloadDictionaries(){
  closeDictionaries();
  final Vector dicts=new Vector();
  if (folder == null) {
    return;
  }
  try {
    FileConnection f=(FileConnection)Connector.open(folder,Connector.READ);
    if (f.exists() && f.isDirectory()) {
      final Enumeration filesList=f.list("*" + Dictionary.FILE_EXTENSION,true);
      while (filesList.hasMoreElements()) {
        final String s=(String)filesList.nextElement();
        try {
          final Dictionary dict=new Dictionary(folder + s);
          dicts.addElement(dict);
        }
 catch (        DictionaryException e) {
        }
      }
    }
  }
 catch (  Exception e) {
  }
  final int size=dicts.size();
  if (size > 0) {
    dictionaries=new Dictionary[size];
    for (int i=0; i < size; i++) {
      dictionaries[i]=(Dictionary)dicts.elementAt(i);
    }
  }
 else {
    dictionaries=null;
  }
}
 

Example 18

From project apb, under directory /modules/apb-installer/src/apb/installer/.

Source file: Installer.java

  17 
vote

private void extract(JarFile jar,String prefix,File targetDir) throws IOException {
  Enumeration e=jar.entries();
  while (e.hasMoreElements()) {
    JarEntry entry=(JarEntry)e.nextElement();
    String name=entry.getName();
    if (name.startsWith("apb-")) {
      if (prefix == null) {
        extract(jar,entry,targetDir,name);
      }
 else {
        name=name.substring(name.indexOf('/') + 1);
        if (name.startsWith(prefix)) {
          name=name.substring(prefix.length());
          if (name.length() > 0) {
            extract(jar,entry,targetDir,name);
          }
        }
      }
    }
  }
}
 

Example 19

From project Application-Builder, under directory /src/main/java/org/silverpeas/applicationbuilder/.

Source file: ReadOnlyArchive.java

  17 
vote

/** 
 * @param entry the entry to read
 * @return the jarEntry of the entry (null if not found or directory)
 * @since 1.0/B
 * @roseuid 3AB080F602D2
 */
private JarEntry getJarEntry(ApplicationBuilderItem entry){
  if (getJar() == null) {
    return null;
  }
  JarEntry jarEntry=null;
  File entryFile=null;
  Enumeration e=getJar().entries();
  while (e.hasMoreElements()) {
    jarEntry=(JarEntry)e.nextElement();
    entryFile=new File(jarEntry.getName());
    if (entryFile.getPath().equals(entry.getArchivePath())) {
      return jarEntry;
    }
  }
  return null;
}
 

Example 20

From project arquillian-container-openwebbeans, under directory /openwebbeans-embedded-1/src/main/java/org/jboss/arquillian/container/openwebbeans/embedded_1/.

Source file: MockHttpSession.java

  17 
vote

public Enumeration getAttributeNames(){
  final Iterator<String> nameIt=attributes.keySet().iterator();
  return new Enumeration(){
    public boolean hasMoreElements(){
      return nameIt.hasNext();
    }
    public Object nextElement(){
      return nameIt.next();
    }
  }
;
}
 

Example 21

From project arquillian_deprecated, under directory /containers/openwebbeans-embedded-1/src/main/java/org/jboss/arquillian/container/openwebbeans/embedded_1/.

Source file: MockHttpSession.java

  17 
vote

public Enumeration getAttributeNames(){
  final Iterator<String> nameIt=attributes.keySet().iterator();
  return new Enumeration(){
    public boolean hasMoreElements(){
      return nameIt.hasNext();
    }
    public Object nextElement(){
      return nameIt.next();
    }
  }
;
}
 

Example 22

From project aviator, under directory /src/main/java/com/googlecode/aviator/asm/optimizer/.

Source file: JarOptimizer.java

  17 
vote

static void optimize(final File f) throws IOException {
  if (f.isDirectory()) {
    File[] files=f.listFiles();
    for (int i=0; i < files.length; ++i) {
      optimize(files[i]);
    }
  }
 else   if (f.getName().endsWith(".jar")) {
    File g=new File(f.getParentFile(),f.getName() + ".new");
    ZipFile zf=new ZipFile(f);
    ZipOutputStream out=new ZipOutputStream(new FileOutputStream(g));
    Enumeration e=zf.entries();
    byte[] buf=new byte[10000];
    while (e.hasMoreElements()) {
      ZipEntry ze=(ZipEntry)e.nextElement();
      if (ze.isDirectory()) {
        continue;
      }
      out.putNextEntry(ze);
      InputStream is=zf.getInputStream(ze);
      int n;
      do {
        n=is.read(buf,0,buf.length);
        if (n != -1) {
          out.write(buf,0,n);
        }
      }
 while (n != -1);
      out.closeEntry();
    }
    out.close();
    zf.close();
    f.delete();
    g.renameTo(f);
  }
}
 

Example 23

From project behemoth, under directory /gate/src/test/java/com/digitalpebble/behemoth/gate/.

Source file: GATEProcessorTest.java

  17 
vote

/** 
 * Unzips the argument into the temp directory and returns the unzipped location.
 */
public static File unzip(File inputZip){
  File rootDir=null;
  try {
    BufferedOutputStream dest=null;
    BufferedInputStream is=null;
    ZipEntry entry;
    ZipFile zipfile=new ZipFile(inputZip);
    String zipname=inputZip.getName().replaceAll("\\.zip","");
    File test=File.createTempFile("aaa","aaa");
    String tempDir=test.getParent();
    test.delete();
    rootDir=new File(tempDir,zipname);
    rootDir.mkdir();
    Enumeration e=zipfile.entries();
    while (e.hasMoreElements()) {
      entry=(ZipEntry)e.nextElement();
      is=new BufferedInputStream(zipfile.getInputStream(entry));
      int count;
      byte data[]=new byte[BUFFER];
      File target=new File(rootDir,entry.getName());
      if (entry.getName().endsWith("/")) {
        target.mkdir();
        continue;
      }
      FileOutputStream fos=new FileOutputStream(target);
      dest=new BufferedOutputStream(fos,BUFFER);
      while ((count=is.read(data,0,BUFFER)) != -1) {
        dest.write(data,0,count);
      }
      dest.flush();
      dest.close();
      is.close();
    }
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return rootDir;
}
 

Example 24

From project bioclipse.speclipse, under directory /plugins/net.bioclipse.spectrum/src/net/bioclipse/spectrum/graph2d/.

Source file: Axis.java

  17 
vote

/** 
 * Return the minimum value of All datasets attached to the axis.
 * @return Data minimum
 */
public double getDataMin(){
  double m;
  Enumeration e;
  DataSet d;
  if (dataset.isEmpty())   return 0.0;
  d=(DataSet)(dataset.firstElement());
  if (d == null)   return 0.0;
  if (orientation == HORIZONTAL) {
    m=d.getXmin();
    for (e=dataset.elements(); e.hasMoreElements(); ) {
      d=(DataSet)e.nextElement();
      m=Math.min(d.getXmin(),m);
    }
  }
 else {
    m=d.getYmin();
    for (e=dataset.elements(); e.hasMoreElements(); ) {
      d=(DataSet)e.nextElement();
      m=Math.min(d.getYmin(),m);
    }
  }
  return m;
}
 

Example 25

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/com/google/zxing/.

Source file: Result.java

  17 
vote

public void putAllMetadata(Hashtable metadata){
  if (metadata != null) {
    if (resultMetadata == null) {
      resultMetadata=metadata;
    }
 else {
      Enumeration e=metadata.keys();
      while (e.hasMoreElements()) {
        ResultMetadataType key=(ResultMetadataType)e.nextElement();
        Object value=metadata.get(key);
        resultMetadata.put(key,value);
      }
    }
  }
}
 

Example 26

From project Blackberry-Sample-App, under directory /BlackberrySampleApp/src/pe/com/avances/sampleapp/doclist/.

Source file: DocumentListView.java

  17 
vote

public DocumentListView(Vector documents){
  super(SCREEN_TITLE,false);
  Bitmap caret=Bitmap.getBitmapResource("chevron_right_black_12x18.png");
  Bitmap leftIcon=Bitmap.getBitmapResource("BulletPointWineRed.png");
  Enumeration enumeration=documents.elements();
  while (enumeration.hasMoreElements()) {
    Document document=(Document)enumeration.nextElement();
    ListStyleButtonField documentListItem=new ListStyleButtonField(leftIcon,document.toString(),caret,0);
    documentListItem.setChangeListener(new FieldChangeListener(){
      public void fieldChanged(      Field field,      int context){
        notifyViewListeners(EventCatalog.DOCUMENT_SELECTED);
      }
    }
);
    add(documentListItem);
  }
}
 

Example 27

From project blacktie, under directory /stompconnect-1.0/src/main/java/org/codehaus/stomp/jms/.

Source file: StompSession.java

  17 
vote

protected void copyStandardHeadersFromMessageToFrame(Message message,StompFrame command) throws JMSException {
  final Map headers=command.getHeaders();
  headers.put(Stomp.Headers.Message.DESTINATION,convertDestination(message.getJMSDestination()));
  headers.put(Stomp.Headers.Message.MESSAGE_ID,message.getJMSMessageID());
  if (message.getJMSCorrelationID() != null) {
    headers.put(Stomp.Headers.Message.CORRELATION_ID,message.getJMSCorrelationID());
  }
  headers.put(Stomp.Headers.Message.EXPIRATION_TIME,"" + message.getJMSExpiration());
  if (message.getJMSRedelivered()) {
    headers.put(Stomp.Headers.Message.REDELIVERED,"true");
  }
  headers.put(Stomp.Headers.Message.PRORITY,"" + message.getJMSPriority());
  if (message.getJMSReplyTo() != null) {
    headers.put(Stomp.Headers.Message.REPLY_TO,convertDestination(message.getJMSReplyTo()));
  }
  headers.put(Stomp.Headers.Message.TIMESTAMP,"" + message.getJMSTimestamp());
  if (message.getJMSType() != null) {
    headers.put(Stomp.Headers.Message.TYPE,message.getJMSType());
  }
  Enumeration names=message.getPropertyNames();
  while (names.hasMoreElements()) {
    String name=(String)names.nextElement();
    Object value=message.getObjectProperty(name);
    headers.put(name,value);
  }
}
 

Example 28

From project bpelunit, under directory /net.bpelunit.framework.client.maven/src/main/java/net/bpelunit/framework/client/maven/.

Source file: BPELUnitMojo.java

  17 
vote

private void addProperties(Xpp3Dom testSuite){
  Xpp3Dom properties=new Xpp3Dom("properties");
  testSuite.addChild(properties);
  Properties systemProperties=System.getProperties();
  if (systemProperties != null) {
    @SuppressWarnings("rawtypes") Enumeration propertyKeys=systemProperties.propertyNames();
    while (propertyKeys.hasMoreElements()) {
      String key=(String)propertyKeys.nextElement();
      String value=systemProperties.getProperty(key);
      if (value == null) {
        value="null";
      }
      Xpp3Dom property=new Xpp3Dom("property");
      properties.addChild(property);
      property.setAttribute("name",key);
      property.setAttribute("value",value);
    }
  }
}
 

Example 29

From project BSPAN---Bluetooth-Sensor-Processing-for-Android, under directory /AndroidSpineServer/src/spine/.

Source file: SPINEManager.java

  17 
vote

/** 
 * package-scoped method called by SPINEFactory. The caller must guarantee that moteCom and platform are not null. 
 */
SPINEManager(String moteCom,String platform){
  try {
    MOTECOM=moteCom;
    PLATFORM=platform;
    MY_GROUP_ID=(byte)Short.parseShort(prop.getProperty(Properties.GROUP_ID_KEY),16);
    LOCALNODEADAPTER_CLASSNAME=prop.getProperty(PLATFORM + "_" + Properties.LOCALNODEADAPTER_CLASSNAME_KEY);
    URL_PREFIX=prop.getProperty(PLATFORM + "_" + Properties.URL_PREFIX_KEY);
    SPINEDATACODEC_PACKAGE=SPINEDATACODEC_PACKAGE_PREFIX + prop.getProperty(PLATFORM + "_" + Properties.SPINEDATACODEC_PACKAGE_SUFFIX_KEY) + ".";
    MESSAGE_CLASSNAME=prop.getProperty(PLATFORM + "_" + Properties.MESSAGE_CLASSNAME_KEY);
    SPINE_SERVICE_MESSAGE_CODEC_PACKAGE=SPINE_SERVICE_MESSAGE_CODEC_PACKAGE_PREFIX + prop.getProperty(PLATFORM + "_" + Properties.SPINEDATACODEC_PACKAGE_SUFFIX_KEY) + ".";
    System.setProperty(Properties.LOCALNODEADAPTER_CLASSNAME_KEY,LOCALNODEADAPTER_CLASSNAME);
    nodeAdapter=LocalNodeAdapter.getLocalNodeAdapter();
    Vector params=new Vector();
    params.addElement(MOTECOM);
    nodeAdapter.init(params);
    java.util.logging.LogManager mng=java.util.logging.LogManager.getLogManager();
    Enumeration e=mng.getLoggerNames();
    nodeAdapter.start();
    connection=nodeAdapter.createAPSConnection();
    baseStation=new Node(new Address("" + SPINEPacketsConstants.SPINE_BASE_STATION));
    baseStation.setLogicalID(new Address(SPINEPacketsConstants.SPINE_BASE_STATION_LABEL));
    eventDispatcher=new EventDispatcher(this);
  }
 catch (  NumberFormatException e) {
    exit(DEF_PROP_MISSING_MSG);
  }
catch (  ClassNotFoundException e) {
    e.printStackTrace();
    if (l.isLoggable(Logger.SEVERE))     l.log(Logger.SEVERE,e.getMessage());
  }
catch (  InstantiationException e) {
    e.printStackTrace();
    if (l.isLoggable(Logger.SEVERE))     l.log(Logger.SEVERE,e.getMessage());
  }
catch (  IllegalAccessException e) {
    e.printStackTrace();
    if (l.isLoggable(Logger.SEVERE))     l.log(Logger.SEVERE,e.getMessage());
  }
}
 

Example 30

From project bundlemaker, under directory /integrationtest/org.bundlemaker.itest.spring/src/org/bundlemaker/itest/spring/experimental/.

Source file: SpecialComponent.java

  17 
vote

/** 
 * Extracts a directory from the archive given a path prefix for entries to retrieve. <code>null</code> can be passed in as a prefix, causing all entries to be be extracted from the archive.
 * @param zip the  {@link ZipFile} to extract from
 * @param pathprefix the prefix'ing path to include for extraction
 * @param parent the parent directory to extract to
 * @throws IOException if the  {@link ZipFile} cannot be read or extraction fails to write the file(s)
 */
void extractDirectory(ZipFile zip,String pathprefix,File parent) throws IOException {
  Enumeration entries=zip.entries();
  String prefix=(pathprefix == null ? Util.EMPTY_STRING : pathprefix);
  ZipEntry entry=null;
  File file=null;
  while (entries.hasMoreElements()) {
    entry=(ZipEntry)entries.nextElement();
    if (entry.getName().startsWith(prefix)) {
      file=new File(parent,entry.getName());
      if (entry.isDirectory()) {
        file.mkdir();
        continue;
      }
      extractEntry(zip,entry,parent);
    }
  }
}
 

Example 31

From project cameraptp, under directory /src/main/resources/.

Source file: JPhoto.java

  17 
vote

private static void cameras(String argv[],int index) throws IOException {
  if (index != (argv.length - 1))   usage(-1);
  Enumeration cameras=getCameras().elements();
  while (cameras.hasMoreElements()) {
    Device dev=(Device)cameras.nextElement();
    DeviceDescriptor desc=dev.getDeviceDescriptor();
    String temp;
    System.out.print(dev.getPortIdentifier().toString());
    System.out.print("\t");
    if ((temp=desc.getProduct(0)) == null) {
      System.out.print("0x");
      System.out.print(Integer.toHexString(desc.getVendorId()));
      System.out.print("/0x");
      System.out.print(Integer.toHexString(desc.getProductId()));
      System.out.println();
    }
 else     System.out.println(temp);
  }
}
 

Example 32

From project capedwarf-blue, under directory /tasks/src/main/java/org/jboss/capedwarf/tasks/.

Source file: TasksServletRequestCreator.java

  17 
vote

static Map<String,Set<String>> get(final Message msg,final String prefix) throws JMSException {
  String regexSafeDelimiter=Pattern.quote(DELIMITER);
  final Map<String,Set<String>> map=new HashMap<String,Set<String>>();
  final Enumeration names=msg.getPropertyNames();
  while (names.hasMoreElements()) {
    final String name=names.nextElement().toString();
    final String value=msg.getStringProperty(name);
    if (name.startsWith(prefix) && name.endsWith(COPY) == false) {
      final String property=msg.getStringProperty(name + COPY);
      if (property != null) {
        map.put(value,new HashSet<String>(Arrays.asList(property.split(regexSafeDelimiter))));
      }
    }
  }
  return map;
}
 

Example 33

From project android_build, under directory /tools/signapk/.

Source file: SignApk.java

  16 
vote

/** 
 * Add the SHA1 of every file to the manifest, creating it if necessary. 
 */
private static Manifest addDigestsToManifest(JarFile jar) throws IOException, GeneralSecurityException {
  Manifest input=jar.getManifest();
  Manifest output=new Manifest();
  Attributes main=output.getMainAttributes();
  if (input != null) {
    main.putAll(input.getMainAttributes());
  }
 else {
    main.putValue("Manifest-Version","1.0");
    main.putValue("Created-By","1.0 (Android SignApk)");
  }
  BASE64Encoder base64=new BASE64Encoder();
  MessageDigest md=MessageDigest.getInstance("SHA1");
  byte[] buffer=new byte[4096];
  int num;
  TreeMap<String,JarEntry> byName=new TreeMap<String,JarEntry>();
  for (Enumeration<JarEntry> e=jar.entries(); e.hasMoreElements(); ) {
    JarEntry entry=e.nextElement();
    byName.put(entry.getName(),entry);
  }
  for (  JarEntry entry : byName.values()) {
    String name=entry.getName();
    if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME)&& !name.equals(CERT_RSA_NAME)&& (stripPattern == null || !stripPattern.matcher(name).matches())) {
      InputStream data=jar.getInputStream(entry);
      while ((num=data.read(buffer)) > 0) {
        md.update(buffer,0,num);
      }
      Attributes attr=null;
      if (input != null)       attr=input.getAttributes(name);
      attr=attr != null ? new Attributes(attr) : new Attributes();
      attr.putValue("SHA1-Digest",base64.encode(md.digest()));
      output.getEntries().put(name,attr);
    }
  }
  return output;
}
 

Example 34

From project acceleo-webapp-generator, under directory /plugins/org.eclipse.acceleo.tutorial.extension.ui/src/org/eclipse/acceleo/tutorial/extension/ui/common/.

Source file: GenerateAll.java

  15 
vote

/** 
 * Finds the template in the plug-in. Returns the template plug-in URI.
 * @param bundleID is the plug-in ID
 * @param relativePath is the relative path of the template in the plug-in
 * @return the template URI
 * @throws IOException
 * @generated
 */
@SuppressWarnings("unchecked") private URI getTemplateURI(String bundleID,IPath relativePath) throws IOException {
  Bundle bundle=Platform.getBundle(bundleID);
  if (bundle == null) {
    return URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(),false);
  }
  URL url=bundle.getEntry(relativePath.toString());
  if (url == null && relativePath.segmentCount() > 1) {
    Enumeration<URL> entries=bundle.findEntries("/","*.emtl",true);
    if (entries != null) {
      String[] segmentsRelativePath=relativePath.segments();
      while (url == null && entries.hasMoreElements()) {
        URL entry=entries.nextElement();
        IPath path=new Path(entry.getPath());
        if (path.segmentCount() > relativePath.segmentCount()) {
          path=path.removeFirstSegments(path.segmentCount() - relativePath.segmentCount());
        }
        String[] segmentsPath=path.segments();
        boolean equals=segmentsPath.length == segmentsRelativePath.length;
        for (int i=0; equals && i < segmentsPath.length; i++) {
          equals=segmentsPath[i].equals(segmentsRelativePath[i]);
        }
        if (equals) {
          url=bundle.getEntry(entry.getPath());
        }
      }
    }
  }
  URI result;
  if (url != null) {
    result=URI.createPlatformPluginURI(new Path(bundleID).append(new Path(url.getPath())).toString(),false);
  }
 else {
    result=URI.createPlatformResourceURI(new Path(bundleID).append(relativePath).toString(),false);
  }
  return result;
}
 

Example 35

From project activejdbc, under directory /activejdbc-instrumentation/src/main/java/org/javalite/instrumentation/.

Source file: InstrumentationModelFinder.java

  15 
vote

/** 
 * Finds and processes property files inside zip or jar files.
 * @param file zip or jar file.
 */
private void processFilePath(File file){
  try {
    if (file.getCanonicalPath().toLowerCase().endsWith(".jar") || file.getCanonicalPath().toLowerCase().endsWith(".zip")) {
      ZipFile zip=new ZipFile(file);
      Enumeration<? extends ZipEntry> entries=zip.entries();
      while (entries.hasMoreElements()) {
        ZipEntry entry=entries.nextElement();
        if (entry.getName().endsWith("class")) {
          InputStream zin=zip.getInputStream(entry);
          classFound(entry.getName().replace(File.separatorChar,'.').substring(0,entry.getName().length() - 6));
          zin.close();
        }
      }
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
catch (  ClassNotFoundException ignore) {
  }
}
 

Example 36

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/session/.

Source file: HttpSessionContext.java

  15 
vote

public Set<String> getKeySet(){
  HashSet<String> result=new HashSet<String>();
  for (@SuppressWarnings("unchecked") Enumeration<String> e=session.getAttributeNames(); e.hasMoreElements(); ) {
    result.add(e.nextElement());
  }
  return result;
}
 

Example 37

From project addis, under directory /application/src/main/java/org/drugis/addis/gui/.

Source file: WelcomeDialog.java

  15 
vote

public static JRadioButton getSelection(ButtonGroup group){
  for (Enumeration<AbstractButton> e=group.getElements(); e.hasMoreElements(); ) {
    JRadioButton b=(JRadioButton)e.nextElement();
    if (b.getModel() == group.getSelection()) {
      return b;
    }
  }
  return null;
}
 

Example 38

From project aether-core, under directory /aether-connector-asynchttpclient/src/test/java/org/eclipse/aether/connector/async/.

Source file: HttpServer.java

  15 
vote

public void handle(String target,HttpServletRequest request,HttpServletResponse response,int dispatch){
  String uri=request.getRequestURI();
  for (  String pattern : recordedPatterns) {
    if (uri.matches(pattern)) {
      String req=request.getMethod() + " " + uri;
      recordedRequests.add(req);
      Map<String,String> headers=new HashMap<String,String>();
      recordedHeaders.put(uri,headers);
      for (@SuppressWarnings("unchecked") Enumeration<String> h=request.getHeaderNames(); h.hasMoreElements(); ) {
        String headername=h.nextElement();
        headers.put(headername,request.getHeader(headername));
      }
    }
  }
}
 

Example 39

From project ajah, under directory /ajah-servlet/src/main/java/com/ajah/servlet/util/.

Source file: SessionUtils.java

  15 
vote

/** 
 * This method will call  {@link HttpSession#removeAttribute(String)} on eachattribute to ensure that they are cleared.
 * @param session session to clear, required.
 */
public static void clearSessionAttributes(final HttpSession session){
  AjahUtils.requireParam(session,"session");
  final Enumeration<?> names=session.getAttributeNames();
  while (names.hasMoreElements()) {
    session.removeAttribute((String)names.nextElement());
  }
}
 

Example 40

From project ALP, under directory /workspace/alp-reporter/src/main/java/com/lohika/alp/reporter/helpers/.

Source file: Resources.java

  15 
vote

/** 
 * Copy JAR resources from path to outside destination. If destination does not exist, it will be created
 * @param jar package with required resources
 * @param path resources path inside package. Should end with "/", but not start with one
 * @param destination outside destination
 * @throws IOException
 */
public void copy(JarFile jar,String path,File destination) throws IOException {
  logger.debug("Copying " + path + " to "+ destination);
  Enumeration<JarEntry> entries=jar.entries();
  int len=path.length();
  while (entries.hasMoreElements()) {
    JarEntry entry=entries.nextElement();
    String name=entry.getName();
    if (name.startsWith(path)) {
      File file=new File(destination,name.substring(len));
      if (entry.isDirectory())       file.mkdir();
 else {
        InputStream is=jar.getInputStream(entry);
        FileOutputStream os=new FileOutputStream(file);
        while (is.available() > 0) {
          os.write(is.read());
        }
        os.close();
        is.close();
      }
    }
  }
}
 

Example 41

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/.

Source file: BaseIterableIterator.java

  15 
vote

@SuppressWarnings("unchecked") protected static <T>Iterator<T> extractIterator(Object k){
  while (k instanceof Reference) {
    k=((Reference)k).get();
  }
  if (k == null) {
    return (Iterator<T>)Collections.emptyList().iterator();
  }
 else   if (k instanceof Iterator) {
    return (Iterator<T>)k;
  }
 else   if (k instanceof Iterable) {
    return ((Iterable<T>)k).iterator();
  }
 else   if (k instanceof Map) {
    return ((Map)k).entrySet().iterator();
  }
 else   if (k instanceof Enumeration) {
    return new IterEnum<T>((Enumeration<T>)k);
  }
 else   if (k.getClass().isArray()) {
    return Arrays.asList((T[])k).iterator();
  }
 else {
    return Arrays.asList((T)k).iterator();
  }
}
 

Example 42

From project anadix, under directory /parsers/anadix-swingparser/src/main/java/org/anadix/swingparser/.

Source file: StatefulParserCallback.java

  15 
vote

private Properties parseAttributes(MutableAttributeSet attributes){
  Properties result=new Properties();
  Enumeration<?> names=attributes.getAttributeNames();
  Object name;
  while (names.hasMoreElements()) {
    name=names.nextElement();
    result.setProperty(name.toString().toLowerCase(),attributes.getAttribute(name).toString().toLowerCase());
  }
  return result;
}
 

Example 43

From project andlytics, under directory /src/com/github/andlyticsproject/io/.

Source file: StatsCsvReaderWriter.java

  15 
vote

public static List<String> getImportFileNamesFromZip(String accountName,List<String> packageNames,String zipFilename) throws ServiceExceptoin {
  List<String> result=new ArrayList<String>();
  try {
    if (!new File(zipFilename).exists()) {
      return result;
    }
    ZipFile zipFile=new ZipFile(zipFilename);
    Enumeration<? extends ZipEntry> entries=zipFile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry=entries.nextElement();
      InputStream in=zipFile.getInputStream(entry);
      if (isValidFile(accountName,in,packageNames)) {
        result.add(entry.getName());
      }
    }
    return result;
  }
 catch (  IOException e) {
    Log.e(TAG,"Error reading zip file: " + e.getMessage());
    return new ArrayList<String>();
  }
}
 

Example 44

From project android-aac-enc, under directory /src/com/coremedia/iso/.

Source file: PropertyBoxParserImpl.java

  15 
vote

public PropertyBoxParserImpl(String... customProperties){
  Context context=AACToM4A.getContext();
  InputStream raw=null, is=null;
  mapping=new Properties();
  try {
    raw=context.getResources().openRawResource(R.raw.isoparser);
    is=new BufferedInputStream(raw);
    mapping.load(is);
    Enumeration<URL> enumeration=Thread.currentThread().getContextClassLoader().getResources("isoparser-custom.properties");
    while (enumeration.hasMoreElements()) {
      URL url=enumeration.nextElement();
      InputStream customIS=new BufferedInputStream(url.openStream());
      try {
        mapping.load(customIS);
      }
  finally {
        customIS.close();
      }
    }
    for (    String customProperty : customProperties) {
      mapping.load(new BufferedInputStream(getClass().getResourceAsStream(customProperty)));
    }
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
 finally {
    try {
      if (raw != null)       raw.close();
      if (is != null)       is.close();
    }
 catch (    IOException e) {
      e.printStackTrace();
    }
  }
}
 

Example 45

From project android-client_1, under directory /src/org/apache/harmony/javax/security/sasl/.

Source file: Sasl.java

  15 
vote

/** 
 * This method forms the list of SaslClient/SaslServer factories which are implemented in used providers
 */
private static Collection<?> findFactories(String service){
  HashSet<Object> fact=new HashSet<Object>();
  Provider[] pp=Security.getProviders();
  if ((pp == null) || (pp.length == 0)) {
    return fact;
  }
  HashSet<String> props=new HashSet<String>();
  for (int i=0; i < pp.length; i++) {
    String prName=pp[i].getName();
    Enumeration<Object> keys=pp[i].keys();
    while (keys.hasMoreElements()) {
      String s=(String)keys.nextElement();
      if (s.startsWith(service)) {
        String prop=pp[i].getProperty(s);
        try {
          if (props.add(prName.concat(prop))) {
            fact.add(newInstance(prop,pp[i]));
          }
        }
 catch (        SaslException e) {
          e.printStackTrace();
        }
      }
    }
  }
  return fact;
}
 

Example 46

From project android-tether, under directory /src/og/android/tether/.

Source file: AccessControlActivity.java

  15 
vote

private ArrayList<ClientData> getCurrentClientData(){
  ArrayList<ClientData> clientDataList=new ArrayList<ClientData>();
  Hashtable<String,ClientData> leases=null;
  try {
    leases=application.coretask.getLeases();
  }
 catch (  Exception e) {
    AccessControlActivity.this.application.displayToastMessage(getString(R.string.accesscontrol_activity_error_read_leasefile));
  }
  if (whitelist != null) {
    for (    String macAddress : whitelist.get()) {
      ClientData clientData=new ClientData();
      clientData.setConnected(false);
      clientData.setIpAddress(getString(R.string.accesscontrol_activity_not_connected));
      if (leases.containsKey(macAddress)) {
        clientData=leases.get(macAddress);
        Log.d(MSG_TAG,clientData.isConnected() + " - " + clientData.getIpAddress());
        leases.remove(macAddress);
      }
      clientData.setAccessAllowed(true);
      clientData.setMacAddress(macAddress);
      clientDataList.add(clientData);
    }
  }
  if (leases != null) {
    Enumeration<String> enumLeases=leases.keys();
    while (enumLeases.hasMoreElements()) {
      String macAddress=enumLeases.nextElement();
      clientDataList.add(leases.get(macAddress));
    }
  }
  this.application.resetClientMacLists();
  return clientDataList;
}
 

Example 47

From project android_external_guava, under directory /src/com/google/common/collect/.

Source file: Iterators.java

  15 
vote

/** 
 * Adapts an  {@code Enumeration} to the {@code Iterator} interface.<p>This method has no equivalent in  {@link Iterables} because viewing an{@code Enumeration} as an {@code Iterable} is impossible. However, thecontents can be <i>copied</i> into a collection using  {@link Collections#list}.
 */
public static <T>UnmodifiableIterator<T> forEnumeration(final Enumeration<T> enumeration){
  checkNotNull(enumeration);
  return new UnmodifiableIterator<T>(){
    public boolean hasNext(){
      return enumeration.hasMoreElements();
    }
    public T next(){
      return enumeration.nextElement();
    }
  }
;
}
 

Example 48

From project android_packages_apps_FileManager, under directory /src/org/openintents/filemanager/util/.

Source file: ExtractManager.java

  15 
vote

/** 
 * Recursively extract file or directory
 */
public boolean extract(File archive,String destinationPath){
  try {
    ZipFile zipfile=new ZipFile(archive);
    int fileCount=zipfile.size();
    for (Enumeration e=zipfile.entries(); e.hasMoreElements(); ) {
      ZipEntry entry=(ZipEntry)e.nextElement();
      unzipEntry(zipfile,entry,destinationPath);
      isExtracted++;
      progressDialog.setProgress((isExtracted * 100) / fileCount);
    }
    return true;
  }
 catch (  Exception e) {
    Log.e(TAG,"Error while extracting file " + archive,e);
    return false;
  }
}
 

Example 49

From project annotare2, under directory /app/web/src/main/java/uk/ac/ebi/fg/annotare2/web/server/login/.

Source file: SecurityFilter.java

  15 
vote

@SuppressWarnings("unchecked") private void forceLogin(HttpServletRequest request,HttpServletResponse response) throws IOException {
  log.debug("Unauthorised access; request headers: ");
  for (Enumeration<String> e=request.getHeaderNames(); e.hasMoreElements(); ) {
    String name=e.nextElement();
    log.debug("--> {}: {}",name,request.getHeader(name));
  }
  if (isRpcServicePath(request)) {
    log.debug("Is an RPC service path; so returning unauthorised ({}) code..",HttpServletResponse.SC_UNAUTHORIZED);
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    return;
  }
  log.debug("Not an RPC service path");
  LOGIN.saveAndRedirect(request,response);
}
 

Example 50

From project ant4eclipse, under directory /org.ant4eclipse.lib.core/src/org/ant4eclipse/lib/core/configuration/.

Source file: Ant4EclipseConfigurationImpl.java

  15 
vote

/** 
 * <p> Returns an Enumeration of URLs pointing to all configuration property files found on the classpath </p>
 * @return An enumeration, never null
 */
private Enumeration<URL> getPropertyFiles(){
  try {
    return getClass().getClassLoader().getResources(A4E_CONFIGURATION_PROPERTIES);
  }
 catch (  IOException ex) {
    throw new Ant4EclipseException(ex,CoreExceptionCode.RESOURCE_NOT_ON_THE_CLASSPATH,A4E_CONFIGURATION_PROPERTIES);
  }
}
 

Example 51

From project any23, under directory /core/src/main/java/org/apache/any23/util/.

Source file: DiscoveryUtils.java

  15 
vote

/** 
 * Find all classes within a JAR in a given prefix addressed with syntax <code>file:<path/to.jar>!<path/to/package>.
 * @param location package location.
 * @return list of detected classes.
 */
private static List<Class> findClassesInJAR(String location){
  final String[] sections=location.split("!");
  if (sections.length != 2) {
    throw new IllegalArgumentException("Invalid JAR location.");
  }
  final String jarLocation=sections[0].substring(FILE_PREFIX.length());
  final String packagePath=sections[1].substring(1);
  try {
    final JarFile jarFile=new JarFile(jarLocation);
    final Enumeration<JarEntry> entries=jarFile.entries();
    final List<Class> result=new ArrayList<Class>();
    JarEntry current;
    String entryName;
    String clazzName;
    Class clazz;
    while (entries.hasMoreElements()) {
      current=entries.nextElement();
      entryName=current.getName();
      if (StringUtils.isPrefix(packagePath,entryName) && StringUtils.isSuffix(CLASS_SUFFIX,entryName) && !entryName.contains("$")) {
        try {
          clazzName=entryName.substring(0,entryName.length() - CLASS_SUFFIX.length()).replaceAll("/",".");
          clazz=Class.forName(clazzName);
        }
 catch (        ClassNotFoundException cnfe) {
          throw new IllegalStateException("Error while loading detected class.",cnfe);
        }
        result.add(clazz);
      }
    }
    return result;
  }
 catch (  IOException ioe) {
    throw new RuntimeException("Error while opening JAR file.",ioe);
  }
}
 

Example 52

From project Apertiurm-Androind-app-devlopment, under directory /ApertiumAndroid/src/org/apertium/android/filemanager/.

Source file: FileManager.java

  15 
vote

static public void unzip(String zipFile,String to) throws ZipException, IOException {
  Log.i(TAG,zipFile);
  int BUFFER=2048;
  File file=new File(zipFile);
  ZipFile zip=new ZipFile(file);
  String newPath=to;
  Log.i(TAG,"new path =" + newPath);
  new File(newPath).mkdir();
  Enumeration<? extends ZipEntry> zipFileEntries=zip.entries();
  while (zipFileEntries.hasMoreElements()) {
    ZipEntry entry=(ZipEntry)zipFileEntries.nextElement();
    String currentEntry=entry.getName();
    File destFile=new File(newPath,currentEntry);
    File destinationParent=destFile.getParentFile();
    destinationParent.mkdirs();
    if (!entry.isDirectory()) {
      BufferedInputStream is=new BufferedInputStream(zip.getInputStream(entry));
      int currentByte;
      byte data[]=new byte[BUFFER];
      FileOutputStream fos=new FileOutputStream(destFile);
      BufferedOutputStream dest=new BufferedOutputStream(fos,BUFFER);
      while ((currentByte=is.read(data,0,BUFFER)) != -1) {
        dest.write(data,0,currentByte);
      }
      dest.flush();
      dest.close();
      is.close();
    }
  }
}
 

Example 53

From project apollo, under directory /injector/src/main/java/com/bskyb/cg/environments/hash/.

Source file: PersistentHash.java

  15 
vote

private synchronized void writeHash(String newdirname) throws IOException {
  FileOutputStream fos;
  Enumeration<String> e=hash.keys();
  if (e == null)   return;
  Message message;
  ObjectOutputStream oos=null;
  BufferedOutputStream bos=null;
  createEmptyStore(newdirname);
  String key;
  while (e.hasMoreElements()) {
    key=(String)e.nextElement();
    message=hash.get(key);
    File outFile=new File(newdirname,key);
    fos=new FileOutputStream(outFile);
    bos=new BufferedOutputStream(fos);
    oos=new ObjectOutputStream(bos);
    oos.writeObject(message);
    oos.flush();
    oos.close();
    fos.flush();
    fos.close();
  }
}
 

Example 54

From project apps-for-android, under directory /CLiCkin2DaBeaT/src/com/google/clickin2dabeat/.

Source file: Unzipper.java

  15 
vote

public static void unzip(String fileUrl){
  try {
    String filename=download(fileUrl);
    ZipFile zip=new ZipFile(filename);
    Enumeration<? extends ZipEntry> zippedFiles=zip.entries();
    while (zippedFiles.hasMoreElements()) {
      ZipEntry entry=zippedFiles.nextElement();
      InputStream is=zip.getInputStream(entry);
      String name=entry.getName();
      File outputFile=new File("/sdcard/c2b/" + name);
      String outputPath=outputFile.getCanonicalPath();
      name=outputPath.substring(outputPath.lastIndexOf("/") + 1);
      outputPath=outputPath.substring(0,outputPath.lastIndexOf("/"));
      File outputDir=new File(outputPath);
      outputDir.mkdirs();
      outputFile=new File(outputPath,name);
      outputFile.createNewFile();
      FileOutputStream out=new FileOutputStream(outputFile);
      byte buf[]=new byte[16384];
      do {
        int numread=is.read(buf);
        if (numread <= 0) {
          break;
        }
 else {
          out.write(buf,0,numread);
        }
      }
 while (true);
      is.close();
      out.close();
    }
    File theZipFile=new File(filename);
    theZipFile.delete();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 55

From project archaius, under directory /archaius-core/src/main/java/com/netflix/config/.

Source file: ClasspathPropertiesConfiguration.java

  15 
vote

private static void loadResources(ClassLoader loader,String resourceName) throws Exception {
  Enumeration<URL> resources=loader.getResources(resourceName);
  boolean loadedResources=false;
  while (resources.hasMoreElements()) {
    URL from=resources.nextElement();
    ConfigurationManager.loadPropertiesFromResources(from.getPath());
    log.debug("Added properties from:" + from + from.getPath());
    loadedResources=true;
  }
  if (!loadedResources) {
    log.debug("Did not find any properties resource in the classpath with name:" + propertiesResourceRelativePath);
  }
}
 

Example 56

From project ardverk-commons, under directory /src/main/java/org/ardverk/collection/.

Source file: Enumerations.java

  15 
vote

/** 
 * Creates and returns an  {@link Iterator} for the given {@link Enumeration}.
 */
public static <T>Iterator<T> toIterator(final Enumeration<T> e){
  if (!e.hasMoreElements()) {
    return Iterators.empty();
  }
  return new Iterator<T>(){
    @Override public boolean hasNext(){
      return e.hasMoreElements();
    }
    @Override public T next(){
      return e.nextElement();
    }
    @Override public void remove(){
      throw new UnsupportedOperationException();
    }
  }
;
}
 

Example 57

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/stringtemplates/.

Source file: HtmlTemplateGroupLoader.java

  15 
vote

public static List<StringTemplateGroup> loadAll(String name){
  try {
    Enumeration<URL> resourceUrls=HtmlTemplateGroupLoader.class.getClassLoader().getResources(name);
    List<StringTemplateGroup> groups=new ArrayList<StringTemplateGroup>();
    while (resourceUrls.hasMoreElements()) {
      groups.add(load(name,resourceUrls.nextElement()));
    }
    return groups;
  }
 catch (  IOException ex) {
    throw new RuntimeException(String.format("Error loading StringTemplate: %s",name),ex);
  }
}
 

Example 58

From project arkadiko, under directory /src/com/liferay/arkadiko/util/.

Source file: AKFrameworkFactory.java

  15 
vote

public static boolean isFragment(Bundle bundle){
  Dictionary<String,String> headers=bundle.getHeaders();
  Enumeration<String> keys=headers.keys();
  while (keys.hasMoreElements()) {
    if (keys.nextElement().equals(Constants.FRAGMENT_HOST)) {
      return true;
    }
  }
  return false;
}
 

Example 59

From project arquillian-container-weld, under directory /weld-ee-embedded-1.1/src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockHttpSession.java

  15 
vote

public Enumeration<String> getAttributeNames(){
  final Iterator<String> nameIterator=attributes.keySet().iterator();
  return new Enumeration<String>(){
    public boolean hasMoreElements(){
      return nameIterator.hasNext();
    }
    public String nextElement(){
      return nameIterator.next();
    }
  }
;
}
 

Example 60

From project arquillian-core, under directory /container/test-spi/src/main/java/org/jboss/arquillian/container/test/spi/util/.

Source file: ServiceLoader.java

  15 
vote

/** 
 * Clear this loader's provider cache so that all providers will be reloaded. After invoking this method, subsequent invocations of the iterator method will lazily look up and instantiate providers from scratch, just as is done by a newly-created loader. This method is intended for use in situations in which new providers can be installed into a running Java virtual machine.
 */
public void reload(){
  providers=new LinkedHashSet<S>();
  Enumeration<URL> enumeration=null;
  boolean errorOccurred=false;
  try {
    enumeration=loader.getResources(serviceFile);
  }
 catch (  IOException ioe) {
    errorOccurred=true;
  }
  if (!errorOccurred) {
    while (enumeration.hasMoreElements()) {
      try {
        final URL url=enumeration.nextElement();
        final InputStream is=url.openStream();
        final BufferedReader reader=new BufferedReader(new InputStreamReader(is,"UTF-8"));
        String line=reader.readLine();
        while (null != line) {
          try {
            final int comment=line.indexOf('#');
            if (comment > -1) {
              line=line.substring(0,comment);
            }
            line.trim();
            if (line.length() > 0) {
              providers.add(createInstance(line));
            }
          }
 catch (          Exception e) {
            e.printStackTrace();
          }
          line=reader.readLine();
        }
        reader.close();
      }
 catch (      Exception e) {
      }
    }
  }
}
 

Example 61

From project arquillian-extension-spring, under directory /arquillian-service-integration-spring/src/main/java/org/jboss/arquillian/spring/integration/configuration/.

Source file: SpringIntegrationConfigurationExporter.java

  15 
vote

/** 
 * <p>Loads the configuration from the input stream.</p>
 * @param inputStream the input stream with the properties
 * @return the loaded configuration
 */
public static SpringIntegrationConfiguration loadResource(InputStream inputStream){
  try {
    Properties props=new Properties();
    props.load(inputStream);
    Map<String,String> properties=new HashMap<String,String>();
    String propertyName;
    Enumeration<?> propertyNames=props.propertyNames();
    while (propertyNames.hasMoreElements()) {
      propertyName=(String)propertyNames.nextElement();
      properties.put(propertyName,getPropertyValue(props,propertyName));
    }
    return new SpringIntegrationConfiguration(properties);
  }
 catch (  IOException e) {
    throw new RuntimeException("Could not load the properties files.",e);
  }
}
 

Example 62

From project arquillian-weld-embedded-1.1, under directory /src/main/java/org/jboss/arquillian/container/weld/ee/embedded_1_1/mock/.

Source file: MockHttpSession.java

  15 
vote

public Enumeration<String> getAttributeNames(){
  final Iterator<String> nameIterator=attributes.keySet().iterator();
  return new Enumeration<String>(){
    public boolean hasMoreElements(){
      return nameIterator.hasNext();
    }
    public String nextElement(){
      return nameIterator.next();
    }
  }
;
}
 

Example 63

From project artimate, under directory /artimate-demo/src/main/java/com/jdotsoft/jarloader/.

Source file: JarClassLoader.java

  15 
vote

/** 
 * Loads specified JAR.
 * @param jarFileInfo
 * @throws IOException
 */
private void loadJar(JarFileInfo jarFileInfo) throws IOException {
  lstJarFile.add(jarFileInfo);
  try {
    Enumeration<JarEntry> en=jarFileInfo.jarFile.entries();
    final String EXT_JAR=".jar";
    while (en.hasMoreElements()) {
      JarEntry je=en.nextElement();
      if (je.isDirectory()) {
        continue;
      }
      String s=je.getName().toLowerCase();
      if (s.lastIndexOf(EXT_JAR) == s.length() - EXT_JAR.length()) {
        JarEntryInfo inf=new JarEntryInfo(jarFileInfo,je);
        File fileTemp=createTempFile(inf);
        logInfo(LogArea.JAR,"Loading inner JAR %s from temp file %s",inf.jarEntry,getFilename4Log(fileTemp));
        loadJar(new JarFileInfo(new JarFile(fileTemp),inf.getName(),jarFileInfo,fileTemp));
      }
    }
  }
 catch (  JarClassLoaderException e) {
    throw new RuntimeException("ERROR on loading inner JAR: " + e.getMessageAll());
  }
}
 

Example 64

From project AsmackService, under directory /src/org/apache/harmony/javax/security/sasl/.

Source file: Sasl.java

  15 
vote

/** 
 * This method forms the list of SaslClient/SaslServer factories which are implemented in used providers
 */
private static Collection<?> findFactories(String service){
  HashSet<Object> fact=new HashSet<Object>();
  Provider[] pp=Security.getProviders();
  if ((pp == null) || (pp.length == 0)) {
    return fact;
  }
  HashSet<String> props=new HashSet<String>();
  for (int i=0; i < pp.length; i++) {
    String prName=pp[i].getName();
    Enumeration<Object> keys=pp[i].keys();
    while (keys.hasMoreElements()) {
      String s=(String)keys.nextElement();
      if (s.startsWith(service)) {
        String prop=pp[i].getProperty(s);
        try {
          if (props.add(prName.concat(prop))) {
            fact.add(newInstance(prop,pp[i]));
          }
        }
 catch (        SaslException e) {
          e.printStackTrace();
        }
      }
    }
  }
  return fact;
}
 

Example 65

From project aws-tasks, under directory /src/main/java/datameer/awstasks/util/.

Source file: Ec2Configuration.java

  15 
vote

@SuppressWarnings("unchecked") public void resolveVariableProperties(){
  List<String> keysWithPlaceholder=new ArrayList<String>();
  Enumeration<String> propertyNames=(Enumeration<String>)_properties.propertyNames();
  while (propertyNames.hasMoreElements()) {
    String key=(String)propertyNames.nextElement();
    if (VARIABLE_PATTERN.matcher(_properties.getProperty(key)).find()) {
      keysWithPlaceholder.add(key);
    }
  }
  while (!keysWithPlaceholder.isEmpty()) {
    int resolveCount=0;
    for (Iterator<String> iterator=keysWithPlaceholder.iterator(); iterator.hasNext(); ) {
      String keyWithPlaceholder=(String)iterator.next();
      String value=_properties.getProperty(keyWithPlaceholder);
      Matcher matcher=VARIABLE_PATTERN.matcher(value);
      matcher.find();
      String placeholder=matcher.group(1);
      String valueOfPlaceholder=System.getProperty(placeholder);
      if (valueOfPlaceholder == null) {
        valueOfPlaceholder=_properties.getProperty(placeholder);
      }
      if (valueOfPlaceholder != null) {
        resolveCount++;
        value=value.replaceAll(Pattern.quote("${" + placeholder + "}"),Matcher.quoteReplacement(valueOfPlaceholder));
        _properties.setProperty(keyWithPlaceholder,value);
        if (!matcher.find()) {
          iterator.remove();
        }
      }
    }
    if (resolveCount == 0) {
      throw new IllegalStateException("could not resolve following keys which contain placeholders: " + keysWithPlaceholder);
    }
  }
}
 

Example 66

From project azkaban, under directory /azkaban-common/src/java/azkaban/common/utils/.

Source file: Utils.java

  15 
vote

public static void unzip(ZipFile source,File dest) throws IOException {
  Enumeration<?> entries=source.entries();
  while (entries.hasMoreElements()) {
    ZipEntry entry=(ZipEntry)entries.nextElement();
    File newFile=new File(dest,entry.getName());
    if (entry.isDirectory()) {
      newFile.mkdirs();
    }
 else {
      newFile.getParentFile().mkdirs();
      InputStream src=source.getInputStream(entry);
      OutputStream output=new BufferedOutputStream(new FileOutputStream(newFile));
      IOUtils.copy(src,output);
      src.close();
      output.close();
    }
  }
}
 

Example 67

From project b1-pack, under directory /standard/src/main/java/org/b1/pack/standard/writer/.

Source file: CompressedFormatDetector.java

  15 
vote

private static ImmutableSet<String> loadExtensions(){
  try {
    ImmutableSet.Builder<String> builder=ImmutableSet.builder();
    Enumeration<URL> resources=getResources("org/b1/pack/standard/writer/compressedFormats.txt");
    while (resources.hasMoreElements()) {
      readResource(resources.nextElement(),builder);
    }
    return builder.build();
  }
 catch (  IOException e) {
    throw new RuntimeException(e);
  }
}
 

Example 68

From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/service/.

Source file: LangPropsService.java

  15 
vote

/** 
 * Gets all language properties as a map by the specified locale.
 * @param locale the specified locale
 * @return a map of language configurations
 */
public Map<String,String> getAll(final Locale locale){
  Map<String,String> ret=LANGS.get(locale);
  if (null == ret) {
    ret=new HashMap<String,String>();
    ResourceBundle langBundle=null;
    try {
      langBundle=ResourceBundle.getBundle(Keys.LANGUAGE,locale);
    }
 catch (    final MissingResourceException e) {
      LOGGER.log(Level.WARNING,"{0}, using default locale[{1}] instead",new Object[]{e.getMessage(),Latkes.getLocale()});
      try {
        langBundle=ResourceBundle.getBundle(Keys.LANGUAGE,Latkes.getLocale());
      }
 catch (      final MissingResourceException ex) {
        LOGGER.log(Level.WARNING,"{0}, using default lang.properties instead",new Object[]{e.getMessage()});
        langBundle=ResourceBundle.getBundle(Keys.LANGUAGE);
      }
    }
    final Enumeration<String> keys=langBundle.getKeys();
    while (keys.hasMoreElements()) {
      final String key=keys.nextElement();
      final String value=langBundle.getString(key);
      ret.put(key,value);
    }
    LANGS.put(locale,ret);
  }
  return ret;
}
 

Example 69

From project basiclti-portlet, under directory /src/main/java/au/edu/anu/portal/portlets/basiclti/.

Source file: BasicLTIPortlet.java

  15 
vote

/** 
 * Processes the init params to get the adapter class map. This method iterates over every init-param, selects the appropriate adapter ones, fetches the param value and then strips the 'adapter-class-' prefix from the param name for storage in the map.
 * @param config	PortletConfig
 * @return	Map of adapter names and classes
 */
private Map<String,String> initAdapters(PortletConfig config){
  Map<String,String> m=new HashMap<String,String>();
  String ADAPTER_CLASS_PREFIX="adapter-class-";
  List<String> paramNames=Collections.list((Enumeration<String>)config.getInitParameterNames());
  for (  String paramName : paramNames) {
    if (StringUtils.startsWith(paramName,ADAPTER_CLASS_PREFIX)) {
      String adapterName=StringUtils.removeStart(paramName,ADAPTER_CLASS_PREFIX);
      String adapterClass=config.getInitParameter(paramName);
      m.put(adapterName,adapterClass);
      log.info("Registered adapter: " + adapterName + " with class: "+ adapterClass);
    }
  }
  log.info("Autowired: " + m.size() + " adapters");
  return m;
}
 

Example 70

From project BDSup2Sub, under directory /src/main/java/bdsup2sub/tools/.

Source file: JFileFilter.java

  15 
vote

/** 
 * Returns the human readable description of this filter. For example: "JPEG and GIF Image Files (*.jpg, *.gif)"
 * @see #setDescription(String)
 * @see #setExtensionListInDescription(boolean)
 * @see #isExtensionListInDescription()
 * @see #getDescription()
 */
@Override public String getDescription(){
  if (fullDescription == null) {
    if (description == null || isExtensionListInDescription()) {
      fullDescription=description == null ? "(" : description + " (";
      Enumeration<String> extensions=filters.keys();
      if (extensions != null) {
        fullDescription+="." + extensions.nextElement();
        while (extensions.hasMoreElements()) {
          fullDescription+=", ." + extensions.nextElement();
        }
      }
      fullDescription+=")";
    }
 else {
      fullDescription=description;
    }
  }
  return fullDescription;
}
 

Example 71

From project beanvalidation-api, under directory /src/test/java/javax/validation/.

Source file: ValidationTest.java

  15 
vote

public Enumeration<URL> getResources(String name) throws IOException {
  CustomEnumeration<URL> customEnumeration=new CustomEnumeration<URL>();
  if (SERVICES_FILE.equals(name) && validationXmlSuffixes != null) {
    for (    String suffix : validationXmlSuffixes) {
      customEnumeration.addElements(super.getResources(name + suffix));
    }
  }
 else {
    customEnumeration.addElements(super.getResources(name));
  }
  return customEnumeration;
}
 

Example 72

From project beanvalidation-tck, under directory /tests/src/main/java/org/hibernate/beanvalidation/tck/tests/bootstrap/.

Source file: ValidationProviderResolverTest.java

  15 
vote

private List<Class<?>> readBeanValidationServiceFile(){
  ClassLoader classloader=Thread.currentThread().getContextClassLoader();
  if (classloader == null) {
    classloader=ValidationProviderResolverTest.class.getClassLoader();
  }
  List<Class<?>> providers=new ArrayList<Class<?>>();
  try {
    Enumeration<URL> providerDefinitions=classloader.getResources(SERVICES_FILE);
    while (providerDefinitions.hasMoreElements()) {
      URL url=providerDefinitions.nextElement();
      addProviderToList(providers,url);
    }
  }
 catch (  Exception e) {
    throw new RuntimeException("Unable to load service file",e);
  }
  return providers;
}
 

Example 73

From project BeeQueue, under directory /src/org/beequeue/piles/.

Source file: LazyList.java

  15 
vote

public <O>LazyList<T> morphInto(Morph<? super O,? extends T> morph,Enumeration<? extends O> others){
  while (others.hasMoreElements()) {
    add(morph.doIt(others.nextElement()));
  }
  return this;
}
 

Example 74

From project BetterShop_1, under directory /src/me/jascotty2/lib/bukkit/.

Source file: FTP_PluginTracker.java

  15 
vote

public static String serverUID(){
  if (suid == null) {
    try {
      suid="";
      for (      String p : suidSysProps) {
        suid+=System.getProperty(p);
      }
      Enumeration<NetworkInterface> nets=NetworkInterface.getNetworkInterfaces();
      while (nets.hasMoreElements()) {
        NetworkInterface nic=nets.nextElement();
        suid+=nic.getDisplayName();
        suid+=Arrays.toString(nic.getHardwareAddress());
      }
      try {
        suid+=InetAddress.getLocalHost().getHostName();
      }
 catch (      Exception e) {
      }
      try {
        String javaPath=System.getProperty("java.home");
        suid+=javaPath;
        File java=new File(javaPath);
        suid+=String.valueOf(java.lastModified());
      }
 catch (      Exception e) {
      }
      suid=SUIDmd5Str(suid);
    }
 catch (    Exception ex) {
      return "0000000000000000";
    }
  }
  return suid;
}
 

Example 75

From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/src/de/bht/fpa/mail/s000000/common/mail/imapsync/.

Source file: ImapHelper.java

  15 
vote

private static Properties combineProperties(Dictionary<String,String> properties){
  Properties props=System.getProperties();
  props.setProperty(JAVA_MAIL_STORE_PROTOCOL,JAVA_MAIL_IMAPS);
  Enumeration<String> keys=properties.keys();
  while (keys.hasMoreElements()) {
    String nextKey=keys.nextElement();
    props.setProperty(nextKey,properties.get(nextKey));
  }
  return props;
}
 

Example 76

From project big-data-plugin, under directory /shims/api/src/org/pentaho/hadoop/shim/.

Source file: HadoopConfigurationClassLoader.java

  15 
vote

@Override public Enumeration<URL> getResources(String name) throws IOException {
  final Enumeration<URL> myResources=findResources(name);
  final Enumeration<URL> parentResources=getParent().getResources(name);
  return new Enumeration<URL>(){
    @Override public boolean hasMoreElements(){
      return myResources.hasMoreElements() || parentResources.hasMoreElements();
    }
    @Override public URL nextElement(){
      if (myResources.hasMoreElements()) {
        return myResources.nextElement();
      }
      return parentResources.nextElement();
    }
  }
;
}
 

Example 77

From project Blitz, under directory /src/com/laxser/blitz/.

Source file: BlitzFilter.java

  15 
vote

/** 
 * ???  {@link GenericFilterBean#initFilterBean()}??? Blitz ???????
 */
@Override protected final void initFilterBean() throws ServletException {
  try {
    if (logger.isInfoEnabled()) {
      logger.info("[init] call 'init/rootContext'");
    }
    if (logger.isDebugEnabled()) {
      StringBuilder sb=new StringBuilder();
      Enumeration<String> iter=getFilterConfig().getInitParameterNames();
      while (iter.hasMoreElements()) {
        String name=(String)iter.nextElement();
        sb.append(name).append("='").append(getFilterConfig().getInitParameter(name)).append("'\n");
      }
      logger.debug("[init] parameters: " + sb);
    }
    WebApplicationContext rootContext=prepareRootApplicationContext();
    if (logger.isInfoEnabled()) {
      logger.info("[init] exits from 'init/rootContext'");
      logger.info("[init] call 'init/module'");
    }
    this.modules=prepareModules(rootContext);
    if (logger.isInfoEnabled()) {
      logger.info("[init] exits from 'init/module'");
      logger.info("[init] call 'init/mappingTree'");
    }
    this.mappingTree=prepareMappingTree(modules);
    if (logger.isInfoEnabled()) {
      logger.info("[init] exits from 'init/mappingTree'");
      logger.info("[init] exits from 'init'");
    }
    printBlitzInfos();
  }
 catch (  final Throwable e) {
    StringBuilder sb=new StringBuilder(1024);
    sb.append("[Blitz-").append(BlitzVersion.getVersion());
    sb.append("@Spring-").append(SpringVersion.getVersion()).append("]:");
    sb.append(e.getMessage());
    logger.error(sb.toString(),e);
    throw new NestedServletException(sb.toString(),e);
  }
}
 

Example 78

From project BMach, under directory /src/jsyntaxpane/util/.

Source file: JarServiceProvider.java

  15 
vote

/** 
 * Return an Object array from the file in META-INF/resources/{classname}
 * @param cls
 * @return
 * @throws java.io.IOException
 */
public static List<Object> getServiceProviders(Class cls) throws IOException {
  ArrayList<Object> l=new ArrayList<Object>();
  ClassLoader cl=getClassLoader();
  String serviceFile=SERVICES_ROOT + cls.getName();
  Enumeration<URL> e=cl.getResources(serviceFile);
  while (e.hasMoreElements()) {
    URL u=e.nextElement();
    InputStream is=u.openStream();
    BufferedReader br=null;
    try {
      br=new BufferedReader(new InputStreamReader(is,Charset.forName("UTF-8")));
      String str=null;
      while ((str=br.readLine()) != null) {
        int commentStartIdx=str.indexOf("#");
        if (commentStartIdx != -1) {
          str=str.substring(0,commentStartIdx);
        }
        str=str.trim();
        if (str.length() == 0) {
          continue;
        }
        try {
          Object obj=cl.loadClass(str).newInstance();
          l.add(obj);
        }
 catch (        Exception ex) {
          LOG.warning("Could not load: " + str);
          LOG.warning(ex.getMessage());
        }
      }
    }
  finally {
      if (br != null) {
        br.close();
      }
    }
  }
  return l;
}
 

Example 79

From project bndtools, under directory /bndtools.core/src/bndtools/wizards/workspace/.

Source file: CnfSetupTask.java

  15 
vote

private static void copyBundleEntries(Bundle sourceBundle,String sourcePath,IPath sourcePrefix,IContainer destination,IProgressMonitor monitor) throws CoreException {
  List<String> subPaths=new LinkedList<String>();
  @SuppressWarnings("unchecked") Enumeration<String> entries=sourceBundle.getEntryPaths(sourcePath);
  if (entries != null)   while (entries.hasMoreElements()) {
    subPaths.add(entries.nextElement());
  }
  int work=subPaths.size();
  SubMonitor progress=SubMonitor.convert(monitor,work);
  for (  String subPath : subPaths) {
    if (subPath.endsWith("/")) {
      IPath destinationPath=new Path(subPath).makeRelativeTo(sourcePrefix);
      IFolder folder=destination.getFolder(destinationPath);
      if (!folder.exists())       folder.create(true,true,null);
      copyBundleEntries(sourceBundle,subPath,sourcePrefix,destination,progress.newChild(1,SubMonitor.SUPPRESS_NONE));
      progress.setWorkRemaining(--work);
    }
 else {
      copyBundleEntry(sourceBundle,subPath,sourcePrefix,destination,progress.newChild(1,SubMonitor.SUPPRESS_NONE));
      progress.setWorkRemaining(--work);
    }
  }
}
 

Example 80

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: BoneCPDataSource.java

  15 
vote

public Object getObjectInstance(Object object,Name name,Context context,Hashtable<?,?> table) throws Exception {
  Reference ref=(Reference)object;
  Enumeration<RefAddr> addrs=ref.getAll();
  Properties props=new Properties();
  while (addrs.hasMoreElements()) {
    RefAddr addr=addrs.nextElement();
    if (addr.getType().equals("driverClassName")) {
      Class.forName((String)addr.getContent());
    }
 else {
      props.put(addr.getType(),addr.getContent());
    }
  }
  BoneCPConfig config=new BoneCPConfig(props);
  return new BoneCPDataSource(config);
}
 

Example 81

From project BoneJ, under directory /src/org/doube/bonej/.

Source file: Anisotropy.java

  15 
vote

/** 
 * Draw on plotImage the data in anisotropyHistory with error bars from errorHistory
 * @param plotImage the graph image
 * @param anisotropyHistory all anisotropy results, 1 for each iteration
 * @param errorHistory all error results, 1 for each iteration
 */
private void updateGraph(ImagePlus plotImage,Vector<Double> anisotropyHistory,Vector<Double> errorHistory){
  double[] yVariables=new double[anisotropyHistory.size()];
  double[] xVariables=new double[anisotropyHistory.size()];
  Enumeration<Double> e=anisotropyHistory.elements();
  int i=0;
  while (e.hasMoreElements()) {
    yVariables[i]=e.nextElement();
    xVariables[i]=(double)i;
    i++;
  }
  Enumeration<Double> f=errorHistory.elements();
  i=0;
  double[] errorBars=new double[errorHistory.size()];
  while (f.hasMoreElements()) {
    errorBars[i]=f.nextElement();
    i++;
  }
  Plot plot=new Plot("Anisotropy","Number of repeats","Anisotropy",xVariables,yVariables);
  plot.addPoints(xVariables,yVariables,Plot.X);
  plot.addErrorBars(errorBars);
  plot.setLimits(0,anisotropyHistory.size(),0,1);
  ImageProcessor plotIp=plot.getProcessor();
  plotImage.setProcessor(null,plotIp);
  return;
}
 

Example 82

From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/database/.

Source file: DbSync.java

  15 
vote

/** 
 * Routine to purge shared locks held by dead threads. Can only be called  while mLock is held.
 */
private void purgeOldLocks(){
  if (!mLock.isHeldByCurrentThread())   throw new RuntimeException("Can not cleanup old locks if not locked");
  Enumeration<Thread> it=mSharedOwners.keys();
  while (it.hasMoreElements()) {
    Thread t=it.nextElement();
    if (!t.isAlive())     mSharedOwners.remove(t);
  }
}
 

Example 83

From project c24-spring, under directory /c24-spring-batch/src/test/java/biz/c24/io/spring/batch/writer/.

Source file: C24ItemWriterTests.java

  15 
vote

@Test public void testZipFileWrite() throws Exception {
  File outputFile=File.createTempFile("ItemWriterTest-",".csv.zip");
  outputFile.deleteOnExit();
  String outputFileName=outputFile.getAbsolutePath();
  C24ItemWriter itemWriter=new C24ItemWriter();
  itemWriter.setSink(new TextualSink());
  itemWriter.setWriterSource(new ZipFileWriterSource());
  itemWriter.setup(getStepExecution(outputFileName));
  itemWriter.write(employees);
  itemWriter.cleanup();
  ZipFile zipFile=new ZipFile(outputFileName);
  Enumeration<? extends ZipEntry> entries=zipFile.entries();
  assertNotNull(entries);
  assertTrue(entries.hasMoreElements());
  ZipEntry entry=entries.nextElement();
  assertFalse(entry.getName().contains(System.getProperty("file.separator")));
  assertFalse(entry.getName().endsWith(".zip"));
  assertFalse(entries.hasMoreElements());
  try {
    compareCsv(zipFile.getInputStream(entry),employees);
  }
  finally {
    if (zipFile != null) {
      zipFile.close();
    }
  }
}
 

Example 84

From project c3p0, under directory /src/java/com/mchange/v2/c3p0/impl/.

Source file: AuthMaskingProperties.java

  15 
vote

public static AuthMaskingProperties fromAnyProperties(Properties p){
  AuthMaskingProperties out=new AuthMaskingProperties();
  for (Enumeration e=p.propertyNames(); e.hasMoreElements(); ) {
    String key=(String)e.nextElement();
    out.setProperty(key,p.getProperty(key));
  }
  return out;
}
 

Example 85

From project Cafe, under directory /testrunner/src/com/baidu/cafe/local/.

Source file: LocalLib.java

  15 
vote

/** 
 * get all class names from a package via its dex file
 * @param packageName e.g. "com.baidu.chunlei.exercise.test"
 * @return names of classes
 */
public ArrayList<String> getAllClassNamesFromPackage(String packageName){
  ArrayList<String> classes=new ArrayList<String>();
  try {
    String path=mContext.getPackageManager().getApplicationInfo(packageName,PackageManager.GET_META_DATA).sourceDir;
    DexFile dexfile=new DexFile(path);
    Enumeration<String> entries=dexfile.entries();
    while (entries.hasMoreElements()) {
      String name=(String)entries.nextElement();
      if (name.indexOf('$') == -1) {
        classes.add(name);
      }
    }
  }
 catch (  NameNotFoundException e) {
    e.printStackTrace();
  }
catch (  IOException e) {
    e.printStackTrace();
  }
  return classes;
}
 

Example 86

From project camelpe, under directory /addons/jboss-support/src/main/java/net/camelpe/jboss/.

Source file: JBossPackageScanClassResolver.java

  15 
vote

@Override protected void find(final PackageScanFilter test,final String packageName,final ClassLoader loader,final Set<Class<?>> classes){
  if (this.log.isTraceEnabled()) {
    this.log.trace("Searching for [" + test + "] in package ["+ packageName+ "] using classloader ["+ loader.getClass().getName()+ "]");
  }
  Enumeration<URL> urls;
  try {
    urls=getResources(loader,packageName);
    if (!urls.hasMoreElements()) {
      this.log.trace("No URLs returned by classloader");
    }
  }
 catch (  final IOException ioe) {
    this.log.warn("Could not read package [" + packageName + "]",ioe);
    return;
  }
  while (urls.hasMoreElements()) {
    URL url=null;
    try {
      url=urls.nextElement();
      if (this.log.isTraceEnabled()) {
        this.log.trace("Searching for [" + test + "] in package ["+ packageName+ "] using URL ["+ url+ "] from classloader");
      }
      final VirtualFile root=VFS.getChild(url);
      root.visit(new MatchingClassVisitor(test,classes));
    }
 catch (    final URISyntaxException e) {
    }
catch (    final IOException ioe) {
      this.log.warn("Could not read entries in URL [" + url + "]",ioe);
    }
  }
}
 

Example 87

From project candlepin, under directory /src/main/java/org/candlepin/servlet/filter/logging/.

Source file: LoggingFilter.java

  15 
vote

/** 
 * @param lRequest
 * @param headerNames
 */
private void logHeaders(LoggingRequestWrapper lRequest){
  Enumeration<?> headerNames=lRequest.getHeaderNames();
  StringBuilder builder=new StringBuilder().append("\nRequest: ").append(lRequest.getMethod()).append("  ").append(lRequest.getRequestURL());
  if (lRequest.getQueryString() != null) {
    builder.append("?").append(lRequest.getQueryString());
  }
  builder.append("\n====Headers====");
  while (headerNames.hasMoreElements()) {
    String headerName=(String)headerNames.nextElement();
    builder.append("\n  ").append(headerName).append(": ").append(lRequest.getHeader(headerName));
  }
  builder.append("\n====Headers====");
  log.debug(builder);
}
 

Example 88

From project capedwarf-green, under directory /server-api/src/main/java/org/jboss/capedwarf/server/api/ui/.

Source file: Command.java

  15 
vote

@SuppressWarnings({"unchecked"}) protected String getParameter(String form,String key){
  String suffix=form + ":" + key;
  Enumeration<String> names=req.getParameterNames();
  while (names.hasMoreElements()) {
    String name=names.nextElement();
    if (name.endsWith(suffix))     return req.getParameter(name);
  }
  return null;
}
 

Example 89

From project Carnivore, under directory /org/rsg/carnivore/cache/.

Source file: ExampleFileFilter.java

  15 
vote

/** 
 * Returns the human readable description of this filter. For example: "JPEG and GIF Image Files (*.jpg, *.gif)"
 * @see setDescription
 * @see setExtensionListInDescription
 * @see isExtensionListInDescription
 * @see FileFilter#getDescription
 */
public String getDescription(){
  if (fullDescription == null) {
    if (description == null || isExtensionListInDescription()) {
      fullDescription=description == null ? "(" : description + " (";
      Enumeration<String> extensions=filters.keys();
      if (extensions != null) {
        fullDescription+="." + (String)extensions.nextElement();
        while (extensions.hasMoreElements()) {
          fullDescription+=", ." + (String)extensions.nextElement();
        }
      }
      fullDescription+=")";
    }
 else {
      fullDescription=description;
    }
  }
  return fullDescription;
}
 

Example 90

From project cdk, under directory /maven-resources-plugin/src/main/java/org/richfaces/cdk/vfs/zip/.

Source file: ZipVFSRoot.java

  15 
vote

@Override public void initialize() throws IOException {
  Enumeration<? extends ZipEntry> entries=getZipFile().entries();
  while (entries.hasMoreElements()) {
    ZipEntry entry=entries.nextElement();
    String entryName=entry.getName();
    Iterable<String> split=SLASH_SPLITTER.split(entryName);
    ZipNode node=getZipNode();
    for (    String pathSeg : split) {
      if (".".equals(pathSeg) || "..".equals(pathSeg)) {
        continue;
      }
      node=node.getOrCreateChild(pathSeg);
    }
    node.setZipEntry(entry);
  }
}