List of usage examples for java.util Properties keySet
@Override
public Set<Object> keySet()
From source file:org.apache.ranger.audit.provider.AuditProviderFactory.java
public synchronized void init(Properties props, String appType) { LOG.info("AuditProviderFactory: initializing.."); if (mInitDone) { LOG.warn("AuditProviderFactory.init(): already initialized! Will try to re-initialize"); }//from ww w .j a va 2s. co m mInitDone = true; componentAppType = appType; MiscUtil.setApplicationType(appType); boolean isEnabled = MiscUtil.getBooleanProperty(props, AUDIT_IS_ENABLED_PROP, false); boolean isAuditToDbEnabled = MiscUtil.getBooleanProperty(props, AUDIT_DB_IS_ENABLED_PROP, false); boolean isAuditToHdfsEnabled = MiscUtil.getBooleanProperty(props, AUDIT_HDFS_IS_ENABLED_PROP, false); boolean isAuditToLog4jEnabled = MiscUtil.getBooleanProperty(props, AUDIT_LOG4J_IS_ENABLED_PROP, false); boolean isAuditToKafkaEnabled = MiscUtil.getBooleanProperty(props, AUDIT_KAFKA_IS_ENABLED_PROP, false); boolean isAuditToSolrEnabled = MiscUtil.getBooleanProperty(props, AUDIT_SOLR_IS_ENABLED_PROP, false); List<AuditHandler> providers = new ArrayList<AuditHandler>(); for (Object propNameObj : props.keySet()) { LOG.info("AUDIT PROPERTY: " + propNameObj.toString() + "=" + props.getProperty(propNameObj.toString())); } // Process new audit configurations List<String> destNameList = new ArrayList<String>(); for (Object propNameObj : props.keySet()) { String propName = propNameObj.toString(); if (!propName.startsWith(AUDIT_DEST_BASE)) { continue; } String destName = propName.substring(AUDIT_DEST_BASE.length() + 1); List<String> splits = MiscUtil.toArray(destName, "."); if (splits.size() > 1) { continue; } String value = props.getProperty(propName); if (value.equalsIgnoreCase("enable") || value.equalsIgnoreCase("enabled") || value.equalsIgnoreCase("true")) { destNameList.add(destName); LOG.info("Audit destination " + propName + " is set to " + value); } } for (String destName : destNameList) { String destPropPrefix = AUDIT_DEST_BASE + "." + destName; AuditHandler destProvider = getProviderFromConfig(props, destPropPrefix, destName, null); if (destProvider != null) { destProvider.init(props, destPropPrefix); String queueName = MiscUtil.getStringProperty(props, destPropPrefix + "." + AuditQueue.PROP_QUEUE); if (queueName == null || queueName.isEmpty()) { LOG.info(destPropPrefix + "." + AuditQueue.PROP_QUEUE + " is not set. Setting queue to batch for " + destName); queueName = "batch"; } LOG.info("queue for " + destName + " is " + queueName); if (queueName != null && !queueName.isEmpty() && !queueName.equalsIgnoreCase("none")) { String queuePropPrefix = destPropPrefix + "." + queueName; AuditHandler queueProvider = getProviderFromConfig(props, queuePropPrefix, queueName, destProvider); if (queueProvider != null) { if (queueProvider instanceof AuditQueue) { AuditQueue qProvider = (AuditQueue) queueProvider; qProvider.init(props, queuePropPrefix); providers.add(queueProvider); } else { LOG.fatal("Provider queue doesn't extend AuditQueue. Destination=" + destName + " can't be created. queueName=" + queueName); } } else { LOG.fatal("Queue provider for destination " + destName + " can't be created. queueName=" + queueName); } } else { LOG.info("Audit destination " + destProvider.getName() + " added to provider list"); providers.add(destProvider); } } } if (providers.size() > 0) { LOG.info("Using v3 audit configuration"); AuditHandler consumer = providers.get(0); // Possible pipeline is: // async_queue -> summary_queue -> multidestination -> batch_queue // -> hdfs_destination // -> batch_queue -> solr_destination // -> batch_queue -> kafka_destination // Above, up to multidestination, the providers are same, then it // branches out in parallel. // Set the providers in the reverse order e.g. if (providers.size() > 1) { // If there are more than one destination, then we need multi // destination to process it in parallel LOG.info("MultiDestAuditProvider is used. Destination count=" + providers.size()); MultiDestAuditProvider multiDestProvider = new MultiDestAuditProvider(); multiDestProvider.init(props); multiDestProvider.addAuditProviders(providers); consumer = multiDestProvider; } // Let's see if Summary is enabled, then summarize before sending it // downstream String propPrefix = BaseAuditHandler.PROP_DEFAULT_PREFIX; boolean summaryEnabled = MiscUtil.getBooleanProperty(props, propPrefix + "." + "summary" + "." + "enabled", false); AuditSummaryQueue summaryQueue = null; if (summaryEnabled) { LOG.info("AuditSummaryQueue is enabled"); summaryQueue = new AuditSummaryQueue(consumer); summaryQueue.init(props, propPrefix); consumer = summaryQueue; } else { LOG.info("AuditSummaryQueue is disabled"); } // Create the AsysnQueue AuditAsyncQueue asyncQueue = new AuditAsyncQueue(consumer); propPrefix = BaseAuditHandler.PROP_DEFAULT_PREFIX + "." + "async"; asyncQueue.init(props, propPrefix); asyncQueue.setParentPath(componentAppType); mProvider = asyncQueue; LOG.info("Starting audit queue " + mProvider.getName()); mProvider.start(); } else { LOG.info("No v3 audit configuration found. Trying v2 audit configurations"); if (!isEnabled || !(isAuditToDbEnabled || isAuditToHdfsEnabled || isAuditToKafkaEnabled || isAuditToLog4jEnabled || isAuditToSolrEnabled || providers.size() == 0)) { LOG.info("AuditProviderFactory: Audit not enabled.."); mProvider = getDefaultProvider(); return; } if (isAuditToDbEnabled) { LOG.info("DbAuditProvider is enabled"); DbAuditProvider dbProvider = new DbAuditProvider(); boolean isAuditToDbAsync = MiscUtil.getBooleanProperty(props, DbAuditProvider.AUDIT_DB_IS_ASYNC_PROP, false); if (isAuditToDbAsync) { int maxQueueSize = MiscUtil.getIntProperty(props, DbAuditProvider.AUDIT_DB_MAX_QUEUE_SIZE_PROP, AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT); int maxFlushInterval = MiscUtil.getIntProperty(props, DbAuditProvider.AUDIT_DB_MAX_FLUSH_INTERVAL_PROP, AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT); AsyncAuditProvider asyncProvider = new AsyncAuditProvider("DbAuditProvider", maxQueueSize, maxFlushInterval, dbProvider); providers.add(asyncProvider); } else { providers.add(dbProvider); } } if (isAuditToHdfsEnabled) { LOG.info("HdfsAuditProvider is enabled"); HdfsAuditProvider hdfsProvider = new HdfsAuditProvider(); boolean isAuditToHdfsAsync = MiscUtil.getBooleanProperty(props, HdfsAuditProvider.AUDIT_HDFS_IS_ASYNC_PROP, false); if (isAuditToHdfsAsync) { int maxQueueSize = MiscUtil.getIntProperty(props, HdfsAuditProvider.AUDIT_HDFS_MAX_QUEUE_SIZE_PROP, AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT); int maxFlushInterval = MiscUtil.getIntProperty(props, HdfsAuditProvider.AUDIT_HDFS_MAX_FLUSH_INTERVAL_PROP, AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT); AsyncAuditProvider asyncProvider = new AsyncAuditProvider("HdfsAuditProvider", maxQueueSize, maxFlushInterval, hdfsProvider); providers.add(asyncProvider); } else { providers.add(hdfsProvider); } } if (isAuditToKafkaEnabled) { LOG.info("KafkaAuditProvider is enabled"); KafkaAuditProvider kafkaProvider = new KafkaAuditProvider(); kafkaProvider.init(props); if (kafkaProvider.isAsync()) { AsyncAuditProvider asyncProvider = new AsyncAuditProvider("MyKafkaAuditProvider", 1000, 1000, kafkaProvider); providers.add(asyncProvider); } else { providers.add(kafkaProvider); } } if (isAuditToSolrEnabled) { LOG.info("SolrAuditProvider is enabled"); SolrAuditProvider solrProvider = new SolrAuditProvider(); solrProvider.init(props); if (solrProvider.isAsync()) { AsyncAuditProvider asyncProvider = new AsyncAuditProvider("MySolrAuditProvider", 1000, 1000, solrProvider); providers.add(asyncProvider); } else { providers.add(solrProvider); } } if (isAuditToLog4jEnabled) { Log4jAuditProvider log4jProvider = new Log4jAuditProvider(); boolean isAuditToLog4jAsync = MiscUtil.getBooleanProperty(props, Log4jAuditProvider.AUDIT_LOG4J_IS_ASYNC_PROP, false); if (isAuditToLog4jAsync) { int maxQueueSize = MiscUtil.getIntProperty(props, Log4jAuditProvider.AUDIT_LOG4J_MAX_QUEUE_SIZE_PROP, AUDIT_ASYNC_MAX_QUEUE_SIZE_DEFAULT); int maxFlushInterval = MiscUtil.getIntProperty(props, Log4jAuditProvider.AUDIT_LOG4J_MAX_FLUSH_INTERVAL_PROP, AUDIT_ASYNC_MAX_FLUSH_INTERVAL_DEFAULT); AsyncAuditProvider asyncProvider = new AsyncAuditProvider("Log4jAuditProvider", maxQueueSize, maxFlushInterval, log4jProvider); providers.add(asyncProvider); } else { providers.add(log4jProvider); } } if (providers.size() == 0) { mProvider = getDefaultProvider(); } else if (providers.size() == 1) { mProvider = providers.get(0); } else { MultiDestAuditProvider multiDestProvider = new MultiDestAuditProvider(); multiDestProvider.addAuditProviders(providers); mProvider = multiDestProvider; } mProvider.init(props); mProvider.start(); } installJvmSutdownHook(props); }
From source file:com.jivesoftware.os.upena.uba.service.InstancePath.java
InstanceDescriptor readInstanceDescriptor() throws FileNotFoundException, IOException { Properties properties = new Properties(); properties.load(new FileInputStream(instanceProperties())); Object enabled = properties.get(instancePrefix + "enabled"); if (enabled == null) { enabled = "true"; }//from w w w . j a v a2s . c o m Object datacenter = properties.get(instancePrefix + "datacenter"); Object rack = properties.get(instancePrefix + "rack"); Object publicHost = properties.get(instancePrefix + "publicHost"); InstanceDescriptor id = new InstanceDescriptor( (datacenter == null) ? "unknownDatacenter" : datacenter.toString(), (rack == null) ? "unknownRack" : rack.toString(), (publicHost == null) ? "unknown" : publicHost.toString(), properties.get(instancePrefix + "clusterKey").toString(), properties.get(instancePrefix + "clusterName").toString(), properties.get(instancePrefix + "serviceKey").toString(), properties.get(instancePrefix + "serviceName").toString(), properties.get(instancePrefix + "releaseGroupKey").toString(), properties.get(instancePrefix + "releaseGroupName").toString(), properties.get(instancePrefix + "instanceKey").toString(), Integer.parseInt(properties.get(instancePrefix + "instanceName").toString()), properties.get(instancePrefix + "version").toString(), properties.get(instancePrefix + "repository").toString(), -1, Boolean.parseBoolean(enabled.toString())); for (Object key : properties.keySet()) { String portKey = key.toString(); if (portKey.endsWith("Port")) { if (!portKey.endsWith("routesPort")) { // ignore injected upena String portName = portKey.substring(instancePrefix.length(), portKey.length() - 4); id.ports.put(portName, new InstanceDescriptor.InstanceDescriptorPort( Integer.parseInt(properties.getProperty(key.toString())))); } } } LOG.debug("Read instance descriptor:" + id + " from:" + instanceProperties()); return id; }
From source file:org.apache.archiva.metadata.repository.file.FileMetadataRepository.java
@Override public void removeArtifact(ArtifactMetadata artifactMetadata, String baseVersion) throws MetadataRepositoryException { try {//from w ww . ja v a2 s.c om File directory = new File(getDirectory(artifactMetadata.getRepositoryId()), artifactMetadata.getNamespace() + "/" + artifactMetadata.getProject() + "/" + baseVersion); Properties properties = readOrCreateProperties(directory, PROJECT_VERSION_METADATA_KEY); String id = artifactMetadata.getId(); properties.remove("artifact:updated:" + id); properties.remove("artifact:whenGathered:" + id); properties.remove("artifact:size:" + id); properties.remove("artifact:md5:" + id); properties.remove("artifact:sha1:" + id); properties.remove("artifact:version:" + id); properties.remove("artifact:facetIds:" + id); String prefix = "artifact:facet:" + id + ":"; for (Object key : new ArrayList(properties.keySet())) { String property = (String) key; if (property.startsWith(prefix)) { properties.remove(property); } } writeProperties(properties, directory, PROJECT_VERSION_METADATA_KEY); } catch (IOException e) { throw new MetadataRepositoryException(e.getMessage(), e); } }
From source file:net.jetrix.config.ServerConfig.java
/** * Save the configuration.// ww w .java 2s . c o m */ public void save() throws IOException { // todo make a backup copy of the previous configuration files // save the server.xml file PrintWriter out = null; try { File file = new File(serverConfigURL.toURI()); out = new PrintWriter(file, ENCODING); } catch (URISyntaxException e) { log.log(Level.SEVERE, e.getMessage(), e); } out.println("<?xml version=\"1.0\"?>"); out.println( "<!DOCTYPE tetrinet-server PUBLIC \"-//LFJR//Jetrix TetriNET Server//EN\" \"http://jetrix.sourceforge.net/dtd/tetrinet-server.dtd\">"); out.println(); out.println("<tetrinet-server host=\"" + (host == null ? "[ALL]" : host.getHostAddress()) + "\">"); out.println(); out.println(" <!-- Server name -->"); out.println(" <name>" + getName() + "</name>"); out.println(); out.println(" <!-- Server default language (using an ISO-639 two-letter language code) -->"); out.println(" <language>" + getLocale().getLanguage() + "</language>"); out.println(); out.println(" <!-- How many seconds of inactivity before timeout occurs -->"); out.println(" <timeout>" + getTimeout() + "</timeout>"); out.println(); out.println(" <!-- How many channels should be available on the server -->"); out.println(" <max-channels>" + getMaxChannels() + "</max-channels>"); out.println(); out.println(" <!-- Maximum number of players on the server -->"); out.println(" <max-players>" + getMaxPlayers() + "</max-players>"); out.println(); out.println(" <!-- Maximum number of simultaneous connections allowed from the same IP -->"); out.println(" <max-connections>" + getMaxConnections() + "</max-connections>"); out.println(); out.println(" <!-- Typing /op <thispassword> will give player operator status -->"); out.println(" <op-password>" + getOpPassword() + "</op-password>"); out.println(); out.println(" <!-- Use this password to log on the administration console -->"); out.println(" <admin-password>" + getAdminPassword() + "</admin-password>"); out.println(); out.println(" <!-- Access Log, where requests are logged to -->"); out.println(" <access-log path=\"" + getAccessLogPath() + "\" />"); out.println(); out.println(" <!-- Error Log, where errors are logged to -->"); out.println(" <error-log path=\"" + getErrorLogPath() + "\" />"); out.println(); out.println(" <!-- Path to the channels descriptor file (relative to the current configuration file) -->"); out.println(" <channels path=\"" + getChannelsFile() + "\"/>"); out.println(); out.println(" <!-- Client listeners -->"); out.println(" <listeners>"); for (Listener listener : getListeners()) { String autostart = !listener.isAutoStart() ? " auto-start=\"false\"" : ""; out.println(" <listener class=\"" + listener.getClass().getName() + "\" port=\"" + listener.getPort() + "\"" + autostart + "/>"); } out.println(" </listeners>"); out.println(); out.println(" <!-- Services -->"); out.println(" <services>"); for (Service service : getServices()) { try { // get the parameters Map<String, Object> params = PropertyUtils.describe(service); String autostart = !service.isAutoStart() ? "auto-start=\"false\"" : ""; String classname = "class=\"" + service.getClass().getName() + "\""; if (params.size() <= 4) { out.println(" <service " + classname + " " + autostart + "/>"); } else { out.println(" <service " + classname + " " + autostart + ">"); for (String param : params.keySet()) { PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(service, param); if (!"autoStart".equals(param) && desc.getWriteMethod() != null) { out.println( " <param name=\"" + param + "\" value=\"" + params.get(param) + "\"/>"); } } out.println(" </service>"); } } catch (Exception e) { e.printStackTrace(); } } out.println(" </services>"); out.println(); out.println(" <!-- Server commands -->"); out.println(" <commands>"); Iterator<Command> commands = CommandManager.getInstance().getCommands(AccessLevel.ADMINISTRATOR); while (commands.hasNext()) { try { Command command = commands.next(); String hidden = command.isHidden() ? " hidden=\"true\"" : ""; Command command2 = command.getClass().newInstance(); String level = command2.getAccessLevel() != command.getAccessLevel() ? " access-level=\"" + command.getAccessLevel() + "\"" : ""; out.println(" <command class=\"" + command.getClass().getName() + "\"" + hidden + level + "/>"); } catch (Exception e) { log.log(Level.WARNING, e.getMessage(), e); } } out.println(" </commands>"); out.println(); out.println(" <ban>"); Iterator<Banlist.Entry> entries = Banlist.getInstance().getBanlist(); while (entries.hasNext()) { Banlist.Entry entry = entries.next(); out.println(" <host>" + entry.pattern + "</host>"); } out.println(" </ban>"); out.println(); if (!datasources.isEmpty()) { out.println(" <!-- Database connection parameters -->"); out.println(" <datasources>"); out.println(); for (DataSourceConfig datasource : datasources.values()) { out.println(" <datasource name=\"" + datasource.getName() + "\">"); out.println(" <!-- The class of the JDBC driver used -->"); out.println(" <driver>" + datasource.getDriver() + "</driver>"); out.println(); out.println(" <!-- The URL of the database (jdbc:<type>://<hostname>:<port>/<database>) -->"); out.println(" <url>" + datasource.getUrl() + "</url>"); out.println(); out.println(" <!-- The username connecting to the database -->"); out.println(" <username>" + datasource.getUsername() + "</username>"); out.println(); out.println(" <!-- The password of the user -->"); if (datasource.getPassword() != null) { out.println(" <password>" + datasource.getPassword() + "</password>"); } else { out.println(" <password/>"); } if (datasource.getMinIdle() != DataSourceManager.DEFAULT_MIN_IDLE) { out.println(); out.println(" <!-- The minimum number of idle connections -->"); out.println(" <min-idle>" + datasource.getMinIdle() + "</min-idle>"); } if (datasource.getMaxActive() != DataSourceManager.DEFAULT_MAX_ACTIVE) { out.println(); out.println(" <!-- The maximum number of active connections -->"); out.println(" <max-active>" + datasource.getMaxActive() + "</max-active>"); } out.println(" </datasource>"); out.println(); } out.println(" </datasources>"); out.println(); } if (mailSessionConfig != null) { StringBuilder buffer = new StringBuilder(); buffer.append(" <mailserver host=\"").append(mailSessionConfig.getHostname()).append("\""); buffer.append(" port=\"").append(mailSessionConfig.getPort()).append("\""); if (mailSessionConfig.isAuth()) { buffer.append(" auth=\"true\""); buffer.append(" username=\"").append(mailSessionConfig.getUsername()).append("\""); buffer.append(" password=\"").append(mailSessionConfig.getPassword()).append("\""); } if (mailSessionConfig.isDebug()) { buffer.append(" debug=\"true\""); } buffer.append("/>"); out.println(" <!-- Mail server parameters -->"); out.println(buffer.toString()); out.println(); } if (properties != null && !properties.isEmpty()) { out.println(" <!-- Extended properties -->"); out.println(" <properties>"); for (String key : properties.stringPropertyNames()) { out.println(" <property name=\"" + key + "\" value=\"" + properties.getProperty(key) + "\">"); } out.println(" </properties>"); out.println(); } out.println("</tetrinet-server>"); out.flush(); out.close(); // save the channels.xml file try { File file = new File(channelsConfigURL.toURI()); out = new PrintWriter(file, ENCODING); } catch (URISyntaxException e) { log.log(Level.SEVERE, e.getMessage(), e); } out.println("<?xml version=\"1.0\"?>"); out.println( "<!DOCTYPE tetrinet-channels PUBLIC \"-//LFJR//Jetrix Channels//EN\" \"http://jetrix.sourceforge.net/dtd/tetrinet-channels.dtd\">"); out.println(); out.println("<tetrinet-channels>"); out.println(); out.println(" <!-- Message Of The Day -->"); out.println(" <motd><![CDATA["); out.println(getMessageOfTheDay()); out.println(" ]]></motd>"); out.println(); // filter definitions Map<String, String> aliases = FilterManager.getInstance().getFilterAliases(); out.println(" <!-- Channel filters -->"); out.println(" <filter-definitions>"); for (String alias : aliases.keySet()) { out.println(" <alias name=\"" + alias + "\" class=\"" + aliases.get(alias) + "\"/>"); } out.println(" </filter-definitions>"); out.println(); // global filters out.println(" <!-- Global filters -->"); out.println(" <default-filters>"); for (FilterConfig filter : globalFilters) { saveFilter(filter, out, " "); } out.println(" </default-filters>"); out.println(); // winlists out.println(" <!-- Winlists -->"); out.println(" <winlists>"); for (Winlist winlist : WinlistManager.getInstance().getWinlists()) { WinlistConfig config = winlist.getConfig(); Properties props = config.getProperties(); if (props == null || props.isEmpty()) { out.println(" <winlist name=\"" + winlist.getId() + "\" class=\"" + winlist.getClass().getName() + "\"/>"); } else { out.println(" <winlist name=\"" + winlist.getId() + "\" class=\"" + winlist.getClass().getName() + "\">"); for (Object name : props.keySet()) { out.println(" <param name=\"" + name + "\" value=\"" + props.get(name) + "\"/>"); } out.println(" </winlist>"); } } out.println(" </winlists>"); out.println(); // default settings Settings settings = Settings.getDefaultSettings(); out.println(" <!-- Default game settings -->"); out.println(" <default-settings>"); out.println(" <!-- What level each player starts at -->"); out.println(" <starting-level>" + settings.getStartingLevel() + "</starting-level>"); out.println(); out.println(" <!-- How many lines to make before player level increases -->"); out.println(" <lines-per-level>" + settings.getLinesPerLevel() + "</lines-per-level>"); out.println(); out.println(" <!-- Number of levels to increase each time -->"); out.println(" <level-increase>" + settings.getLevelIncrease() + "</level-increase>"); out.println(); out.println(" <!-- Lines to make to get a special block -->"); out.println(" <lines-per-special>" + settings.getLinesPerSpecial() + "</lines-per-special>"); out.println(); out.println(" <!-- Number of special blocks added each time -->"); out.println(" <special-added>" + settings.getSpecialAdded() + "</special-added>"); out.println(); out.println(" <!-- Capacity of Special block inventory -->"); out.println(" <special-capacity>" + settings.getSpecialCapacity() + "</special-capacity>"); out.println(); out.println(" <!-- Play by classic rules? -->"); out.println(" <classic-rules>" + (settings.getClassicRules() ? "true" : "false") + "</classic-rules>"); out.println(); out.println(" <!-- Average together all player's game level? -->"); out.println( " <average-levels>" + (settings.getAverageLevels() ? "true" : "false") + "</average-levels>"); out.println(); out.println(" <!-- Same sequence of blocks for all players? (tetrinet 1.14 clients only) -->"); out.println(" <same-blocks>" + (settings.getSameBlocks() ? "true" : "false") + "</same-blocks>"); out.println(); out.println(" <block-occurancy>"); for (Block block : Block.values()) { out.println(" <" + block.getCode() + ">" + settings.getOccurancy(block) + "</" + block.getCode() + ">"); } out.println(" </block-occurancy>"); out.println(); out.println(" <special-occurancy>"); for (Special special : Special.values()) { out.println(" <" + special.getCode() + ">" + settings.getOccurancy(special) + "</" + special.getCode() + ">"); } out.println(" </special-occurancy>"); out.println(); out.println(" <!-- Sudden death parameters -->"); out.println(" <sudden-death>"); out.println(" <!-- Time in seconds before the sudden death begins, 0 to disable the sudden death -->"); out.println(" <time>" + settings.getSuddenDeathTime() + "</time>"); out.println(); out.println( " <!-- The message displayed when the sudden death begins. Use \"key:\" prefix to display an internationalized message -->"); out.println(" <message>" + settings.getSuddenDeathMessage() + "</message>"); out.println(); out.println(" <!-- The delay in seconds between lines additions -->"); out.println(" <delay>" + settings.getSuddenDeathDelay() + "</delay>"); out.println(); out.println(" <!-- The number of lines added -->"); out.println(" <lines-added>" + settings.getSuddenDeathLinesAdded() + "</lines-added>"); out.println(" </sudden-death>"); out.println(); out.println(" </default-settings>"); out.println(); out.println(); out.println(" <channels>"); for (Channel channel : ChannelManager.getInstance().channels()) { ChannelConfig config = channel.getConfig(); if (config.isPersistent()) { out.println(" <channel name=\"" + config.getName() + "\">"); if (config.getDescription() != null) { String description = config.getDescription(); description = description.contains("<") ? "<![CDATA[" + description + "]]>" : description; out.println(" <description>" + description + "</description>"); } if (config.getTopic() != null && config.getTopic().trim().length() > 0) { out.println(" <topic>"); out.println("<![CDATA["); out.println(config.getTopic()); out.println("]]>"); out.println(" </topic>"); } if (config.getSpeed() != Speed.MIXED) { out.println(" <speed>" + config.getSpeed().name().toLowerCase() + "</speed>"); } if (config.isPasswordProtected()) { out.println(" <password>" + config.getPassword() + "</password>"); } if (config.getAccessLevel() != AccessLevel.PLAYER) { out.println(" <access-level>" + config.getAccessLevel() + "</access-level>"); } if (config.isIdleAllowed()) { out.println(" <idle>true</idle>"); } if (!config.isVisible()) { out.println(" <visible>false</visible>"); } if (config.getMaxPlayers() != ChannelConfig.PLAYER_CAPACITY) { out.println(" <max-players>" + config.getMaxPlayers() + "</max-players>"); } if (config.getMaxSpectators() != ChannelConfig.SPECTATOR_CAPACITY) { out.println(" <max-spectators>" + config.getMaxSpectators() + "</max-spectators>"); } if (config.getWinlistId() != null) { out.println(" <winlist name=\"" + config.getWinlistId() + "\"/>"); } // channel settings settings = config.getSettings(); if (!settings.useDefaultSettings()) { out.println(" <settings>"); if (!settings.isDefaultStartingLevel()) { out.println(" <starting-level>" + settings.getStartingLevel() + "</starting-level>"); } if (!settings.isDefaultLinesPerLevel()) { out.println( " <lines-per-level>" + settings.getLinesPerLevel() + "</lines-per-level>"); } if (!settings.isDefaultLevelIncrease()) { out.println(" <level-increase>" + settings.getLevelIncrease() + "</level-increase>"); } if (!settings.isDefaultLinesPerSpecial()) { out.println(" <lines-per-special>" + settings.getLinesPerSpecial() + "</lines-per-special>"); } if (!settings.isDefaultSpecialAdded()) { out.println(" <special-added>" + settings.getSpecialAdded() + "</special-added>"); } if (!settings.isDefaultSpecialCapacity()) { out.println(" <special-capacity>" + settings.getSpecialCapacity() + "</special-capacity>"); } if (!settings.isDefaultClassicRules()) { out.println(" <classic-rules>" + (settings.getClassicRules() ? "true" : "false") + "</classic-rules>"); } if (!settings.isDefaultAverageLevels()) { out.println(" <average-levels>" + (settings.getAverageLevels() ? "true" : "false") + "</average-levels>"); } if (!settings.isDefaultSameBlocks()) { out.println(" <same-blocks>" + (settings.getSameBlocks() ? "true" : "false") + "</same-blocks>"); } if (!settings.isDefaultBlockOccurancy()) { out.println(" <block-occurancy>"); for (Block block : Block.values()) { if (settings.getOccurancy(block) != 0) { out.println(" <" + block.getCode() + ">" + settings.getOccurancy(block) + "</" + block.getCode() + ">"); } } out.println(" </block-occurancy>"); } if (!settings.isDefaultSpecialOccurancy()) { out.println(" <special-occurancy>"); for (Special special : Special.values()) { if (settings.getOccurancy(special) != 0) { out.println(" <" + special.getCode() + ">" + settings.getOccurancy(special) + "</" + special.getCode() + ">"); } } out.println(" </special-occurancy>"); } // sudden death settings if (!settings.isDefaultSuddenDeath()) { out.println(" <sudden-death>"); if (!settings.isDefaultSuddenDeathTime()) { out.println(" <time>" + settings.getSuddenDeathTime() + "</time>"); } if (!settings.isDefaultSuddenDeathMessage()) { out.println(" <message>" + settings.getSuddenDeathMessage() + "</message>"); } if (!settings.isDefaultSuddenDeathDelay()) { out.println(" <delay>" + settings.getSuddenDeathDelay() + "</delay>"); } if (!settings.isDefaultSuddenDeathLinesAdded()) { out.println(" <lines-added>" + settings.getSuddenDeathLinesAdded() + "</lines-added>"); } out.println(" </sudden-death>"); } out.println(" </settings>"); } // local filters Collection<MessageFilter> filters = channel.getLocalFilters(); if (!filters.isEmpty()) { out.println(" <filters>"); for (MessageFilter filter : filters) { saveFilter(filter.getConfig(), out, " "); } out.println(" </filters>"); } out.println(" </channel>"); out.println(); } } out.println(" </channels>"); out.println(); out.println("</tetrinet-channels>"); out.close(); }
From source file:org.apache.ranger.audit.provider.BaseAuditHandler.java
@Override public void init(Properties props, String basePropertyName) { LOG.info("BaseAuditProvider.init()"); this.props = props; if (basePropertyName != null) { propPrefix = basePropertyName;//from w w w.j a v a 2 s . co m } LOG.info("propPrefix=" + propPrefix); // Get final token List<String> tokens = MiscUtil.toArray(propPrefix, "."); String finalToken = tokens.get(tokens.size() - 1); String name = MiscUtil.getStringProperty(props, basePropertyName + "." + PROP_NAME); if (name != null && !name.isEmpty()) { setName(name); } if (providerName == null) { setName(finalToken); LOG.info("Using providerName from property prefix. providerName=" + getName()); } LOG.info("providerName=" + getName()); try { new GsonBuilder().setDateFormat("yyyyMMdd-HH:mm:ss.SSS-Z").create(); } catch (Throwable excp) { LOG.warn( "Log4jAuditProvider.init(): failed to create GsonBuilder object. events will be formated using toString(), instead of Json", excp); } mLogFailureReportMinIntervalInMs = MiscUtil.getIntProperty(props, AUDIT_LOG_FAILURE_REPORT_MIN_INTERVAL_PROP, 60 * 1000); String configPropsNamePrefix = propPrefix + "." + PROP_CONFIG + "."; for (Object propNameObj : props.keySet()) { String propName = propNameObj.toString(); if (!propName.startsWith(configPropsNamePrefix)) { continue; } String configName = propName.substring(configPropsNamePrefix.length()); String configValue = props.getProperty(propName); configProps.put(configName, configValue); LOG.info("Found Config property: " + configName + " => " + configValue); } }
From source file:gtu._work.ui.ExecuteOpener.java
void reloadExecListProperties(Properties prop) throws FileNotFoundException, IOException { DefaultListModel execListModel = new DefaultListModel(); List<String> keys = ListUtil.getList(prop.keySet(), String.class); Collections.sort(keys);/* ww w . j a va 2 s .c om*/ for (Object obj : keys) { execListModel.addElement((String) obj); } execList.setModel(execListModel); }
From source file:org.apache.archiva.metadata.repository.file.FileMetadataRepository.java
@Override public MetadataFacet getMetadataFacet(String repositoryId, String facetId, String name) { Properties properties; try {/*from w ww . j a v a2 s . com*/ properties = readProperties(new File(getMetadataDirectory(repositoryId, facetId), name), METADATA_KEY); } catch (FileNotFoundException e) { return null; } catch (IOException e) { // TODO log.error(e.getMessage(), e); return null; } MetadataFacet metadataFacet = null; MetadataFacetFactory metadataFacetFactory = metadataFacetFactories.get(facetId); if (metadataFacetFactory != null) { metadataFacet = metadataFacetFactory.createMetadataFacet(repositoryId, name); Map<String, String> map = new HashMap<>(); for (Object key : new ArrayList(properties.keySet())) { String property = (String) key; map.put(property, properties.getProperty(property)); } metadataFacet.fromProperties(map); } return metadataFacet; }
From source file:er.extensions.foundation.ERXProperties.java
/** * <div class="en">/*from w w w . j a va 2 s . c o m*/ * For each property in originalProperties, process the keys and values with * the registered property operators and stores the converted value into * destinationProperties. * </div> * * <div class="ja"> * ??????????? * ????????? * ERXSystem? * </div> * * @param originalProperties <div class="en">the properties to convert</div> * <div class="ja"></div> * @param destinationProperties <div class="en">the properties to copy into</div> * <div class="ja">???</div> */ public static void evaluatePropertyOperators(Properties originalProperties, Properties destinationProperties) { NSArray<String> operatorKeys = ERXProperties.operators.allKeys(); for (Object keyObj : new TreeSet<Object>(originalProperties.keySet())) { String key = (String) keyObj; if (key != null && key.length() > 0) { String value = originalProperties.getProperty(key); if (operatorKeys.count() > 0 && key.indexOf(".@") != -1) { ERXProperties.Operator operator = null; NSDictionary<String, String> computedProperties = null; for (String operatorKey : operatorKeys) { String operatorKeyWithAt = ".@" + operatorKey; if (key.endsWith(operatorKeyWithAt)) { operator = ERXProperties.operators.objectForKey(operatorKey); computedProperties = operator.compute( key.substring(0, key.length() - operatorKeyWithAt.length()), value, null); break; } int keyIndex = key.indexOf(operatorKeyWithAt + "."); if (keyIndex != -1) { operator = ERXProperties.operators.objectForKey(operatorKey); computedProperties = operator.compute(key.substring(0, keyIndex), value, key.substring(keyIndex + operatorKeyWithAt.length() + 1)); break; } } if (computedProperties == null) { destinationProperties.put(key, value); } else { originalProperties.remove(key); // If the key exists in the System properties' defaults with a different value, we must reinsert // the property so it doesn't get overwritten with the default value when we evaluate again. // This happens because ERXConfigurationManager processes the properties after a configuration // change in multiple passes and each calls this method. if (System.getProperty(key) != null && !System.getProperty(key).equals(value)) { originalProperties.put(key, value); } for (String computedKey : computedProperties.allKeys()) { destinationProperties.put(computedKey, computedProperties.objectForKey(computedKey)); } } } else { destinationProperties.put(key, value); } } } }
From source file:com.glaf.jbpm.connection.DbcpConnectionProvider.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public void configure(Properties props) throws RuntimeException { String jdbcDriverClass = props.getProperty(Environment.DRIVER); String jdbcUrl = props.getProperty(Environment.URL); Properties connectionProps = ConnectionProviderFactory.getConnectionProperties(props); log.info("DBCP using driver: " + jdbcDriverClass + " at URL: " + jdbcUrl); log.info("Connection properties: " + PropertiesHelper.maskOut(connectionProps, "password")); autocommit = PropertiesHelper.getBoolean(Environment.AUTOCOMMIT, props); log.info("autocommit mode: " + autocommit); if (jdbcDriverClass == null) { log.warn("No JDBC Driver class was specified by property " + Environment.DRIVER); } else {/*from w w w.j av a 2s . co m*/ try { Class.forName(jdbcDriverClass); } catch (ClassNotFoundException cnfe) { try { ClassUtils.classForName(jdbcDriverClass); } catch (Exception e) { String msg = "JDBC Driver class not found: " + jdbcDriverClass; log.error(msg, e); throw new RuntimeException(msg, e); } } } String dbUser = props.getProperty(Environment.USER); String dbPassword = props.getProperty(Environment.PASS); if (dbUser == null) { dbUser = ""; } if (dbPassword == null) { dbPassword = ""; } Properties properties = new Properties(); for (Iterator<Object> ii = props.keySet().iterator(); ii.hasNext();) { String key = (String) ii.next(); if (key.startsWith("hibernate.dbcp.")) { String newKey = key.substring(15); properties.put(newKey, props.get(key)); } } // Create the actual pool of connections ObjectPool connectionPool = new GenericObjectPool(null); if (props.getProperty("hibernate.connection.maxIdle") != null) { int value = PropertiesHelper.getInt("hibernate.connection.maxIdle", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMaxIdle(value); } } if (props.getProperty("hibernate.connection.minIdle") != null) { int value = PropertiesHelper.getInt("hibernate.connection.minIdle", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMinIdle(value); } } if (props.getProperty("hibernate.connection.maxActive") != null) { int value = PropertiesHelper.getInt("hibernate.connection.maxActive", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMaxActive(value); } } if (props.getProperty("hibernate.connection.maxWait") != null) { int value = PropertiesHelper.getInt("hibernate.connection.maxWait", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMaxWait(value); } } // how often should the evictor run (if ever, default is -1 = off) if (props.getProperty("hibernate.connection.timeBetweenEvictionRunsMillis") != null) { int value = PropertiesHelper.getInt("hibernate.connection.timeBetweenEvictionRunsMillis", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setTimeBetweenEvictionRunsMillis(value); // in each eviction run, ecict at least a fourth of "maxIdle" // connections int maxIdle = ((GenericObjectPool) connectionPool).getMaxIdle(); int numTestsPerEvictionRun = (int) Math.ceil(((double) maxIdle / 4)); ((GenericObjectPool) connectionPool).setNumTestsPerEvictionRun(numTestsPerEvictionRun); } } // how long may a connection sit idle in the pool before it may be // evicted if (props.getProperty("hibernate.connection.minEvictableIdleTimeMillis") != null) { int value = PropertiesHelper.getInt("hibernate.connection.minEvictableIdleTimeMillis", props, 0); if (value > 0) { ((GenericObjectPool) connectionPool).setMinEvictableIdleTimeMillis(value); } } // Create a factory to be used by the pool to create the connections ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, dbUser, dbPassword); // Create a factory for caching the PreparedStatements KeyedObjectPoolFactory kpf = null; if (props.getProperty("hibernate.connection.maxStatements") != null) { int value = PropertiesHelper.getInt("hibernate.connection.maxStatements", props, 0); if (value > 0) { kpf = new StackKeyedObjectPoolFactory(null, value); } } else { kpf = new StackKeyedObjectPoolFactory(null, 200); } // Wrap the connections and statements with pooled variants try { String testSQL = null; if (props.getProperty("hibernate.connection.testSQL") != null) { testSQL = PropertiesHelper.getString("hibernate.connection.testSQL", props, null); } new PoolableConnectionFactory(connectionFactory, connectionPool, kpf, testSQL, false, false); if (testSQL != null) { ((GenericObjectPool) connectionPool).setTestOnBorrow(true); } } catch (Exception e) { throw new ConnectionPoolException("DBCP", jdbcDriverClass, jdbcUrl, e); } ds = new PoolingDataSource(connectionPool); Connection conn = null; try { conn = ds.getConnection(); if (conn == null) { throw new RuntimeException("DBCP connection pool can't get jdbc connection"); } } catch (SQLException ex) { throw new RuntimeException(ex); } finally { JdbcUtils.close(conn); } String i = props.getProperty(Environment.ISOLATION); if (i == null) { isolation = null; } else { isolation = new Integer(i); log.info("JDBC isolation level: " + Environment.isolationLevelToString(isolation.intValue())); } }
From source file:jp.ne.sakura.kkkon.android.exceptionhandler.testapp.ExceptionHandlerReportApp.java
/** Called when the activity is first created. */ @Override// w ww. j a v a 2s . c o m public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { ExceptionHandler.initialize(context); if (ExceptionHandler.needReport()) { final String fileName = ExceptionHandler.getBugReportFileAbsolutePath(); final File file = new File(fileName); final File fileZip; { String strFileZip = file.getAbsolutePath(); { int index = strFileZip.lastIndexOf('.'); if (0 < index) { strFileZip = strFileZip.substring(0, index); strFileZip += ".zip"; } } Log.d(TAG, strFileZip); fileZip = new File(strFileZip); if (fileZip.exists()) { fileZip.delete(); } } if (file.exists()) { Log.d(TAG, file.getAbsolutePath()); InputStream inStream = null; ZipOutputStream outStream = null; try { inStream = new FileInputStream(file); String strFileName = file.getAbsolutePath(); { int index = strFileName.lastIndexOf(File.separatorChar); if (0 < index) { strFileName = strFileName.substring(index + 1); } } Log.d(TAG, strFileName); outStream = new ZipOutputStream(new FileOutputStream(fileZip)); byte[] buff = new byte[8124]; { ZipEntry entry = new ZipEntry(strFileName); outStream.putNextEntry(entry); int len = 0; while (0 < (len = inStream.read(buff))) { outStream.write(buff, 0, len); } outStream.closeEntry(); } outStream.finish(); outStream.flush(); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != outStream) { try { outStream.close(); } catch (Exception e) { } } outStream = null; if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } Log.i(TAG, "zip created"); } if (file.exists()) { // upload or send e-mail InputStream inStream = null; StringBuilder sb = new StringBuilder(); try { inStream = new FileInputStream(file); byte[] buff = new byte[8124]; int readed = 0; do { readed = inStream.read(buff); for (int i = 0; i < readed; i++) { sb.append((char) buff[i]); } } while (readed >= 0); final String str = sb.toString(); Log.i(TAG, str); } catch (IOException e) { Log.e(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } inStream = null; } AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if (null != defaultLocale) { if (defaultLocale.equals(Locale.JAPANESE) || defaultLocale.equals(Locale.JAPAN)) { title = ""; message = "?????????"; positive = "?"; negative = ""; needDefaultLang = false; } } if (needDefaultLang) { title = "ERROR"; message = "Got unexpected error. Do you want to send information of error."; positive = "Send"; negative = "Cancel"; } alertDialog.setTitle(title); alertDialog.setMessage(message); alertDialog.setPositiveButton(positive + " mail", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderMailClient.upload(context, file, new String[] { "diverKon+sakura@gmail.com" }); } }); alertDialog.setNeutralButton(positive + " http", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { DefaultUploaderWeb.upload(ExceptionHandlerReportApp.this, fileZip, "http://kkkon.sakura.ne.jp/android/bug"); } }); alertDialog.setNegativeButton(negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { ExceptionHandler.clearReport(); } }); alertDialog.show(); } // TODO separate activity for crash report //DefaultCheckerAPK.checkAPK( this, null ); } ExceptionHandler.registHandler(); } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("ExceptionHandler"); layout.addView(tv); Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); Button btn2 = new Button(this); btn2.setText("reinstall apk"); btn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); if (fileApk.exists()) { foundApk = true; Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); } } if (false == foundApk) { for (int i = 0; i < 10; ++i) { File fileApk = new File("/data/app/" + context.getPackageName() + "-" + i + ".apk"); Log.d(TAG, "check apk:" + fileApk.getAbsolutePath()); if (fileApk.exists()) { Log.i(TAG, "apk found. path=" + fileApk.getAbsolutePath()); /* * // require parmission { final String strCmd = "pm install -r " + fileApk.getAbsolutePath(); try { Runtime.getRuntime().exec( strCmd ); } catch ( IOException e ) { Log.e( TAG, "got exception", e ); } } */ Intent promptInstall = new Intent(Intent.ACTION_VIEW); promptInstall.setDataAndType(Uri.fromFile(fileApk), "application/vnd.android.package-archive"); promptInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(promptInstall); break; } } } } }); layout.addView(btn2); Button btn3 = new Button(this); btn3.setText("check apk"); btn3.setOnClickListener(new View.OnClickListener() { private boolean checkApk(final File fileApk, final ZipEntryFilter filter) { final boolean[] result = new boolean[1]; result[0] = true; final Thread thread = new Thread(new Runnable() { @Override public void run() { if (fileApk.exists()) { ZipFile zipFile = null; try { zipFile = new ZipFile(fileApk); List<ZipEntry> list = new ArrayList<ZipEntry>(zipFile.size()); for (Enumeration<? extends ZipEntry> e = zipFile.entries(); e.hasMoreElements();) { ZipEntry ent = e.nextElement(); Log.d(TAG, ent.getName()); Log.d(TAG, "" + ent.getSize()); final boolean accept = filter.accept(ent); if (accept) { list.add(ent); } } Log.d(TAG, Build.CPU_ABI); // API 4 Log.d(TAG, Build.CPU_ABI2); // API 8 final String[] abiArray = { Build.CPU_ABI // API 4 , Build.CPU_ABI2 // API 8 }; String abiMatched = null; { boolean foundMatched = false; for (final String abi : abiArray) { if (null == abi) { continue; } if (0 == abi.length()) { continue; } for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abi + "/"; if (entry.getName().startsWith(prefixABI)) { abiMatched = abi; foundMatched = true; break; } } if (foundMatched) { break; } } } Log.d(TAG, "matchedAbi=" + abiMatched); if (null != abiMatched) { boolean needReInstall = false; for (final ZipEntry entry : list) { Log.d(TAG, entry.getName()); final String prefixABI = "lib/" + abiMatched + "/"; if (entry.getName().startsWith(prefixABI)) { final String jniName = entry.getName().substring(prefixABI.length()); Log.d(TAG, "jni=" + jniName); final String strFileDst = context.getApplicationInfo().nativeLibraryDir + "/" + jniName; Log.d(TAG, strFileDst); final File fileDst = new File(strFileDst); if (!fileDst.exists()) { Log.w(TAG, "needReInstall: content missing " + strFileDst); needReInstall = true; } else { assert (entry.getSize() <= Integer.MAX_VALUE); if (fileDst.length() != entry.getSize()) { Log.w(TAG, "needReInstall: size broken " + strFileDst); needReInstall = true; } else { //org.apache.commons.io.IOUtils.contentEquals( zipFile.getInputStream( entry ), new FileInputStream(fileDst) ); final int size = (int) entry.getSize(); byte[] buffSrc = new byte[size]; { InputStream inStream = null; try { inStream = zipFile.getInputStream(entry); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffSrc, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } byte[] buffDst = new byte[(int) fileDst.length()]; { InputStream inStream = null; try { inStream = new FileInputStream(fileDst); int pos = 0; { while (pos < size) { final int ret = inStream.read(buffDst, pos, size - pos); if (ret <= 0) { break; } pos += ret; } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != inStream) { try { inStream.close(); } catch (Exception e) { } } } } if (Arrays.equals(buffSrc, buffDst)) { Log.d(TAG, " content equal " + strFileDst); // OK } else { Log.w(TAG, "needReInstall: content broken " + strFileDst); needReInstall = true; } } } } } // for ZipEntry if (needReInstall) { // need call INSTALL APK Log.w(TAG, "needReInstall apk"); result[0] = false; } else { Log.d(TAG, "no need ReInstall apk"); } } } catch (IOException e) { Log.d(TAG, "got exception", e); } finally { if (null != zipFile) { try { zipFile.close(); } catch (Exception e) { } } } } } }); thread.setName("check jni so"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "check thread.id=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now checking installation. Cancel check?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ try { thread.join(); } catch (InterruptedException e) { Log.d(TAG, "got exception", e); } return result[0]; } @Override public void onClick(View view) { boolean foundApk = false; { final String apkPath = context.getPackageCodePath(); // API8 Log.d(TAG, "PackageCodePath: " + apkPath); final File fileApk = new File(apkPath); this.checkApk(fileApk, new ZipEntryFilter() { @Override public boolean accept(ZipEntry entry) { if (entry.isDirectory()) { return false; } final String filename = entry.getName(); if (filename.startsWith("lib/")) { return true; } return false; } }); } } }); layout.addView(btn3); Button btn4 = new Button(this); btn4.setText("print dir and path"); btn4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { { final File file = context.getCacheDir(); Log.d(TAG, "Ctx.CacheDir=" + file.getAbsoluteFile()); } { final File file = context.getExternalCacheDir(); // API 8 if (null == file) { // no permission Log.d(TAG, "Ctx.ExternalCacheDir="); } else { Log.d(TAG, "Ctx.ExternalCacheDir=" + file.getAbsolutePath()); } } { final File file = context.getFilesDir(); Log.d(TAG, "Ctx.FilesDir=" + file.getAbsolutePath()); } { final String value = context.getPackageResourcePath(); Log.d(TAG, "Ctx.PackageResourcePath=" + value); } { final String[] files = context.fileList(); if (null == files) { Log.d(TAG, "Ctx.fileList=" + files); } else { for (final String filename : files) { Log.d(TAG, "Ctx.fileList=" + filename); } } } { final File file = Environment.getDataDirectory(); Log.d(TAG, "Env.DataDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getDownloadCacheDirectory(); Log.d(TAG, "Env.DownloadCacheDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getExternalStorageDirectory(); Log.d(TAG, "Env.ExternalStorageDirectory=" + file.getAbsolutePath()); } { final File file = Environment.getRootDirectory(); Log.d(TAG, "Env.RootDirectory=" + file.getAbsolutePath()); } { final ApplicationInfo appInfo = context.getApplicationInfo(); Log.d(TAG, "AppInfo.dataDir=" + appInfo.dataDir); Log.d(TAG, "AppInfo.nativeLibraryDir=" + appInfo.nativeLibraryDir); // API 9 Log.d(TAG, "AppInfo.publicSourceDir=" + appInfo.publicSourceDir); { final String[] sharedLibraryFiles = appInfo.sharedLibraryFiles; if (null == sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + sharedLibraryFiles); } else { for (final String fileName : sharedLibraryFiles) { Log.d(TAG, "AppInfo.sharedLibraryFiles=" + fileName); } } } Log.d(TAG, "AppInfo.sourceDir=" + appInfo.sourceDir); } { Log.d(TAG, "System.Properties start"); final Properties properties = System.getProperties(); if (null != properties) { for (final Object key : properties.keySet()) { String value = properties.getProperty((String) key); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.Properties end"); } { Log.d(TAG, "System.getenv start"); final Map<String, String> mapEnv = System.getenv(); if (null != mapEnv) { for (final Map.Entry<String, String> entry : mapEnv.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); Log.d(TAG, " key=" + key + ",value=" + value); } } Log.d(TAG, "System.getenv end"); } } }); layout.addView(btn4); Button btn5 = new Button(this); btn5.setText("check INSTALL_NON_MARKET_APPS"); btn5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SettingsCompat.initialize(context); if (SettingsCompat.isAllowedNonMarketApps()) { Log.d(TAG, "isAllowdNonMarketApps=true"); } else { Log.d(TAG, "isAllowdNonMarketApps=false"); } } }); layout.addView(btn5); Button btn6 = new Button(this); btn6.setText("send email"); btn6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent mailto = new Intent(); mailto.setAction(Intent.ACTION_SENDTO); mailto.setType("message/rfc822"); mailto.setData(Uri.parse("mailto:")); mailto.putExtra(Intent.EXTRA_EMAIL, new String[] { "" }); mailto.putExtra(Intent.EXTRA_SUBJECT, "[BugReport] " + context.getPackageName()); mailto.putExtra(Intent.EXTRA_TEXT, "body text"); //mailto.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK ); //context.startActivity( mailto ); Intent intent = Intent.createChooser(mailto, "Send Email"); if (null != intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { context.startActivity(intent); } catch (android.content.ActivityNotFoundException e) { Log.d(TAG, "got Exception", e); } } } }); layout.addView(btn6); Button btn7 = new Button(this); btn7.setText("upload http thread"); btn7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d(TAG, "brd=" + Build.BRAND); Log.d(TAG, "prd=" + Build.PRODUCT); //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); final Thread thread = new Thread(new Runnable() { @Override public void run() { Log.d(TAG, "upload thread tid=" + android.os.Process.myTid()); try { HttpPost httpPost = new HttpPost("http://kkkon.sakura.ne.jp/android/bug"); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); } Log.d(TAG, "upload finish"); } }); thread.setName("upload crash"); thread.start(); /* while ( thread.isAlive() ) { Log.d( TAG, "thread tid=" + android.os.Process.myTid() + ",state=" + thread.getState() ); if ( ! thread.isAlive() ) { break; } AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExceptionHandlerTestApp.this ); final Locale defaultLocale = Locale.getDefault(); String title = ""; String message = ""; String positive = ""; String negative = ""; boolean needDefaultLang = true; if ( null != defaultLocale ) { if ( defaultLocale.equals( Locale.JAPANESE ) || defaultLocale.equals( Locale.JAPAN ) ) { title = ""; message = "???????"; positive = "?"; negative = ""; needDefaultLang = false; } } if ( needDefaultLang ) { title = "INFO"; message = "Now uploading error information. Cancel upload?"; positive = "Wait"; negative = "Cancel"; } alertDialog.setTitle( title ); alertDialog.setMessage( message ); alertDialog.setPositiveButton( positive, null); alertDialog.setNegativeButton( negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface di, int i) { if ( thread.isAlive() ) { Log.d( TAG, "request interrupt" ); thread.interrupt(); } else { // nothing } } } ); if ( ! thread.isAlive() ) { break; } alertDialog.show(); if ( ! Thread.State.RUNNABLE.equals(thread.getState()) ) { break; } } */ /* try { thread.join(); // must call. leak handle... } catch ( InterruptedException e ) { Log.d( TAG, "got Exception", e ); } */ } }); layout.addView(btn7); Button btn8 = new Button(this); btn8.setText("upload http AsyncTask"); btn8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams().getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn8); Button btn9 = new Button(this); btn9.setText("call checkAPK"); btn9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean result = DefaultCheckerAPK.checkAPK(ExceptionHandlerReportApp.this, null); Log.i(TAG, "checkAPK result=" + result); } }); layout.addView(btn9); setContentView(layout); }