Java Code Examples for java.util.Enumeration

The following are top voted examples for showing how to use java.util.Enumeration. 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: jentrata-msh   File: Zip.java View source code Vote up 17 votes
/**
 * Extracts a set of files compressed in a zip file to a directory.
 * 
 * @param fromFile the zip file.
 * @param dir the directory to which the files to be extracted. Current user
 *            directory will be chosen if it is null.
 * @throws UtilitiesException if there is any error in the extraction.
 */
public static void extract(File fromFile, File dir)
        throws UtilitiesException {
    try {
        if (dir == null) {
            dir = new File(System.getProperty("user.dir"));
        }
        else if (!dir.exists()) {
            dir.mkdirs();
        }

        if (!dir.isDirectory()) {
            throw new UtilitiesException("Invalid output directory: " + dir);
        }

        ZipFile zipFile = new ZipFile(fromFile);
        ArrayList fileEntries = new ArrayList();

        Enumeration zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();
            if (zipEntry.isDirectory()) {
                new File(dir, zipEntry.getName()).mkdirs();
            }
            else {
                fileEntries.add(zipEntry);
            }
        }

        Iterator allFiles = fileEntries.iterator();
        while (allFiles.hasNext()) {
            ZipEntry fileEntry = (ZipEntry) allFiles.next();
            File destFile = new File(dir, fileEntry.getName());
            destFile.setLastModified(fileEntry.getTime());
            destFile.getParentFile().mkdirs();
            FileOutputStream outs = new FileOutputStream(destFile);
            InputStream ins = zipFile.getInputStream(fileEntry);
            IOHandler.pipe(ins, outs);
            ins.close();
            outs.close();
        }

        zipFile.close();
    }
    catch (Exception e) {
        throw new UtilitiesException("Unable to extract zip file: "
                + fromFile, e);
    }
}
 
Example 2
Project: apache-james-mime4j-groundhog   File: StringArrayMapTest.java View source code Vote up 7 votes
private void assertEquals(String[] pArray, Enumeration<String> pEnum) {
    final List<String> list = new ArrayList<String>();
    while (pEnum.hasMoreElements()) {
        list.add(pEnum.nextElement());
    }
    Collections.sort(list, Collator.getInstance(Locale.US));
    assertEquals(pArray.length, list.size());
    for (int i = 0;  i < pArray.length;  i++) {
        assertEquals(pArray[i], list.get(i));
    }
}
 
Example 3
Project: JAME   File: Scene.java View source code Vote up 7 votes
@Override
public String toString() {
	final StringBuffer s = new StringBuffer("scene: " + name + "\r\n");
	Solid solid = null;
	final Enumeration<Solid> solids = getSolids();
	while (solids.hasMoreElements()) {
		solid = solids.nextElement();
		s.append(solid.toString());
	}
	return (s.toString());
}
 
Example 4
Project: jentrata-msh   File: PropertiesPageletAdaptor.java View source code Vote up 6 votes
protected PropertyTree getPropertiesForDisplayAndUpdate(HttpServletRequest request,
		PropertyTree dom) {

	PropertySheet props = getProperties();

	String action = request.getParameter(REQ_PARAM_ACTION);
	if (request.getMethod().equalsIgnoreCase("post")) {
		if ("update".equalsIgnoreCase(action)) {
			Enumeration names = request.getParameterNames();
			while (names.hasMoreElements()) {
				String name = names.nextElement().toString();
				if (name.startsWith(REQ_PARAM_PROPERTY)) {
					props.setProperty(name.substring(REQ_PARAM_PROPERTY
							.length()), request.getParameter(name));
				}
			}
			try {
				if (props instanceof PersistentComponent) {
					if (((PersistentComponent) props).getURL() != null) {
						props.store();
					}
				}
				request.setAttribute(ATTR_MESSAGE,
						"Properties updated successfully");
			} catch (Exception e) {
				request.setAttribute(ATTR_MESSAGE,
						"Unable to update properties: " + e);
			}
		}
	}

	String[] keys = (String[]) ArrayUtilities.toArray(
			props.propertyNames(), new String[] {});
	Arrays.sort(keys);

	for (int i = 0, pi = 0; i < keys.length; i++) {
		String value = props.getProperty(keys[i], "");
		if (value.indexOf('\n') == -1 && value.indexOf('\r') == -1) {
			pi++;
			dom.setProperty("property[" + pi + "]/name", keys[i]);
			dom.setProperty("property[" + pi + "]/value", props
					.getProperty(keys[i]));
		}
	}

	return dom;

}
 
