下面列出了java.util.Enumeration#nextElement ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Specifies whether this animated memory image should always be
* updated by sending the complete buffer of pixels whenever
* there is a change.
* This flag is ignored if the animation flag is not turned on
* through the setAnimated() method.
* <p>This method should be called immediately after the
* MemoryImageSource is constructed and before an image is
* created with it to ensure that all ImageConsumers will
* receive the correct pixel delivery hints.
* @param fullbuffers <code>true</code> if the complete pixel
* buffer should always
* be sent
* @see #setAnimated
*/
public synchronized void setFullBufferUpdates(boolean fullbuffers) {
if (this.fullbuffers == fullbuffers) {
return;
}
this.fullbuffers = fullbuffers;
if (animating) {
Enumeration enum_ = theConsumers.elements();
while (enum_.hasMoreElements()) {
ImageConsumer ic = (ImageConsumer) enum_.nextElement();
ic.setHints(fullbuffers
? (ImageConsumer.TOPDOWNLEFTRIGHT |
ImageConsumer.COMPLETESCANLINES)
: ImageConsumer.RANDOMPIXELORDER);
}
}
}
/**
* Get the Principal given the authenticated Subject. Currently the first subject that is not of type {@code Group} is
* considered or the single subject inside the CallerPrincipal group.
*
* @param subject
* @return the authenticated subject
*/
protected static Principal getPrincipal(Subject subject) {
Principal principal = null;
Principal callerPrincipal = null;
if (subject != null) {
Set<Principal> principals = subject.getPrincipals();
if (principals != null && !principals.isEmpty()) {
for (Principal p : principals) {
if (!(p instanceof Group) && principal == null) {
principal = p;
}
if (p instanceof Group) {
Group g = Group.class.cast(p);
if (g.getName().equals(SecurityConstants.CALLER_PRINCIPAL_GROUP) && callerPrincipal == null) {
Enumeration<? extends Principal> e = g.members();
if (e.hasMoreElements())
callerPrincipal = e.nextElement();
}
}
}
}
}
return callerPrincipal == null ? principal : callerPrincipal;
}
/**
* First finds path to marker file url, otherwise throws {@link JarValidationException}.
* Then scans jar classes according to list indicated in marker files.
* Additional logic is added to close {@link URL} after {@link ConfigFactory#parseURL(URL)}.
* This is extremely important for Windows users where system doesn't allow to delete file if it's being used.
*
* @param classLoader unique class loader for jar
* @param path local path to jar
* @param urls urls associated with the jar (ex: binary and source)
* @return scan result of packages, classes, annotations found in jar
*/
private ScanResult scan(ClassLoader classLoader, Path path, URL[] urls) throws IOException {
Enumeration<URL> markerFileEnumeration = classLoader.getResources(
ConfigConstants.DRILL_JAR_MARKER_FILE_RESOURCE_PATHNAME);
while (markerFileEnumeration.hasMoreElements()) {
URL markerFile = markerFileEnumeration.nextElement();
if (markerFile.getPath().contains(path.toUri().getPath())) {
URLConnection markerFileConnection = null;
try {
markerFileConnection = markerFile.openConnection();
DrillConfig drillConfig = DrillConfig.create(ConfigFactory.parseURL(markerFile));
return RunTimeScan.dynamicPackageScan(drillConfig, Sets.newHashSet(urls));
} finally {
if (markerFileConnection instanceof JarURLConnection) {
((JarURLConnection) markerFile.openConnection()).getJarFile().close();
}
}
}
}
throw new JarValidationException(String.format("Marker file %s is missing in %s",
ConfigConstants.DRILL_JAR_MARKER_FILE_RESOURCE_PATHNAME, path.getName()));
}
public Enumeration<URL> getResources(String name) throws TGResourceException {
try {
Vector<URL> vector = new Vector<URL>();
if( this.getFilePaths() != null){
for( int i = 0; i < this.getFilePaths().length ; i ++ ){
File file = new File(this.getFilePaths()[i] + File.separator + name);
if( TGFileUtils.isExistentAndReadable( file ) ){
vector.addElement( file.getAbsoluteFile().toURI().toURL() );
}
}
}
Enumeration<URL> resources = this.classLoader.getResources(name);
while( resources.hasMoreElements() ){
URL url = (URL)resources.nextElement();
if( !vector.contains(url) ){
vector.addElement( url );
}
}
return vector.elements();
} catch (Throwable e) {
throw new TGResourceException(e);
}
}
/**
* Retrieves all intialization parameters for this servlet and stores them in a java.util.Properties object.
*
* @param config javax.servlet.ServletConfig
* @return java.util.Properties
*/
protected Properties initParamsToProperties(final ServletConfig config) {
final Properties properties = new Properties();
//@Tomcat
// Set some defaults
properties.setProperty("openejb.loader", "tomcat");
// Load in each init-param as a property
final Enumeration<?> enumeration = config.getInitParameterNames();
System.out.println("OpenEJB Loader init-params:");
if (!enumeration.hasMoreElements()) {
System.out.println("\tThere are no initialization parameters.");
}
while (enumeration.hasMoreElements()) {
final String name = (String) enumeration.nextElement();
final String value = config.getInitParameter(name);
properties.put(name, value);
System.out.println("\tparam-name: " + name + ", param-value: " + value);
}
return properties;
}
/**
* Iterates through the parameters in this holder, recording them in the supplied parameter processor.
**/
public void recordParameters( ParameterProcessor processor ) throws IOException {
Enumeration e = _parameters.keys();
while (e.hasMoreElements()) {
String name = (String) e.nextElement();
Object[] values = (Object[]) _parameters.get( name );
for (int i = 0; i < values.length; i++) {
if (values[i] instanceof String || values[i] == null) {
processor.addParameter( name, (String) values[i], _characterSet );
} else if (values[i] instanceof UploadFileSpec) {
processor.addFile( name, (UploadFileSpec) values[i] );
}
}
}
}
private static List<PomInfo> getAllJarPomInfo() throws IOException {
List<PomInfo> pomInfos = Lists.newArrayList();
String metaPath = "META-INF";
Enumeration<URL> urls = Analyzer.class.getClassLoader().getResources(metaPath);
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
if (url != null && "jar".equals(url.getProtocol())) {
String urlStr = url.toString();
logger.debug("url-str: " + urlStr);
String location = urlStr.substring(urlStr.indexOf('f'), urlStr.lastIndexOf('!'));
logger.debug("location: " + location);
readPomInfo(location, pomInfos);
}
}
return pomInfos;
}
/**
* Change the duration value of each note in the Part.
*/
public void setDuration(double val) {
Enumeration enum1 = getPhraseList().elements();
while(enum1.hasMoreElements()){
Phrase phrase = (Phrase) enum1.nextElement();
phrase.setDuration(val);
}
}
/**
* Checks whether the scheme can take command line options.
*
* @return index 0 is true if the classifier can take options
*/
protected boolean[] canTakeOptions() {
boolean[] result = new boolean[2];
print("options...");
if (m_Classifier instanceof OptionHandler) {
println("yes");
if (m_Debug) {
println("\n=== Full report ===");
Enumeration enu = ((OptionHandler)m_Classifier).listOptions();
while (enu.hasMoreElements()) {
Option option = (Option) enu.nextElement();
print(option.synopsis() + "\n"
+ option.description() + "\n");
}
println("\n");
}
result[0] = true;
}
else {
println("no");
result[0] = false;
}
return result;
}
/**
* Sets the http request data.
*
* @param request the request
* @param requestContainer the request container
*/
private void setHttpRequestData(HttpServletRequest request, RequestContainer requestContainer) {
requestContainer.setAttribute(HTTP_REQUEST_AUTH_TYPE, request.getAuthType());
requestContainer.setAttribute(HTTP_REQUEST_CHARACTER_ENCODING, request.getCharacterEncoding());
requestContainer.setAttribute(HTTP_REQUEST_CONTENT_LENGTH, String.valueOf(request.getContentLength()));
requestContainer.setAttribute(HTTP_REQUEST_CONTENT_TYPE, request.getContentType());
requestContainer.setAttribute(HTTP_REQUEST_CONTEXT_PATH, request.getContextPath());
requestContainer.setAttribute(HTTP_REQUEST_METHOD, request.getMethod());
requestContainer.setAttribute(HTTP_REQUEST_PATH_INFO, request.getPathInfo());
requestContainer.setAttribute(HTTP_REQUEST_PATH_TRANSLATED, request.getPathTranslated());
requestContainer.setAttribute(HTTP_REQUEST_PROTOCOL, request.getProtocol());
requestContainer.setAttribute(HTTP_REQUEST_QUERY_STRING, request.getQueryString());
requestContainer.setAttribute(HTTP_REQUEST_REMOTE_ADDR, request.getRemoteAddr());
requestContainer.setAttribute(HTTP_REQUEST_REMOTE_HOST, request.getRemoteHost());
requestContainer.setAttribute(HTTP_REQUEST_REMOTE_USER, request.getRemoteUser());
requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID, request.getRequestedSessionId());
requestContainer.setAttribute(HTTP_REQUEST_REQUEST_URI, request.getRequestURI());
requestContainer.setAttribute(HTTP_REQUEST_SCHEME, request.getScheme());
requestContainer.setAttribute(HTTP_REQUEST_SERVER_NAME, request.getServerName());
requestContainer.setAttribute(HTTP_REQUEST_SERVER_PORT, String.valueOf(request.getServerPort()));
requestContainer.setAttribute(HTTP_REQUEST_SERVLET_PATH, request.getServletPath());
if (request.getUserPrincipal() != null)
requestContainer.setAttribute(HTTP_REQUEST_USER_PRINCIPAL, request.getUserPrincipal());
requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_COOKIE, String.valueOf(request.isRequestedSessionIdFromCookie()));
requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_FROM_URL, String.valueOf(request.isRequestedSessionIdFromURL()));
requestContainer.setAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID_VALID, String.valueOf(request.isRequestedSessionIdValid()));
requestContainer.setAttribute(HTTP_REQUEST_SECURE, String.valueOf(request.isSecure()));
Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = (String) headerNames.nextElement();
String headerValue = request.getHeader(headerName);
requestContainer.setAttribute(headerName, headerValue);
} // while (headerNames.hasMoreElements())
requestContainer.setAttribute(HTTP_SESSION_ID, request.getSession().getId());
requestContainer.setAttribute(Constants.HTTP_IS_XML_REQUEST, "FALSE");
}
/**
* Delete all the generated source files made during the execution
* of this environment (those that have been registered with the
* "addGeneratedFile" method).
*/
public void deleteGeneratedFiles() {
synchronized(generatedFiles) {
Enumeration<File> enumeration = generatedFiles.elements();
while (enumeration.hasMoreElements()) {
File file = enumeration.nextElement();
file.delete();
}
generatedFiles.removeAllElements();
}
}
public static List<String> getAllIPV4() {
if (IPV4_LIST == null) {
IPV4_LIST = new LinkedList<>();
try {
Enumeration<NetworkInterface> interfs = NetworkInterface.getNetworkInterfaces();
while (interfs.hasMoreElements()) {
NetworkInterface networkInterface = interfs.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress address = inetAddresses.nextElement();
if (address instanceof Inet4Address) {
String addressStr = address.getHostAddress();
if ("127.0.0.1".equals(addressStr)) {
continue;
} else if ("localhost".equals(addressStr)) {
continue;
}
IPV4_LIST.add(addressStr);
}
}
}
} catch (SocketException e) {
}
}
return IPV4_LIST;
}
@Test
public void testConflictRegionServerHostnameConfigurationsAbortServer() throws Exception {
Enumeration<NetworkInterface> netInterfaceList = NetworkInterface.getNetworkInterfaces();
while (netInterfaceList.hasMoreElements()) {
NetworkInterface ni = netInterfaceList.nextElement();
Enumeration<InetAddress> addrList = ni.getInetAddresses();
// iterate through host addresses and use each as hostname
while (addrList.hasMoreElements()) {
InetAddress addr = addrList.nextElement();
if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isMulticastAddress()) {
continue;
}
String hostName = addr.getHostName();
LOG.info("Found " + hostName + " on " + ni);
TEST_UTIL.getConfiguration().set(DNS.MASTER_HOSTNAME_KEY, hostName);
// "hbase.regionserver.hostname" and "hbase.regionserver.hostname.disable.master.reversedns"
// are mutually exclusive. Exception should be thrown if both are used.
TEST_UTIL.getConfiguration().set(DNS.RS_HOSTNAME_KEY, hostName);
TEST_UTIL.getConfiguration().setBoolean(HRegionServer.RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY, true);
try {
StartMiniClusterOption option = StartMiniClusterOption.builder()
.numMasters(NUM_MASTERS).numRegionServers(NUM_RS).numDataNodes(NUM_RS).build();
TEST_UTIL.startMiniCluster(option);
} catch (Exception e) {
Throwable t1 = e.getCause();
Throwable t2 = t1.getCause();
assertTrue(t1.getMessage()+" - "+t2.getMessage(), t2.getMessage().contains(
HRegionServer.RS_HOSTNAME_DISABLE_MASTER_REVERSEDNS_KEY + " and " +
DNS.RS_HOSTNAME_KEY + " are mutually exclusive"));
return;
} finally {
TEST_UTIL.shutdownMiniCluster();
}
assertTrue("Failed to validate against conflict hostname configurations", false);
}
}
}
@Test
public void testRegionServerHostname() throws Exception {
Enumeration<NetworkInterface> netInterfaceList = NetworkInterface.getNetworkInterfaces();
while (netInterfaceList.hasMoreElements()) {
NetworkInterface ni = netInterfaceList.nextElement();
Enumeration<InetAddress> addrList = ni.getInetAddresses();
// iterate through host addresses and use each as hostname
while (addrList.hasMoreElements()) {
InetAddress addr = addrList.nextElement();
if (addr.isLoopbackAddress() || addr.isLinkLocalAddress() || addr.isMulticastAddress() ||
!addr.isSiteLocalAddress()) {
continue;
}
String hostName = addr.getHostName();
LOG.info("Found " + hostName + " on " + ni + ", addr=" + addr);
TEST_UTIL.getConfiguration().set(DNS.MASTER_HOSTNAME_KEY, hostName);
TEST_UTIL.getConfiguration().set(DNS.RS_HOSTNAME_KEY, hostName);
StartMiniClusterOption option = StartMiniClusterOption.builder()
.numMasters(NUM_MASTERS).numRegionServers(NUM_RS).numDataNodes(NUM_RS).build();
TEST_UTIL.startMiniCluster(option);
try {
ZKWatcher zkw = TEST_UTIL.getZooKeeperWatcher();
List<String> servers = ZKUtil.listChildrenNoWatch(zkw, zkw.getZNodePaths().rsZNode);
// there would be NUM_RS+1 children - one for the master
assertTrue(servers.size() ==
NUM_RS + (LoadBalancer.isTablesOnMaster(TEST_UTIL.getConfiguration())? 1: 0));
for (String server : servers) {
assertTrue("From zookeeper: " + server + " hostname: " + hostName,
server.startsWith(hostName.toLowerCase(Locale.ROOT)+","));
}
zkw.close();
} finally {
TEST_UTIL.shutdownMiniCluster();
}
}
}
}
public final void traverse() throws IOException {
try (ZipFile zipFile = new ZipFile(file.toFile())) {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
visit(zipFile, entry);
}
} catch (IllegalArgumentException e) { // help debugging a "MALFORMED" error
throw new IllegalArgumentException("zipfile traverse exception on file:" + file, e);
}
}
public String getResetPassword( HttpServletRequest request )
{
// Invalidate a previous session
HttpSession session = request.getSession( false );
if ( session != null )
{
session.removeAttribute( SESSION_ATTRIBUTE_USER );
}
Map<String, Object> model = new HashMap<>( );
Locale locale = AdminUserService.getLocale( request );
Enumeration<String> enumParams = request.getParameterNames( );
ReferenceList listParams = new ReferenceList( );
String strParamName;
while ( enumParams.hasMoreElements( ) )
{
strParamName = enumParams.nextElement( );
String strParamValue = request.getParameter( strParamName );
listParams.addItem( strParamName, strParamValue );
}
model.put( MARK_PARAM_VERSION, AppInfo.getVersion( ) );
model.put( MARK_PARAMS_LIST, listParams );
model.put( MARK_SITE_NAME, PortalService.getSiteName( ) );
HtmlTemplate template = AppTemplateService.getTemplate( TEMPLATE_ADMIN_RESET_PASSWORD, locale, model );
return template.getHtml( );
}
public static void main(String[] args) throws Exception {
// Try to register a JCE provider from property sun.security.mscapi.testprovider in the first slot
// otherwise register a dummy provider which would provoke the issue of bug 8139436
boolean providerPrepended = false;
String testprovider = System.getProperty("sun.security.mscapi.testprovider");
if (testprovider != null && !testprovider.isEmpty()) {
try {
System.out.println("Trying to prepend external JCE provider " + testprovider);
Class<?> providerclass = Class.forName(testprovider);
Object provider = providerclass.newInstance();
Security.insertProviderAt((Provider)provider, 1);
} catch (Exception e) {
System.out.println("Could not load JCE provider " + testprovider +". Exception is:");
e.printStackTrace(System.out);
}
providerPrepended = true;
System.out.println("Sucessfully prepended JCE provider " + testprovider);
}
if (!providerPrepended) {
System.out.println("Trying to prepend dummy JCE provider");
Security.insertProviderAt(new TestProvider(), 1);
System.out.println("Sucessfully prepended dummy JCE provider");
}
// load Windows-ROOT KeyStore
KeyStore keyStore = KeyStore.getInstance("Windows-ROOT", "SunMSCAPI");
keyStore.load(null, null);
// iterate KeyStore
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
System.out.print("Reading certificate for alias: " + alias + "...");
keyStore.getCertificate(alias);
System.out.println(" done.");
}
}
/**
* Return the maximum size of the table. The maximum height is the
* row heighttimes the number of rows.
* The maximum width is the sum of the maximum widths of each column.
*/
public Dimension getMaximumSize(JComponent c) {
long width = 0;
Enumeration<TableColumn> enumeration = table.getColumnModel().getColumns();
while (enumeration.hasMoreElements()) {
TableColumn aColumn = enumeration.nextElement();
width = width + aColumn.getMaxWidth();
}
return createTableSize(width);
}
private PermissionCollection mergePermissions() {
if (staticPermissions)
return permissions;
PermissionCollection perms =
java.security.AccessController.doPrivileged
(new java.security.PrivilegedAction<PermissionCollection>() {
public PermissionCollection run() {
Policy p = Policy.getPolicyNoCheck();
return p.getPermissions(ProtectionDomain.this);
}
});
Permissions mergedPerms = new Permissions();
int swag = 32;
int vcap = 8;
Enumeration<Permission> e;
List<Permission> pdVector = new ArrayList<>(vcap);
List<Permission> plVector = new ArrayList<>(swag);
//
// Build a vector of domain permissions for subsequent merge
if (permissions != null) {
synchronized (permissions) {
e = permissions.elements();
while (e.hasMoreElements()) {
pdVector.add(e.nextElement());
}
}
}
//
// Build a vector of Policy permissions for subsequent merge
if (perms != null) {
synchronized (perms) {
e = perms.elements();
while (e.hasMoreElements()) {
plVector.add(e.nextElement());
vcap++;
}
}
}
if (perms != null && permissions != null) {
//
// Weed out the duplicates from the policy. Unless a refresh
// has occurred since the pd was consed this should result in
// an empty vector.
synchronized (permissions) {
e = permissions.elements(); // domain vs policy
while (e.hasMoreElements()) {
Permission pdp = e.nextElement();
Class<?> pdpClass = pdp.getClass();
String pdpActions = pdp.getActions();
String pdpName = pdp.getName();
for (int i = 0; i < plVector.size(); i++) {
Permission pp = plVector.get(i);
if (pdpClass.isInstance(pp)) {
// The equals() method on some permissions
// have some side effects so this manual
// comparison is sufficient.
if (pdpName.equals(pp.getName()) &&
pdpActions.equals(pp.getActions())) {
plVector.remove(i);
break;
}
}
}
}
}
}
if (perms !=null) {
// the order of adding to merged perms and permissions
// needs to preserve the bugfix 4301064
for (int i = plVector.size()-1; i >= 0; i--) {
mergedPerms.add(plVector.get(i));
}
}
if (permissions != null) {
for (int i = pdVector.size()-1; i >= 0; i--) {
mergedPerms.add(pdVector.get(i));
}
}
return mergedPerms;
}
/**
* Reads properties that inherit from three locations. Properties
* are first defined in the system resource location (i.e. in the
* CLASSPATH). These default properties must exist. Properties optionally
* defined in the user properties location (WekaPackageManager.PROPERTIES_DIR)
* override default settings. Properties defined in the current directory (optional)
* override all these settings.
*
* @param resourceName the location of the resource that should be
* loaded. e.g.: "weka/core/Utils.props". (The use of hardcoded
* forward slashes here is OK - see
* jdk1.1/docs/guide/misc/resources.html) This routine will also
* look for the file (in this case) "Utils.props" in the users home
* directory and the current directory.
* @return the Properties
* @exception Exception if no default properties are defined, or if
* an error occurs reading the properties files.
*/
public static Properties readProperties(String resourceName)
throws Exception {
Properties defaultProps = new Properties();
try {
// Apparently hardcoded slashes are OK here
// jdk1.1/docs/guide/misc/resources.html
Utils utils = new Utils();
Enumeration<URL> urls = utils.getClass().getClassLoader().getResources(resourceName);
boolean first = true;
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
if (first) {
defaultProps.load(url.openStream());
first = false;
}
else {
Properties props = new Properties(defaultProps);
props.load(url.openStream());
defaultProps = props;
}
}
} catch (Exception ex) {
System.err.println("Warning, unable to load properties file(s) from "
+"system resource (Utils.java): " + resourceName);
}
// Hardcoded slash is OK here
// eg: see jdk1.1/docs/guide/misc/resources.html
int slInd = resourceName.lastIndexOf('/');
if (slInd != -1) {
resourceName = resourceName.substring(slInd + 1);
}
/* Allow a properties file in the WekaPackageManager.PROPERTIES_DIR to override
Properties userProps = new Properties(defaultProps);
if (!WekaPackageManager.PROPERTIES_DIR.exists()) {
WekaPackageManager.PROPERTIES_DIR.mkdir();
}
File propFile = new File(WekaPackageManager.PROPERTIES_DIR.toString()
+ File.separator
+ resourceName);
if (propFile.exists()) {
try {
userProps.load(new FileInputStream(propFile));
} catch (Exception ex) {
throw new Exception("Problem reading user properties: " + propFile);
}
}
// Allow a properties file in the current directory to override
Properties localProps = new Properties(userProps);
propFile = new File(resourceName);
if (propFile.exists()) {
try {
localProps.load(new FileInputStream(propFile));
} catch (Exception ex) {
throw new Exception("Problem reading local properties: " + propFile);
}
}
*/
return defaultProps;
}