Example 5
Project: jentrata-msh   File: DispositionNotification.java View source code Vote up 6 votes
private void saveReportValues() throws AS2MessageException {
    try {
        Enumeration reportEn = reportValues.getAllHeaderLines();
        StringBuffer reportData = new StringBuffer();

        while (reportEn.hasMoreElements()) {
            reportData.append((String) reportEn.nextElement()).append("\r\n");
        }

        reportData.append("\r\n");

        String reportText = MimeUtility.encodeText(reportData.toString(),
                "us-ascii", "7bit");
        reportPart.setContent(reportText,
                AS2Header.CONTENT_TYPE_MESSAGE_DISPOSITION_NOTIFICATION);
        reportPart.setHeader("Content-Type",
                AS2Header.CONTENT_TYPE_MESSAGE_DISPOSITION_NOTIFICATION);
        reportPart.setHeader("Content-Transfer-Encoding", "7bit");
    }
    catch (Exception e) {
        throw new AS2MessageException("Error in saving report values", e);
    }
}
 
Example 6
Project: iot-server-appliances   File: HTTPCommunicationHandlerImpl.java View source code Vote up 6 votes
/**
 * This is an overloaded method that fetches the public IPv4 address of the given network
 * interface
 *
 * @param networkInterfaceName the network-interface of whose IPv4 address is to be retrieved
 * @return the IP Address iof the device
 * @throws AgentCoreOperationException if any errors occur whilst trying to get details of the
 *                                     given network interface
 */
private String getDeviceIP(String networkInterfaceName) throws
                                                        AgentCoreOperationException {
	String ipAddress = null;
	try {
		Enumeration<InetAddress> interfaceIPAddresses = NetworkInterface.getByName(
				networkInterfaceName).getInetAddresses();
		for (; interfaceIPAddresses.hasMoreElements(); ) {
			InetAddress ip = interfaceIPAddresses.nextElement();
			ipAddress = ip.getHostAddress();
			if (log.isDebugEnabled()) {
				log.debug(AgentConstants.LOG_APPENDER + "IP Address: " + ipAddress);
			}

			if (CommunicationUtils.validateIPv4(ipAddress)) {
				return ipAddress;
			}
		}
	} catch (SocketException | NullPointerException exception) {
		String errorMsg =
				"Error encountered whilst trying to get IP Addresses of the network interface: " +
						networkInterfaceName +
						".\nPlease check whether the name of the network interface used is correct";
		log.error(AgentConstants.LOG_APPENDER + errorMsg);
		throw new AgentCoreOperationException(errorMsg, exception);
	}

	return ipAddress;
}
 
Example 7
Project: jentrata-msh   File: HttpDispatcherContext.java View source code Vote up 6 votes
/**
 * Gets the information of all registered Http request listeners.
 * The resulted properties will contain a set of pathInfo-listenerName pairs.
 * 
 * @return the information as properties.
 */
public Properties getRegisteredListenersInfo() {
    Properties info = new Properties();
    Enumeration keys = requestListeners.keys();
    while (keys.hasMoreElements()) {
        Object key = keys.nextElement();
        String value = requestListeners.get(key).getClass().getName();
        info.setProperty(key.toString(), value);
    }
    return info;
}
 
Example 8
Project: JAME   File: JXTANetworkService.java View source code Vote up 6 votes
/**
 * @see net.jxta.discovery.DiscoveryListener#discoveryEvent(net.jxta.discovery.DiscoveryEvent)
 */
public void discoveryEvent(final DiscoveryEvent e) {
	final DiscoveryResponseMsg response = e.getResponse();
	logger.fine("Got a discovery response [" + response.getResponseCount() + " elements] from peer " + e.getSource());
	final Enumeration<Advertisement> advEnum = response.getAdvertisements();
	if (advEnum != null) {
		while (advEnum.hasMoreElements()) {
			final Advertisement adv = advEnum.nextElement();
			if (adv.getAdvType().equals(ModuleSpecAdvertisement.getAdvertisementType())) {
				final ModuleSpecAdvertisement msadv = (ModuleSpecAdvertisement) adv;
				logger.fine("Got a module spec advertisement");
				printAdvertisement(msadv);
				synchronized (controlSessions) {
					synchronized (invalidAdvertisements) {
						if (!pipeadv.getID().toString().equals(msadv.getPipeAdvertisement().getID().toString()) && !controlSessions.containsKey(msadv.getPipeAdvertisement().getID().toString()) && !invalidAdvertisements.contains(msadv.getPipeAdvertisement().getID().toString())) {
							Thread thread = factory.newThread(new DiscoveryRunnable(msadv, this));
							thread.setName("Discovery task for pipe " + msadv.getPipeAdvertisement().getPipeID().toString());
							thread.start();
						}
					}
				}
			}
		}
	}
}
 
Example 9
Project: dlna   File: HttpServer.java View source code Vote up 5 votes
/**
 * Sends given response to the socket.
 */
private void sendResponse( String status, String mime, Properties header, InputStream data )
{
	try
	{
		if ( status == null )
			throw new Error( "sendResponse(): Status can't be null." );

		OutputStream out = mySocket.getOutputStream();
		PrintWriter pw = new PrintWriter( out );
		pw.print("HTTP/1.0 " + status + " \r\n");

		if ( mime != null )
			pw.print("Content-Type: " + mime + "\r\n");

		if ( header == null || header.getProperty( "Date" ) == null )
			pw.print( "Date: " + gmtFrmt.format( new Date()) + "\r\n");

		if ( header != null )
		{
			Enumeration e = header.keys();
			while ( e.hasMoreElements())
			{
				String key = (String)e.nextElement();
				String value = header.getProperty( key );
				pw.print( key + ": " + value + "\r\n");
			}
		}

		pw.print("\r\n");
		pw.flush();

		if ( data != null )
		{
			int pending = data.available();	// This is to support partial sends, see serveFile()
			byte[] buff = new byte[2048];
			while (pending>0)
			{
				int read = data.read( buff, 0, ( (pending>2048) ?  2048 : pending ));
				if (read <= 0)	break;
				out.write( buff, 0, read );
				pending -= read;
			}
		}
		out.flush();
		out.close();
		if ( data != null )
			data.close();
	}
	catch( IOException ioe )
	{
		// Couldn't write? No can do.
		try { mySocket.close(); } catch( Throwable t ) {}
	}
}
 
Example 10
Project: dlna   File: FileHelper.java View source code Vote up 5 votes
public static boolean unZipFile(String fileName, String unZipDir) throws Exception {
	File f = new File(unZipDir);

	if (!f.exists()) {
		f.mkdirs();
	}

	BufferedInputStream is = null;
	ZipEntry entry;
	ZipFile zipfile = new ZipFile(fileName);
	Enumeration<?> enumeration = zipfile.entries();
	byte data[] = new byte[FILE_BUFFER_SIZE];
	log.i("unZipDir: " + unZipDir);

	while (enumeration.hasMoreElements()) {
		entry = (ZipEntry)enumeration.nextElement();

		if (entry.isDirectory()) {
			File f1 = new File(unZipDir + "/" + entry.getName());
			log.i("entry.isDirectory XXX " + f1.getPath());
			if (!f1.exists()) {
				f1.mkdirs();
			}
		} else {
			is = new BufferedInputStream(zipfile.getInputStream(entry));
			int count;
			String name = unZipDir + "/" + entry.getName();
			RandomAccessFile m_randFile = null;
			File file = new File(name);
			if (file.exists()) {
				file.delete();
			}

			file.createNewFile();
			m_randFile = new RandomAccessFile(file, "rw");
			int begin = 0;

			while ((count = is.read(data, 0, FILE_BUFFER_SIZE)) != -1) {
				try {
					m_randFile.seek(begin);
				} catch (Exception ex) {
					log.e("exception, ex: " + ex.toString());
				}

				m_randFile.write(data, 0, count);
				begin = begin + count;
			}
			
			file.delete();
			m_randFile.close();
			is.close();
		}
	}

	return true;
}