id
stringlengths
27
31
content
stringlengths
14
287k
max_stars_repo_path
stringlengths
52
57
crossvul-java_data_good_1910_15
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.insteon.internal.device; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.types.Command; import org.openhab.binding.insteon.internal.utils.Utils; import org.openhab.binding.insteon.internal.utils.Utils.ParsingException; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Class that loads the device feature templates from an xml stream * * @author Daniel Pfrommer - Initial contribution * @author Rob Nielsen - Port to openHAB 2 insteon binding */ @NonNullByDefault public class FeatureTemplateLoader { public static List<FeatureTemplate> readTemplates(InputStream input) throws IOException, ParsingException { List<FeatureTemplate> features = new ArrayList<>(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbFactory.setXIncludeAware(false); dbFactory.setExpandEntityReferences(false); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Parse it! Document doc = dBuilder.parse(input); doc.getDocumentElement().normalize(); Element root = doc.getDocumentElement(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) node; if (e.getTagName().equals("feature")) { features.add(parseFeature(e)); } } } } catch (SAXException e) { throw new ParsingException("Failed to parse XML!", e); } catch (ParserConfigurationException e) { throw new ParsingException("Got parser config exception! ", e); } return features; } private static FeatureTemplate parseFeature(Element e) throws ParsingException { String name = e.getAttribute("name"); boolean statusFeature = e.getAttribute("statusFeature").equals("true"); FeatureTemplate feature = new FeatureTemplate(name, statusFeature, e.getAttribute("timeout")); NodeList nodes = e.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element child = (Element) node; if (child.getTagName().equals("message-handler")) { parseMessageHandler(child, feature); } else if (child.getTagName().equals("command-handler")) { parseCommandHandler(child, feature); } else if (child.getTagName().equals("message-dispatcher")) { parseMessageDispatcher(child, feature); } else if (child.getTagName().equals("poll-handler")) { parsePollHandler(child, feature); } } } return feature; } private static HandlerEntry makeHandlerEntry(Element e) throws ParsingException { String handler = e.getTextContent(); if (handler == null) { throw new ParsingException("Could not find Handler for: " + e.getTextContent()); } NamedNodeMap attributes = e.getAttributes(); Map<String, @Nullable String> params = new HashMap<>(); for (int i = 0; i < attributes.getLength(); i++) { Node n = attributes.item(i); params.put(n.getNodeName(), n.getNodeValue()); } return new HandlerEntry(handler, params); } private static void parseMessageHandler(Element e, FeatureTemplate f) throws DOMException, ParsingException { HandlerEntry he = makeHandlerEntry(e); if (e.getAttribute("default").equals("true")) { f.setDefaultMessageHandler(he); } else { String attr = e.getAttribute("cmd"); int command = (attr == null) ? 0 : Utils.from0xHexString(attr); f.addMessageHandler(command, he); } } private static void parseCommandHandler(Element e, FeatureTemplate f) throws ParsingException { HandlerEntry he = makeHandlerEntry(e); if (e.getAttribute("default").equals("true")) { f.setDefaultCommandHandler(he); } else { Class<? extends Command> command = parseCommandClass(e.getAttribute("command")); f.addCommandHandler(command, he); } } private static void parseMessageDispatcher(Element e, FeatureTemplate f) throws DOMException, ParsingException { HandlerEntry he = makeHandlerEntry(e); f.setMessageDispatcher(he); } private static void parsePollHandler(Element e, FeatureTemplate f) throws ParsingException { HandlerEntry he = makeHandlerEntry(e); f.setPollHandler(he); } private static Class<? extends Command> parseCommandClass(String c) throws ParsingException { if (c.equals("OnOffType")) { return OnOffType.class; } else if (c.equals("PercentType")) { return PercentType.class; } else if (c.equals("DecimalType")) { return DecimalType.class; } else if (c.equals("IncreaseDecreaseType")) { return IncreaseDecreaseType.class; } else { throw new ParsingException("Unknown Command Type"); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_15
crossvul-java_data_good_4033_2
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.ds.common; import org.postgresql.PGProperty; import org.postgresql.jdbc.AutoSave; import org.postgresql.jdbc.PreferQueryMode; import org.postgresql.util.ExpressionProperties; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.postgresql.util.URLCoder; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Arrays; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.NamingException; import javax.naming.RefAddr; import javax.naming.Reference; import javax.naming.Referenceable; import javax.naming.StringRefAddr; import javax.sql.CommonDataSource; /** * Base class for data sources and related classes. * * @author Aaron Mulder (ammulder@chariotsolutions.com) */ public abstract class BaseDataSource implements CommonDataSource, Referenceable { private static final Logger LOGGER = Logger.getLogger(BaseDataSource.class.getName()); // Standard properties, defined in the JDBC 2.0 Optional Package spec private String[] serverNames = new String[] {"localhost"}; private String databaseName = ""; private String user; private String password; private int[] portNumbers = new int[] {0}; // Map for all other properties private Properties properties = new Properties(); /* * Ensure the driver is loaded as JDBC Driver might be invisible to Java's ServiceLoader. * Usually, {@code Class.forName(...)} is not required as {@link DriverManager} detects JDBC drivers * via {@code META-INF/services/java.sql.Driver} entries. However there might be cases when the driver * is located at the application level classloader, thus it might be required to perform manual * registration of the driver. */ static { try { Class.forName("org.postgresql.Driver"); } catch (ClassNotFoundException e) { throw new IllegalStateException( "BaseDataSource is unable to load org.postgresql.Driver. Please check if you have proper PostgreSQL JDBC Driver jar on the classpath", e); } } /** * Gets a connection to the PostgreSQL database. The database is identified by the DataSource * properties serverName, databaseName, and portNumber. The user to connect as is identified by * the DataSource properties user and password. * * @return A valid database connection. * @throws SQLException Occurs when the database connection cannot be established. */ public Connection getConnection() throws SQLException { return getConnection(user, password); } /** * Gets a connection to the PostgreSQL database. The database is identified by the DataSource * properties serverName, databaseName, and portNumber. The user to connect as is identified by * the arguments user and password, which override the DataSource properties by the same name. * * @param user user * @param password password * @return A valid database connection. * @throws SQLException Occurs when the database connection cannot be established. */ public Connection getConnection(String user, String password) throws SQLException { try { Connection con = DriverManager.getConnection(getUrl(), user, password); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.log(Level.FINE, "Created a {0} for {1} at {2}", new Object[] {getDescription(), user, getUrl()}); } return con; } catch (SQLException e) { LOGGER.log(Level.FINE, "Failed to create a {0} for {1} at {2}: {3}", new Object[] {getDescription(), user, getUrl(), e}); throw e; } } /** * This implementation don't use a LogWriter. */ @Override public PrintWriter getLogWriter() { return null; } /** * This implementation don't use a LogWriter. * * @param printWriter Not used */ @Override public void setLogWriter(PrintWriter printWriter) { // NOOP } /** * Gets the name of the host the PostgreSQL database is running on. * * @return name of the host the PostgreSQL database is running on * @deprecated use {@link #getServerNames()} */ @Deprecated public String getServerName() { return serverNames[0]; } /** * Gets the name of the host(s) the PostgreSQL database is running on. * * @return name of the host(s) the PostgreSQL database is running on */ public String[] getServerNames() { return serverNames; } /** * Sets the name of the host the PostgreSQL database is running on. If this is changed, it will * only affect future calls to getConnection. The default value is {@code localhost}. * * @param serverName name of the host the PostgreSQL database is running on * @deprecated use {@link #setServerNames(String[])} */ @Deprecated public void setServerName(String serverName) { this.setServerNames(new String[] { serverName }); } /** * Sets the name of the host(s) the PostgreSQL database is running on. If this is changed, it will * only affect future calls to getConnection. The default value is {@code localhost}. * * @param serverNames name of the host(s) the PostgreSQL database is running on */ public void setServerNames(String[] serverNames) { if (serverNames == null || serverNames.length == 0) { this.serverNames = new String[] {"localhost"}; } else { serverNames = Arrays.copyOf(serverNames, serverNames.length); for (int i = 0; i < serverNames.length; i++) { if (serverNames[i] == null || serverNames[i].equals("")) { serverNames[i] = "localhost"; } } this.serverNames = serverNames; } } /** * Gets the name of the PostgreSQL database, running on the server identified by the serverName * property. * * @return name of the PostgreSQL database */ public String getDatabaseName() { return databaseName; } /** * Sets the name of the PostgreSQL database, running on the server identified by the serverName * property. If this is changed, it will only affect future calls to getConnection. * * @param databaseName name of the PostgreSQL database */ public void setDatabaseName(String databaseName) { this.databaseName = databaseName; } /** * Gets a description of this DataSource-ish thing. Must be customized by subclasses. * * @return description of this DataSource-ish thing */ public abstract String getDescription(); /** * Gets the user to connect as by default. If this is not specified, you must use the * getConnection method which takes a user and password as parameters. * * @return user to connect as by default */ public String getUser() { return user; } /** * Sets the user to connect as by default. If this is not specified, you must use the * getConnection method which takes a user and password as parameters. If this is changed, it will * only affect future calls to getConnection. * * @param user user to connect as by default */ public void setUser(String user) { this.user = user; } /** * Gets the password to connect with by default. If this is not specified but a password is needed * to log in, you must use the getConnection method which takes a user and password as parameters. * * @return password to connect with by default */ public String getPassword() { return password; } /** * Sets the password to connect with by default. If this is not specified but a password is needed * to log in, you must use the getConnection method which takes a user and password as parameters. * If this is changed, it will only affect future calls to getConnection. * * @param password password to connect with by default */ public void setPassword(String password) { this.password = password; } /** * Gets the port which the PostgreSQL server is listening on for TCP/IP connections. * * @return The port, or 0 if the default port will be used. * @deprecated use {@link #getPortNumbers()} */ @Deprecated public int getPortNumber() { if (portNumbers == null || portNumbers.length == 0) { return 0; } return portNumbers[0]; } /** * Gets the port(s) which the PostgreSQL server is listening on for TCP/IP connections. * * @return The port(s), or 0 if the default port will be used. */ public int[] getPortNumbers() { return portNumbers; } /** * Sets the port which the PostgreSQL server is listening on for TCP/IP connections. Be sure the * -i flag is passed to postmaster when PostgreSQL is started. If this is not set, or set to 0, * the default port will be used. * * @param portNumber port which the PostgreSQL server is listening on for TCP/IP * @deprecated use {@link #setPortNumbers(int[])} */ @Deprecated public void setPortNumber(int portNumber) { setPortNumbers(new int[] { portNumber }); } /** * Sets the port(s) which the PostgreSQL server is listening on for TCP/IP connections. Be sure the * -i flag is passed to postmaster when PostgreSQL is started. If this is not set, or set to 0, * the default port will be used. * * @param portNumbers port(s) which the PostgreSQL server is listening on for TCP/IP */ public void setPortNumbers(int[] portNumbers) { if (portNumbers == null || portNumbers.length == 0) { portNumbers = new int[] { 0 }; } this.portNumbers = Arrays.copyOf(portNumbers, portNumbers.length); } /** * @return command line options for this connection */ public String getOptions() { return PGProperty.OPTIONS.get(properties); } /** * Set command line options for this connection * * @param options string to set options to */ public void setOptions(String options) { PGProperty.OPTIONS.set(properties, options); } /** * @return login timeout * @see PGProperty#LOGIN_TIMEOUT */ @Override public int getLoginTimeout() { return PGProperty.LOGIN_TIMEOUT.getIntNoCheck(properties); } /** * @param loginTimeout login timeout * @see PGProperty#LOGIN_TIMEOUT */ @Override public void setLoginTimeout(int loginTimeout) { PGProperty.LOGIN_TIMEOUT.set(properties, loginTimeout); } /** * @return connect timeout * @see PGProperty#CONNECT_TIMEOUT */ public int getConnectTimeout() { return PGProperty.CONNECT_TIMEOUT.getIntNoCheck(properties); } /** * @param connectTimeout connect timeout * @see PGProperty#CONNECT_TIMEOUT */ public void setConnectTimeout(int connectTimeout) { PGProperty.CONNECT_TIMEOUT.set(properties, connectTimeout); } /** * @return protocol version * @see PGProperty#PROTOCOL_VERSION */ public int getProtocolVersion() { if (!PGProperty.PROTOCOL_VERSION.isPresent(properties)) { return 0; } else { return PGProperty.PROTOCOL_VERSION.getIntNoCheck(properties); } } /** * @param protocolVersion protocol version * @see PGProperty#PROTOCOL_VERSION */ public void setProtocolVersion(int protocolVersion) { if (protocolVersion == 0) { PGProperty.PROTOCOL_VERSION.set(properties, null); } else { PGProperty.PROTOCOL_VERSION.set(properties, protocolVersion); } } /** * @return receive buffer size * @see PGProperty#RECEIVE_BUFFER_SIZE */ public int getReceiveBufferSize() { return PGProperty.RECEIVE_BUFFER_SIZE.getIntNoCheck(properties); } /** * @param nbytes receive buffer size * @see PGProperty#RECEIVE_BUFFER_SIZE */ public void setReceiveBufferSize(int nbytes) { PGProperty.RECEIVE_BUFFER_SIZE.set(properties, nbytes); } /** * @return send buffer size * @see PGProperty#SEND_BUFFER_SIZE */ public int getSendBufferSize() { return PGProperty.SEND_BUFFER_SIZE.getIntNoCheck(properties); } /** * @param nbytes send buffer size * @see PGProperty#SEND_BUFFER_SIZE */ public void setSendBufferSize(int nbytes) { PGProperty.SEND_BUFFER_SIZE.set(properties, nbytes); } /** * @param count prepare threshold * @see PGProperty#PREPARE_THRESHOLD */ public void setPrepareThreshold(int count) { PGProperty.PREPARE_THRESHOLD.set(properties, count); } /** * @return prepare threshold * @see PGProperty#PREPARE_THRESHOLD */ public int getPrepareThreshold() { return PGProperty.PREPARE_THRESHOLD.getIntNoCheck(properties); } /** * @return prepared statement cache size (number of statements per connection) * @see PGProperty#PREPARED_STATEMENT_CACHE_QUERIES */ public int getPreparedStatementCacheQueries() { return PGProperty.PREPARED_STATEMENT_CACHE_QUERIES.getIntNoCheck(properties); } /** * @param cacheSize prepared statement cache size (number of statements per connection) * @see PGProperty#PREPARED_STATEMENT_CACHE_QUERIES */ public void setPreparedStatementCacheQueries(int cacheSize) { PGProperty.PREPARED_STATEMENT_CACHE_QUERIES.set(properties, cacheSize); } /** * @return prepared statement cache size (number of megabytes per connection) * @see PGProperty#PREPARED_STATEMENT_CACHE_SIZE_MIB */ public int getPreparedStatementCacheSizeMiB() { return PGProperty.PREPARED_STATEMENT_CACHE_SIZE_MIB.getIntNoCheck(properties); } /** * @param cacheSize statement cache size (number of megabytes per connection) * @see PGProperty#PREPARED_STATEMENT_CACHE_SIZE_MIB */ public void setPreparedStatementCacheSizeMiB(int cacheSize) { PGProperty.PREPARED_STATEMENT_CACHE_SIZE_MIB.set(properties, cacheSize); } /** * @return database metadata cache fields size (number of fields cached per connection) * @see PGProperty#DATABASE_METADATA_CACHE_FIELDS */ public int getDatabaseMetadataCacheFields() { return PGProperty.DATABASE_METADATA_CACHE_FIELDS.getIntNoCheck(properties); } /** * @param cacheSize database metadata cache fields size (number of fields cached per connection) * @see PGProperty#DATABASE_METADATA_CACHE_FIELDS */ public void setDatabaseMetadataCacheFields(int cacheSize) { PGProperty.DATABASE_METADATA_CACHE_FIELDS.set(properties, cacheSize); } /** * @return database metadata cache fields size (number of megabytes per connection) * @see PGProperty#DATABASE_METADATA_CACHE_FIELDS_MIB */ public int getDatabaseMetadataCacheFieldsMiB() { return PGProperty.DATABASE_METADATA_CACHE_FIELDS_MIB.getIntNoCheck(properties); } /** * @param cacheSize database metadata cache fields size (number of megabytes per connection) * @see PGProperty#DATABASE_METADATA_CACHE_FIELDS_MIB */ public void setDatabaseMetadataCacheFieldsMiB(int cacheSize) { PGProperty.DATABASE_METADATA_CACHE_FIELDS_MIB.set(properties, cacheSize); } /** * @param fetchSize default fetch size * @see PGProperty#DEFAULT_ROW_FETCH_SIZE */ public void setDefaultRowFetchSize(int fetchSize) { PGProperty.DEFAULT_ROW_FETCH_SIZE.set(properties, fetchSize); } /** * @return default fetch size * @see PGProperty#DEFAULT_ROW_FETCH_SIZE */ public int getDefaultRowFetchSize() { return PGProperty.DEFAULT_ROW_FETCH_SIZE.getIntNoCheck(properties); } /** * @param unknownLength unknown length * @see PGProperty#UNKNOWN_LENGTH */ public void setUnknownLength(int unknownLength) { PGProperty.UNKNOWN_LENGTH.set(properties, unknownLength); } /** * @return unknown length * @see PGProperty#UNKNOWN_LENGTH */ public int getUnknownLength() { return PGProperty.UNKNOWN_LENGTH.getIntNoCheck(properties); } /** * @param seconds socket timeout * @see PGProperty#SOCKET_TIMEOUT */ public void setSocketTimeout(int seconds) { PGProperty.SOCKET_TIMEOUT.set(properties, seconds); } /** * @return socket timeout * @see PGProperty#SOCKET_TIMEOUT */ public int getSocketTimeout() { return PGProperty.SOCKET_TIMEOUT.getIntNoCheck(properties); } /** * @param seconds timeout that is used for sending cancel command * @see PGProperty#CANCEL_SIGNAL_TIMEOUT */ public void setCancelSignalTimeout(int seconds) { PGProperty.CANCEL_SIGNAL_TIMEOUT.set(properties, seconds); } /** * @return timeout that is used for sending cancel command in seconds * @see PGProperty#CANCEL_SIGNAL_TIMEOUT */ public int getCancelSignalTimeout() { return PGProperty.CANCEL_SIGNAL_TIMEOUT.getIntNoCheck(properties); } /** * @param enabled if SSL is enabled * @see PGProperty#SSL */ public void setSsl(boolean enabled) { if (enabled) { PGProperty.SSL.set(properties, true); } else { PGProperty.SSL.set(properties, false); } } /** * @return true if SSL is enabled * @see PGProperty#SSL */ public boolean getSsl() { // "true" if "ssl" is set but empty return PGProperty.SSL.getBoolean(properties) || "".equals(PGProperty.SSL.get(properties)); } /** * @param classname SSL factory class name * @see PGProperty#SSL_FACTORY */ public void setSslfactory(String classname) { PGProperty.SSL_FACTORY.set(properties, classname); } /** * @return SSL factory class name * @see PGProperty#SSL_FACTORY */ public String getSslfactory() { return PGProperty.SSL_FACTORY.get(properties); } /** * @return SSL mode * @see PGProperty#SSL_MODE */ public String getSslMode() { return PGProperty.SSL_MODE.get(properties); } /** * @param mode SSL mode * @see PGProperty#SSL_MODE */ public void setSslMode(String mode) { PGProperty.SSL_MODE.set(properties, mode); } /** * @return SSL mode * @see PGProperty#SSL_FACTORY_ARG */ public String getSslFactoryArg() { return PGProperty.SSL_FACTORY_ARG.get(properties); } /** * @param arg argument forwarded to SSL factory * @see PGProperty#SSL_FACTORY_ARG */ public void setSslFactoryArg(String arg) { PGProperty.SSL_FACTORY_ARG.set(properties, arg); } /** * @return argument forwarded to SSL factory * @see PGProperty#SSL_HOSTNAME_VERIFIER */ public String getSslHostnameVerifier() { return PGProperty.SSL_HOSTNAME_VERIFIER.get(properties); } /** * @param className SSL hostname verifier * @see PGProperty#SSL_HOSTNAME_VERIFIER */ public void setSslHostnameVerifier(String className) { PGProperty.SSL_HOSTNAME_VERIFIER.set(properties, className); } /** * @return className SSL hostname verifier * @see PGProperty#SSL_CERT */ public String getSslCert() { return PGProperty.SSL_CERT.get(properties); } /** * @param file SSL certificate * @see PGProperty#SSL_CERT */ public void setSslCert(String file) { PGProperty.SSL_CERT.set(properties, file); } /** * @return SSL certificate * @see PGProperty#SSL_KEY */ public String getSslKey() { return PGProperty.SSL_KEY.get(properties); } /** * @param file SSL key * @see PGProperty#SSL_KEY */ public void setSslKey(String file) { PGProperty.SSL_KEY.set(properties, file); } /** * @return SSL root certificate * @see PGProperty#SSL_ROOT_CERT */ public String getSslRootCert() { return PGProperty.SSL_ROOT_CERT.get(properties); } /** * @param file SSL root certificate * @see PGProperty#SSL_ROOT_CERT */ public void setSslRootCert(String file) { PGProperty.SSL_ROOT_CERT.set(properties, file); } /** * @return SSL password * @see PGProperty#SSL_PASSWORD */ public String getSslPassword() { return PGProperty.SSL_PASSWORD.get(properties); } /** * @param password SSL password * @see PGProperty#SSL_PASSWORD */ public void setSslPassword(String password) { PGProperty.SSL_PASSWORD.set(properties, password); } /** * @return SSL password callback * @see PGProperty#SSL_PASSWORD_CALLBACK */ public String getSslPasswordCallback() { return PGProperty.SSL_PASSWORD_CALLBACK.get(properties); } /** * @param className SSL password callback class name * @see PGProperty#SSL_PASSWORD_CALLBACK */ public void setSslPasswordCallback(String className) { PGProperty.SSL_PASSWORD_CALLBACK.set(properties, className); } /** * @param applicationName application name * @see PGProperty#APPLICATION_NAME */ public void setApplicationName(String applicationName) { PGProperty.APPLICATION_NAME.set(properties, applicationName); } /** * @return application name * @see PGProperty#APPLICATION_NAME */ public String getApplicationName() { return PGProperty.APPLICATION_NAME.get(properties); } /** * @param targetServerType target server type * @see PGProperty#TARGET_SERVER_TYPE */ public void setTargetServerType(String targetServerType) { PGProperty.TARGET_SERVER_TYPE.set(properties, targetServerType); } /** * @return target server type * @see PGProperty#TARGET_SERVER_TYPE */ public String getTargetServerType() { return PGProperty.TARGET_SERVER_TYPE.get(properties); } /** * @param loadBalanceHosts load balance hosts * @see PGProperty#LOAD_BALANCE_HOSTS */ public void setLoadBalanceHosts(boolean loadBalanceHosts) { PGProperty.LOAD_BALANCE_HOSTS.set(properties, loadBalanceHosts); } /** * @return load balance hosts * @see PGProperty#LOAD_BALANCE_HOSTS */ public boolean getLoadBalanceHosts() { return PGProperty.LOAD_BALANCE_HOSTS.isPresent(properties); } /** * @param hostRecheckSeconds host recheck seconds * @see PGProperty#HOST_RECHECK_SECONDS */ public void setHostRecheckSeconds(int hostRecheckSeconds) { PGProperty.HOST_RECHECK_SECONDS.set(properties, hostRecheckSeconds); } /** * @return host recheck seconds * @see PGProperty#HOST_RECHECK_SECONDS */ public int getHostRecheckSeconds() { return PGProperty.HOST_RECHECK_SECONDS.getIntNoCheck(properties); } /** * @param enabled if TCP keep alive should be enabled * @see PGProperty#TCP_KEEP_ALIVE */ public void setTcpKeepAlive(boolean enabled) { PGProperty.TCP_KEEP_ALIVE.set(properties, enabled); } /** * @return true if TCP keep alive is enabled * @see PGProperty#TCP_KEEP_ALIVE */ public boolean getTcpKeepAlive() { return PGProperty.TCP_KEEP_ALIVE.getBoolean(properties); } /** * @param enabled if binary transfer should be enabled * @see PGProperty#BINARY_TRANSFER */ public void setBinaryTransfer(boolean enabled) { PGProperty.BINARY_TRANSFER.set(properties, enabled); } /** * @return true if binary transfer is enabled * @see PGProperty#BINARY_TRANSFER */ public boolean getBinaryTransfer() { return PGProperty.BINARY_TRANSFER.getBoolean(properties); } /** * @param oidList list of OIDs that are allowed to use binary transfer * @see PGProperty#BINARY_TRANSFER_ENABLE */ public void setBinaryTransferEnable(String oidList) { PGProperty.BINARY_TRANSFER_ENABLE.set(properties, oidList); } /** * @return list of OIDs that are allowed to use binary transfer * @see PGProperty#BINARY_TRANSFER_ENABLE */ public String getBinaryTransferEnable() { return PGProperty.BINARY_TRANSFER_ENABLE.get(properties); } /** * @param oidList list of OIDs that are not allowed to use binary transfer * @see PGProperty#BINARY_TRANSFER_DISABLE */ public void setBinaryTransferDisable(String oidList) { PGProperty.BINARY_TRANSFER_DISABLE.set(properties, oidList); } /** * @return list of OIDs that are not allowed to use binary transfer * @see PGProperty#BINARY_TRANSFER_DISABLE */ public String getBinaryTransferDisable() { return PGProperty.BINARY_TRANSFER_DISABLE.get(properties); } /** * @return string type * @see PGProperty#STRING_TYPE */ public String getStringType() { return PGProperty.STRING_TYPE.get(properties); } /** * @param stringType string type * @see PGProperty#STRING_TYPE */ public void setStringType(String stringType) { PGProperty.STRING_TYPE.set(properties, stringType); } /** * @return true if column sanitizer is disabled * @see PGProperty#DISABLE_COLUMN_SANITISER */ public boolean isColumnSanitiserDisabled() { return PGProperty.DISABLE_COLUMN_SANITISER.getBoolean(properties); } /** * @return true if column sanitizer is disabled * @see PGProperty#DISABLE_COLUMN_SANITISER */ public boolean getDisableColumnSanitiser() { return PGProperty.DISABLE_COLUMN_SANITISER.getBoolean(properties); } /** * @param disableColumnSanitiser if column sanitizer should be disabled * @see PGProperty#DISABLE_COLUMN_SANITISER */ public void setDisableColumnSanitiser(boolean disableColumnSanitiser) { PGProperty.DISABLE_COLUMN_SANITISER.set(properties, disableColumnSanitiser); } /** * @return current schema * @see PGProperty#CURRENT_SCHEMA */ public String getCurrentSchema() { return PGProperty.CURRENT_SCHEMA.get(properties); } /** * @param currentSchema current schema * @see PGProperty#CURRENT_SCHEMA */ public void setCurrentSchema(String currentSchema) { PGProperty.CURRENT_SCHEMA.set(properties, currentSchema); } /** * @return true if connection is readonly * @see PGProperty#READ_ONLY */ public boolean getReadOnly() { return PGProperty.READ_ONLY.getBoolean(properties); } /** * @param readOnly if connection should be readonly * @see PGProperty#READ_ONLY */ public void setReadOnly(boolean readOnly) { PGProperty.READ_ONLY.set(properties, readOnly); } /** * @return The behavior when set read only * @see PGProperty#READ_ONLY_MODE */ public String getReadOnlyMode() { return PGProperty.READ_ONLY_MODE.get(properties); } /** * @param mode the behavior when set read only * @see PGProperty#READ_ONLY_MODE */ public void setReadOnlyMode(String mode) { PGProperty.READ_ONLY_MODE.set(properties, mode); } /** * @return true if driver should log unclosed connections * @see PGProperty#LOG_UNCLOSED_CONNECTIONS */ public boolean getLogUnclosedConnections() { return PGProperty.LOG_UNCLOSED_CONNECTIONS.getBoolean(properties); } /** * @param enabled true if driver should log unclosed connections * @see PGProperty#LOG_UNCLOSED_CONNECTIONS */ public void setLogUnclosedConnections(boolean enabled) { PGProperty.LOG_UNCLOSED_CONNECTIONS.set(properties, enabled); } /** * @return true if driver should log include detail in server error messages * @see PGProperty#LOG_SERVER_ERROR_DETAIL */ public boolean getLogServerErrorDetail() { return PGProperty.LOG_SERVER_ERROR_DETAIL.getBoolean(properties); } /** * @param enabled true if driver should include detail in server error messages * @see PGProperty#LOG_SERVER_ERROR_DETAIL */ public void setLogServerErrorDetail(boolean enabled) { PGProperty.LOG_SERVER_ERROR_DETAIL.set(properties, enabled); } /** * @return assumed minimal server version * @see PGProperty#ASSUME_MIN_SERVER_VERSION */ public String getAssumeMinServerVersion() { return PGProperty.ASSUME_MIN_SERVER_VERSION.get(properties); } /** * @param minVersion assumed minimal server version * @see PGProperty#ASSUME_MIN_SERVER_VERSION */ public void setAssumeMinServerVersion(String minVersion) { PGProperty.ASSUME_MIN_SERVER_VERSION.set(properties, minVersion); } /** * @return JAAS application name * @see PGProperty#JAAS_APPLICATION_NAME */ public String getJaasApplicationName() { return PGProperty.JAAS_APPLICATION_NAME.get(properties); } /** * @param name JAAS application name * @see PGProperty#JAAS_APPLICATION_NAME */ public void setJaasApplicationName(String name) { PGProperty.JAAS_APPLICATION_NAME.set(properties, name); } /** * @return true if perform JAAS login before GSS authentication * @see PGProperty#JAAS_LOGIN */ public boolean getJaasLogin() { return PGProperty.JAAS_LOGIN.getBoolean(properties); } /** * @param doLogin true if perform JAAS login before GSS authentication * @see PGProperty#JAAS_LOGIN */ public void setJaasLogin(boolean doLogin) { PGProperty.JAAS_LOGIN.set(properties, doLogin); } /** * @return Kerberos server name * @see PGProperty#KERBEROS_SERVER_NAME */ public String getKerberosServerName() { return PGProperty.KERBEROS_SERVER_NAME.get(properties); } /** * @param serverName Kerberos server name * @see PGProperty#KERBEROS_SERVER_NAME */ public void setKerberosServerName(String serverName) { PGProperty.KERBEROS_SERVER_NAME.set(properties, serverName); } /** * @return true if use SPNEGO * @see PGProperty#USE_SPNEGO */ public boolean getUseSpNego() { return PGProperty.USE_SPNEGO.getBoolean(properties); } /** * @param use true if use SPNEGO * @see PGProperty#USE_SPNEGO */ public void setUseSpNego(boolean use) { PGProperty.USE_SPNEGO.set(properties, use); } /** * @return GSS mode: auto, sspi, or gssapi * @see PGProperty#GSS_LIB */ public String getGssLib() { return PGProperty.GSS_LIB.get(properties); } /** * @param lib GSS mode: auto, sspi, or gssapi * @see PGProperty#GSS_LIB */ public void setGssLib(String lib) { PGProperty.GSS_LIB.set(properties, lib); } /** * @return SSPI service class * @see PGProperty#SSPI_SERVICE_CLASS */ public String getSspiServiceClass() { return PGProperty.SSPI_SERVICE_CLASS.get(properties); } /** * @param serviceClass SSPI service class * @see PGProperty#SSPI_SERVICE_CLASS */ public void setSspiServiceClass(String serviceClass) { PGProperty.SSPI_SERVICE_CLASS.set(properties, serviceClass); } /** * @return if connection allows encoding changes * @see PGProperty#ALLOW_ENCODING_CHANGES */ public boolean getAllowEncodingChanges() { return PGProperty.ALLOW_ENCODING_CHANGES.getBoolean(properties); } /** * @param allow if connection allows encoding changes * @see PGProperty#ALLOW_ENCODING_CHANGES */ public void setAllowEncodingChanges(boolean allow) { PGProperty.ALLOW_ENCODING_CHANGES.set(properties, allow); } /** * @return socket factory class name * @see PGProperty#SOCKET_FACTORY */ public String getSocketFactory() { return PGProperty.SOCKET_FACTORY.get(properties); } /** * @param socketFactoryClassName socket factory class name * @see PGProperty#SOCKET_FACTORY */ public void setSocketFactory(String socketFactoryClassName) { PGProperty.SOCKET_FACTORY.set(properties, socketFactoryClassName); } /** * @return socket factory argument * @see PGProperty#SOCKET_FACTORY_ARG */ public String getSocketFactoryArg() { return PGProperty.SOCKET_FACTORY_ARG.get(properties); } /** * @param socketFactoryArg socket factory argument * @see PGProperty#SOCKET_FACTORY_ARG */ public void setSocketFactoryArg(String socketFactoryArg) { PGProperty.SOCKET_FACTORY_ARG.set(properties, socketFactoryArg); } /** * @param replication set to 'database' for logical replication or 'true' for physical replication * @see PGProperty#REPLICATION */ public void setReplication(String replication) { PGProperty.REPLICATION.set(properties, replication); } /** * @return 'select', "callIfNoReturn', or 'call' * @see PGProperty#ESCAPE_SYNTAX_CALL_MODE */ public String getEscapeSyntaxCallMode() { return PGProperty.ESCAPE_SYNTAX_CALL_MODE.get(properties); } /** * @param callMode the call mode to use for JDBC escape call syntax * @see PGProperty#ESCAPE_SYNTAX_CALL_MODE */ public void setEscapeSyntaxCallMode(String callMode) { PGProperty.ESCAPE_SYNTAX_CALL_MODE.set(properties, callMode); } /** * @return null, 'database', or 'true * @see PGProperty#REPLICATION */ public String getReplication() { return PGProperty.REPLICATION.get(properties); } /** * @return Logger Level of the JDBC Driver * @see PGProperty#LOGGER_LEVEL */ public String getLoggerLevel() { return PGProperty.LOGGER_LEVEL.get(properties); } /** * @param loggerLevel of the JDBC Driver * @see PGProperty#LOGGER_LEVEL */ public void setLoggerLevel(String loggerLevel) { PGProperty.LOGGER_LEVEL.set(properties, loggerLevel); } /** * @return File output of the Logger. * @see PGProperty#LOGGER_FILE */ public String getLoggerFile() { ExpressionProperties exprProps = new ExpressionProperties(properties, System.getProperties()); return PGProperty.LOGGER_FILE.get(exprProps); } /** * @param loggerFile File output of the Logger. * @see PGProperty#LOGGER_LEVEL */ public void setLoggerFile(String loggerFile) { PGProperty.LOGGER_FILE.set(properties, loggerFile); } /** * Generates a {@link DriverManager} URL from the other properties supplied. * * @return {@link DriverManager} URL from the other properties supplied */ public String getUrl() { StringBuilder url = new StringBuilder(100); url.append("jdbc:postgresql://"); for (int i = 0; i < serverNames.length; i++) { if (i > 0) { url.append(","); } url.append(serverNames[i]); if (portNumbers != null && portNumbers.length >= i && portNumbers[i] != 0) { url.append(":").append(portNumbers[i]); } } url.append("/").append(URLCoder.encode(databaseName)); StringBuilder query = new StringBuilder(100); for (PGProperty property : PGProperty.values()) { if (property.isPresent(properties)) { if (query.length() != 0) { query.append("&"); } query.append(property.getName()); query.append("="); query.append(URLCoder.encode(property.get(properties))); } } if (query.length() > 0) { url.append("?"); url.append(query); } return url.toString(); } /** * Generates a {@link DriverManager} URL from the other properties supplied. * * @return {@link DriverManager} URL from the other properties supplied */ public String getURL() { return getUrl(); } /** * Sets properties from a {@link DriverManager} URL. * * @param url properties to set */ public void setUrl(String url) { Properties p = org.postgresql.Driver.parseURL(url, null); if (p == null) { throw new IllegalArgumentException("URL invalid " + url); } for (PGProperty property : PGProperty.values()) { if (!this.properties.containsKey(property.getName())) { setProperty(property, property.get(p)); } } } /** * Sets properties from a {@link DriverManager} URL. * Added to follow convention used in other DBMS. * * @param url properties to set */ public void setURL(String url) { setUrl(url); } public String getProperty(String name) throws SQLException { PGProperty pgProperty = PGProperty.forName(name); if (pgProperty != null) { return getProperty(pgProperty); } else { throw new PSQLException(GT.tr("Unsupported property name: {0}", name), PSQLState.INVALID_PARAMETER_VALUE); } } public void setProperty(String name, String value) throws SQLException { PGProperty pgProperty = PGProperty.forName(name); if (pgProperty != null) { setProperty(pgProperty, value); } else { throw new PSQLException(GT.tr("Unsupported property name: {0}", name), PSQLState.INVALID_PARAMETER_VALUE); } } public String getProperty(PGProperty property) { return property.get(properties); } public void setProperty(PGProperty property, String value) { if (value == null) { return; } switch (property) { case PG_HOST: setServerNames(value.split(",")); break; case PG_PORT: String[] ps = value.split(","); int[] ports = new int[ps.length]; for (int i = 0 ; i < ps.length; i++) { try { ports[i] = Integer.parseInt(ps[i]); } catch (NumberFormatException e) { ports[i] = 0; } } setPortNumbers(ports); break; case PG_DBNAME: setDatabaseName(value); break; case USER: setUser(value); break; case PASSWORD: setPassword(value); break; default: properties.setProperty(property.getName(), value); } } /** * Generates a reference using the appropriate object factory. * * @return reference using the appropriate object factory */ protected Reference createReference() { return new Reference(getClass().getName(), PGObjectFactory.class.getName(), null); } public Reference getReference() throws NamingException { Reference ref = createReference(); StringBuilder serverString = new StringBuilder(); for (int i = 0; i < serverNames.length; i++) { if (i > 0) { serverString.append(","); } String serverName = serverNames[i]; serverString.append(serverName); } ref.add(new StringRefAddr("serverName", serverString.toString())); StringBuilder portString = new StringBuilder(); for (int i = 0; i < portNumbers.length; i++) { if (i > 0) { portString.append(","); } int p = portNumbers[i]; portString.append(Integer.toString(p)); } ref.add(new StringRefAddr("portNumber", portString.toString())); ref.add(new StringRefAddr("databaseName", databaseName)); if (user != null) { ref.add(new StringRefAddr("user", user)); } if (password != null) { ref.add(new StringRefAddr("password", password)); } for (PGProperty property : PGProperty.values()) { if (property.isPresent(properties)) { ref.add(new StringRefAddr(property.getName(), property.get(properties))); } } return ref; } public void setFromReference(Reference ref) { databaseName = getReferenceProperty(ref, "databaseName"); String portNumberString = getReferenceProperty(ref, "portNumber"); if (portNumberString != null) { String[] ps = portNumberString.split(","); int[] ports = new int[ps.length]; for (int i = 0; i < ps.length; i++) { try { ports[i] = Integer.parseInt(ps[i]); } catch (NumberFormatException e) { ports[i] = 0; } } setPortNumbers(ports); } else { setPortNumbers(null); } setServerNames(getReferenceProperty(ref, "serverName").split(",")); for (PGProperty property : PGProperty.values()) { setProperty(property, getReferenceProperty(ref, property.getName())); } } private static String getReferenceProperty(Reference ref, String propertyName) { RefAddr addr = ref.get(propertyName); if (addr == null) { return null; } return (String) addr.getContent(); } protected void writeBaseObject(ObjectOutputStream out) throws IOException { out.writeObject(serverNames); out.writeObject(databaseName); out.writeObject(user); out.writeObject(password); out.writeObject(portNumbers); out.writeObject(properties); } protected void readBaseObject(ObjectInputStream in) throws IOException, ClassNotFoundException { serverNames = (String[]) in.readObject(); databaseName = (String) in.readObject(); user = (String) in.readObject(); password = (String) in.readObject(); portNumbers = (int[]) in.readObject(); properties = (Properties) in.readObject(); } public void initializeFrom(BaseDataSource source) throws IOException, ClassNotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); source.writeBaseObject(oos); oos.close(); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); readBaseObject(ois); } /** * @return preferred query execution mode * @see PGProperty#PREFER_QUERY_MODE */ public PreferQueryMode getPreferQueryMode() { return PreferQueryMode.of(PGProperty.PREFER_QUERY_MODE.get(properties)); } /** * @param preferQueryMode extended, simple, extendedForPrepared, or extendedCacheEverything * @see PGProperty#PREFER_QUERY_MODE */ public void setPreferQueryMode(PreferQueryMode preferQueryMode) { PGProperty.PREFER_QUERY_MODE.set(properties, preferQueryMode.value()); } /** * @return connection configuration regarding automatic per-query savepoints * @see PGProperty#AUTOSAVE */ public AutoSave getAutosave() { return AutoSave.of(PGProperty.AUTOSAVE.get(properties)); } /** * @param autoSave connection configuration regarding automatic per-query savepoints * @see PGProperty#AUTOSAVE */ public void setAutosave(AutoSave autoSave) { PGProperty.AUTOSAVE.set(properties, autoSave.value()); } /** * see PGProperty#CLEANUP_SAVEPOINTS * * @return boolean indicating property set */ public boolean getCleanupSavepoints() { return PGProperty.CLEANUP_SAVEPOINTS.getBoolean(properties); } /** * see PGProperty#CLEANUP_SAVEPOINTS * * @param cleanupSavepoints will cleanup savepoints after a successful transaction */ public void setCleanupSavepoints(boolean cleanupSavepoints) { PGProperty.CLEANUP_SAVEPOINTS.set(properties, cleanupSavepoints); } /** * @return boolean indicating property is enabled or not. * @see PGProperty#REWRITE_BATCHED_INSERTS */ public boolean getReWriteBatchedInserts() { return PGProperty.REWRITE_BATCHED_INSERTS.getBoolean(properties); } /** * @param reWrite boolean value to set the property in the properties collection * @see PGProperty#REWRITE_BATCHED_INSERTS */ public void setReWriteBatchedInserts(boolean reWrite) { PGProperty.REWRITE_BATCHED_INSERTS.set(properties, reWrite); } /** * @return boolean indicating property is enabled or not. * @see PGProperty#HIDE_UNPRIVILEGED_OBJECTS */ public boolean getHideUnprivilegedObjects() { return PGProperty.HIDE_UNPRIVILEGED_OBJECTS.getBoolean(properties); } /** * @param hideUnprivileged boolean value to set the property in the properties collection * @see PGProperty#HIDE_UNPRIVILEGED_OBJECTS */ public void setHideUnprivilegedObjects(boolean hideUnprivileged) { PGProperty.HIDE_UNPRIVILEGED_OBJECTS.set(properties, hideUnprivileged); } public String getMaxResultBuffer() { return PGProperty.MAX_RESULT_BUFFER.get(properties); } public void setMaxResultBuffer(String maxResultBuffer) { PGProperty.MAX_RESULT_BUFFER.set(properties, maxResultBuffer); } //#if mvn.project.property.postgresql.jdbc.spec >= "JDBC4.1" @Override //#endif public java.util.logging.Logger getParentLogger() { return Logger.getLogger("org.postgresql"); } public String getXmlFactoryFactory() { return PGProperty.XML_FACTORY_FACTORY.get(properties); } public void setXmlFactoryFactory(String xmlFactoryFactory) { PGProperty.XML_FACTORY_FACTORY.set(properties, xmlFactoryFactory); } /* * Alias methods below, these are to help with ease-of-use with other database tools / frameworks * which expect normal java bean getters / setters to exist for the property names. */ public boolean isSsl() { return getSsl(); } public String getSslfactoryarg() { return getSslFactoryArg(); } public void setSslfactoryarg(final String arg) { setSslFactoryArg(arg); } public String getSslcert() { return getSslCert(); } public void setSslcert(final String file) { setSslCert(file); } public String getSslmode() { return getSslMode(); } public void setSslmode(final String mode) { setSslMode(mode); } public String getSslhostnameverifier() { return getSslHostnameVerifier(); } public void setSslhostnameverifier(final String className) { setSslHostnameVerifier(className); } public String getSslkey() { return getSslKey(); } public void setSslkey(final String file) { setSslKey(file); } public String getSslrootcert() { return getSslRootCert(); } public void setSslrootcert(final String file) { setSslRootCert(file); } public String getSslpasswordcallback() { return getSslPasswordCallback(); } public void setSslpasswordcallback(final String className) { setSslPasswordCallback(className); } public String getSslpassword() { return getSslPassword(); } public void setSslpassword(final String sslpassword) { setSslPassword(sslpassword); } public int getRecvBufferSize() { return getReceiveBufferSize(); } public void setRecvBufferSize(final int nbytes) { setReceiveBufferSize(nbytes); } public boolean isAllowEncodingChanges() { return getAllowEncodingChanges(); } public boolean isLogUnclosedConnections() { return getLogUnclosedConnections(); } public boolean isTcpKeepAlive() { return getTcpKeepAlive(); } public boolean isReadOnly() { return getReadOnly(); } public boolean isDisableColumnSanitiser() { return getDisableColumnSanitiser(); } public boolean isLoadBalanceHosts() { return getLoadBalanceHosts(); } public boolean isCleanupSavePoints() { return getCleanupSavepoints(); } public void setCleanupSavePoints(final boolean cleanupSavepoints) { setCleanupSavepoints(cleanupSavepoints); } public boolean isReWriteBatchedInserts() { return getReWriteBatchedInserts(); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4033_2
crossvul-java_data_good_4362_0
/** * (The MIT License) * * Copyright (c) 2008 - 2011: * * * {Aaron Patterson}[http://tenderlovemaking.com] * * {Mike Dalessio}[http://mike.daless.io] * * {Charles Nutter}[http://blog.headius.com] * * {Sergio Arbeo}[http://www.serabe.com] * * {Patrick Mahoney}[http://polycrystal.org] * * {Yoko Harada}[http://yokolet.blogspot.com] * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package nokogiri; import static nokogiri.internals.NokogiriHelpers.getNokogiriClass; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import javax.xml.transform.Source; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.Verifier; import org.iso_relax.verifier.VerifierConfigurationException; import org.iso_relax.verifier.VerifierFactory; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.anno.JRubyClass; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; import org.w3c.dom.Document; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; /** * Class for Nokogiri::XML::RelaxNG * * @author sergio * @author Yoko Harada <yokolet@gmail.com> */ @JRubyClass(name="Nokogiri::XML::RelaxNG", parent="Nokogiri::XML::Schema") public class XmlRelaxng extends XmlSchema { private Verifier verifier; public XmlRelaxng(Ruby ruby, RubyClass klazz) { super(ruby, klazz); } private void setVerifier(Verifier verifier) { this.verifier = verifier; } static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source, IRubyObject parseOptions) { Ruby runtime = context.getRuntime(); XmlRelaxng xmlRelaxng = (XmlRelaxng) NokogiriService.XML_RELAXNG_ALLOCATOR.allocate(runtime, klazz); if (parseOptions == null) { parseOptions = defaultParseOptions(context.getRuntime()); } xmlRelaxng.setInstanceVariable("@errors", runtime.newEmptyArray()); xmlRelaxng.setInstanceVariable("@parse_options", parseOptions); try { Schema schema = xmlRelaxng.getSchema(source, context); xmlRelaxng.setVerifier(schema.newVerifier()); return xmlRelaxng; } catch (VerifierConfigurationException ex) { throw context.getRuntime().newRuntimeError("Could not parse document: " + ex.getMessage()); } } private Schema getSchema(Source source, ThreadContext context) { InputStream is; VerifierFactory factory = new com.thaiopensource.relaxng.jarv.VerifierFactoryImpl(); if (source instanceof StreamSource) { StreamSource ss = (StreamSource)source; is = ss.getInputStream(); } else { //if (this.source instanceof DOMSource) DOMSource ds = (DOMSource)source; StringWriter xmlAsWriter = new StringWriter(); StreamResult result = new StreamResult(xmlAsWriter); try { TransformerFactory.newInstance().newTransformer().transform(ds, result); } catch (TransformerConfigurationException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } catch (TransformerException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } try { is = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } } try { return factory.compileSchema(is); } catch (VerifierConfigurationException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } catch (SAXException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } catch (IOException ex) { throw context.getRuntime().newIOError(ex.getMessage()); } } @Override protected void setErrorHandler(ErrorHandler errorHandler) { verifier.setErrorHandler(errorHandler); } @Override protected void validate(Document document) throws SAXException, IOException { verifier.verify(document); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4362_0
crossvul-java_data_good_1910_3
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.bosesoundtouch.internal; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import org.openhab.binding.bosesoundtouch.internal.handler.BoseSoundTouchHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * The {@link XMLResponseProcessor} class handles the XML mapping * * @author Christian Niessner - Initial contribution * @author Thomas Traunbauer - Initial contribution */ public class XMLResponseProcessor { private BoseSoundTouchHandler handler; private Map<XMLHandlerState, Map<String, XMLHandlerState>> stateSwitchingMap; public XMLResponseProcessor(BoseSoundTouchHandler handler) { this.handler = handler; init(); } public void handleMessage(String msg) throws SAXException, IOException { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setContentHandler(new XMLResponseHandler(handler, stateSwitchingMap)); reader.parse(new InputSource(new StringReader(msg))); } // initializes our XML parsing state machine private void init() { stateSwitchingMap = new HashMap<>(); Map<String, XMLHandlerState> msgInitMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.INIT, msgInitMap); msgInitMap.put("msg", XMLHandlerState.Msg); msgInitMap.put("SoundTouchSdkInfo", XMLHandlerState.Unprocessed); msgInitMap.put("userActivityUpdate", XMLHandlerState.Unprocessed); // ignored.. Map<String, XMLHandlerState> msgBodyMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.MsgBody, msgBodyMap); msgBodyMap.put("info", XMLHandlerState.Info); msgBodyMap.put("volume", XMLHandlerState.Volume); msgBodyMap.put("presets", XMLHandlerState.Presets); msgBodyMap.put("key", XMLHandlerState.Unprocessed); // only confirmation of our key presses... msgBodyMap.put("status", XMLHandlerState.Unprocessed); // only confirmation of commands sent to device... msgBodyMap.put("zone", XMLHandlerState.Zone); // only confirmation of our key presses... msgBodyMap.put("bass", XMLHandlerState.Bass); msgBodyMap.put("sources", XMLHandlerState.Sources); msgBodyMap.put("bassCapabilities", XMLHandlerState.BassCapabilities); msgBodyMap.put("group", XMLHandlerState.Group); // info message states Map<String, XMLHandlerState> infoMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Info, infoMap); infoMap.put("components", XMLHandlerState.Info); infoMap.put("component", XMLHandlerState.Info); infoMap.put("name", XMLHandlerState.InfoName); infoMap.put("type", XMLHandlerState.InfoType); infoMap.put("componentCategory", XMLHandlerState.Unprocessed); infoMap.put("softwareVersion", XMLHandlerState.InfoFirmwareVersion); infoMap.put("serialNumber", XMLHandlerState.Unprocessed); infoMap.put("networkInfo", XMLHandlerState.Unprocessed); infoMap.put("margeAccountUUID", XMLHandlerState.Unprocessed); infoMap.put("margeURL", XMLHandlerState.Unprocessed); infoMap.put("moduleType", XMLHandlerState.InfoModuleType); infoMap.put("variant", XMLHandlerState.Unprocessed); infoMap.put("variantMode", XMLHandlerState.Unprocessed); infoMap.put("countryCode", XMLHandlerState.Unprocessed); infoMap.put("regionCode", XMLHandlerState.Unprocessed); Map<String, XMLHandlerState> updatesMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Updates, updatesMap); updatesMap.put("clockDisplayUpdated", XMLHandlerState.Unprocessed); // can we get anything useful of that? updatesMap.put("connectionStateUpdated", XMLHandlerState.UnprocessedNoTextExpected); updatesMap.put("infoUpdated", XMLHandlerState.Unprocessed); updatesMap.put("nowPlayingUpdated", XMLHandlerState.MsgBody); updatesMap.put("nowSelectionUpdated", XMLHandlerState.Unprocessed); // TODO this seems to be quite a useful info // what is currently played.. updatesMap.put("recentsUpdated", XMLHandlerState.Unprocessed); updatesMap.put("volumeUpdated", XMLHandlerState.MsgBody); updatesMap.put("zoneUpdated", XMLHandlerState.ZoneUpdated); // just notifies but dosn't provide details updatesMap.put("bassUpdated", XMLHandlerState.BassUpdated); updatesMap.put("presetsUpdated", XMLHandlerState.MsgBody); updatesMap.put("groupUpdated", XMLHandlerState.MsgBody); Map<String, XMLHandlerState> volume = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Volume, volume); volume.put("targetvolume", XMLHandlerState.VolumeTarget); volume.put("actualvolume", XMLHandlerState.VolumeActual); volume.put("muteenabled", XMLHandlerState.VolumeMuteEnabled); Map<String, XMLHandlerState> nowPlayingMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.NowPlaying, nowPlayingMap); nowPlayingMap.put("album", XMLHandlerState.NowPlayingAlbum); nowPlayingMap.put("art", XMLHandlerState.NowPlayingArt); nowPlayingMap.put("artist", XMLHandlerState.NowPlayingArtist); nowPlayingMap.put("ContentItem", XMLHandlerState.ContentItem); nowPlayingMap.put("description", XMLHandlerState.NowPlayingDescription); nowPlayingMap.put("playStatus", XMLHandlerState.NowPlayingPlayStatus); nowPlayingMap.put("rateEnabled", XMLHandlerState.NowPlayingRateEnabled); nowPlayingMap.put("skipEnabled", XMLHandlerState.NowPlayingSkipEnabled); nowPlayingMap.put("skipPreviousEnabled", XMLHandlerState.NowPlayingSkipPreviousEnabled); nowPlayingMap.put("stationLocation", XMLHandlerState.NowPlayingStationLocation); nowPlayingMap.put("stationName", XMLHandlerState.NowPlayingStationName); nowPlayingMap.put("track", XMLHandlerState.NowPlayingTrack); nowPlayingMap.put("connectionStatusInfo", XMLHandlerState.Unprocessed); // TODO active when Source==Bluetooth // TODO active when Source==Pandora and maybe also other sources - seems to be rating related nowPlayingMap.put("time", XMLHandlerState.Unprocessed); nowPlayingMap.put("rating", XMLHandlerState.Unprocessed); nowPlayingMap.put("rateEnabled", XMLHandlerState.Unprocessed); // ContentItem specifies a resource (that also could be bookmarked in a preset) Map<String, XMLHandlerState> contentItemMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.ContentItem, contentItemMap); contentItemMap.put("itemName", XMLHandlerState.ContentItemItemName); contentItemMap.put("containerArt", XMLHandlerState.ContentItemContainerArt); Map<String, XMLHandlerState> presetMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Preset, presetMap); presetMap.put("ContentItem", XMLHandlerState.ContentItem); Map<String, XMLHandlerState> zoneMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Zone, zoneMap); zoneMap.put("member", XMLHandlerState.ZoneMember); Map<String, XMLHandlerState> bassMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Bass, bassMap); bassMap.put("targetbass", XMLHandlerState.BassTarget); bassMap.put("actualbass", XMLHandlerState.BassActual); Map<String, XMLHandlerState> sourceMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Sources, sourceMap); Map<String, XMLHandlerState> bassCapabilitiesMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.BassCapabilities, bassCapabilitiesMap); bassCapabilitiesMap.put("bassAvailable", XMLHandlerState.BassAvailable); bassCapabilitiesMap.put("bassMin", XMLHandlerState.BassMin); bassCapabilitiesMap.put("bassMax", XMLHandlerState.BassMax); bassCapabilitiesMap.put("bassDefault", XMLHandlerState.BassDefault); Map<String, XMLHandlerState> groupsMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Group, groupsMap); groupsMap.put("name", XMLHandlerState.GroupName); groupsMap.put("masterDeviceId", XMLHandlerState.MasterDeviceId); groupsMap.put("roles", XMLHandlerState.Unprocessed); groupsMap.put("senderIPAddress", XMLHandlerState.Unprocessed); groupsMap.put("status", XMLHandlerState.Unprocessed); groupsMap.put("roles", XMLHandlerState.Unprocessed); groupsMap.put("groupRole", XMLHandlerState.Unprocessed); groupsMap.put("deviceId", XMLHandlerState.DeviceId); groupsMap.put("role", XMLHandlerState.Unprocessed); groupsMap.put("ipAddress", XMLHandlerState.DeviceIp); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_3
crossvul-java_data_bad_1910_3
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.bosesoundtouch.internal; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import org.openhab.binding.bosesoundtouch.internal.handler.BoseSoundTouchHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * The {@link XMLResponseProcessor} class handles the XML mapping * * @author Christian Niessner - Initial contribution * @author Thomas Traunbauer - Initial contribution */ public class XMLResponseProcessor { private BoseSoundTouchHandler handler; private Map<XMLHandlerState, Map<String, XMLHandlerState>> stateSwitchingMap; public XMLResponseProcessor(BoseSoundTouchHandler handler) { this.handler = handler; init(); } public void handleMessage(String msg) throws SAXException, IOException { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(new XMLResponseHandler(handler, stateSwitchingMap)); reader.parse(new InputSource(new StringReader(msg))); } // initializes our XML parsing state machine private void init() { stateSwitchingMap = new HashMap<>(); Map<String, XMLHandlerState> msgInitMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.INIT, msgInitMap); msgInitMap.put("msg", XMLHandlerState.Msg); msgInitMap.put("SoundTouchSdkInfo", XMLHandlerState.Unprocessed); msgInitMap.put("userActivityUpdate", XMLHandlerState.Unprocessed); // ignored.. Map<String, XMLHandlerState> msgBodyMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.MsgBody, msgBodyMap); msgBodyMap.put("info", XMLHandlerState.Info); msgBodyMap.put("volume", XMLHandlerState.Volume); msgBodyMap.put("presets", XMLHandlerState.Presets); msgBodyMap.put("key", XMLHandlerState.Unprocessed); // only confirmation of our key presses... msgBodyMap.put("status", XMLHandlerState.Unprocessed); // only confirmation of commands sent to device... msgBodyMap.put("zone", XMLHandlerState.Zone); // only confirmation of our key presses... msgBodyMap.put("bass", XMLHandlerState.Bass); msgBodyMap.put("sources", XMLHandlerState.Sources); msgBodyMap.put("bassCapabilities", XMLHandlerState.BassCapabilities); msgBodyMap.put("group", XMLHandlerState.Group); // info message states Map<String, XMLHandlerState> infoMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Info, infoMap); infoMap.put("components", XMLHandlerState.Info); infoMap.put("component", XMLHandlerState.Info); infoMap.put("name", XMLHandlerState.InfoName); infoMap.put("type", XMLHandlerState.InfoType); infoMap.put("componentCategory", XMLHandlerState.Unprocessed); infoMap.put("softwareVersion", XMLHandlerState.InfoFirmwareVersion); infoMap.put("serialNumber", XMLHandlerState.Unprocessed); infoMap.put("networkInfo", XMLHandlerState.Unprocessed); infoMap.put("margeAccountUUID", XMLHandlerState.Unprocessed); infoMap.put("margeURL", XMLHandlerState.Unprocessed); infoMap.put("moduleType", XMLHandlerState.InfoModuleType); infoMap.put("variant", XMLHandlerState.Unprocessed); infoMap.put("variantMode", XMLHandlerState.Unprocessed); infoMap.put("countryCode", XMLHandlerState.Unprocessed); infoMap.put("regionCode", XMLHandlerState.Unprocessed); Map<String, XMLHandlerState> updatesMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Updates, updatesMap); updatesMap.put("clockDisplayUpdated", XMLHandlerState.Unprocessed); // can we get anything useful of that? updatesMap.put("connectionStateUpdated", XMLHandlerState.UnprocessedNoTextExpected); updatesMap.put("infoUpdated", XMLHandlerState.Unprocessed); updatesMap.put("nowPlayingUpdated", XMLHandlerState.MsgBody); updatesMap.put("nowSelectionUpdated", XMLHandlerState.Unprocessed); // TODO this seems to be quite a useful info // what is currently played.. updatesMap.put("recentsUpdated", XMLHandlerState.Unprocessed); updatesMap.put("volumeUpdated", XMLHandlerState.MsgBody); updatesMap.put("zoneUpdated", XMLHandlerState.ZoneUpdated); // just notifies but dosn't provide details updatesMap.put("bassUpdated", XMLHandlerState.BassUpdated); updatesMap.put("presetsUpdated", XMLHandlerState.MsgBody); updatesMap.put("groupUpdated", XMLHandlerState.MsgBody); Map<String, XMLHandlerState> volume = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Volume, volume); volume.put("targetvolume", XMLHandlerState.VolumeTarget); volume.put("actualvolume", XMLHandlerState.VolumeActual); volume.put("muteenabled", XMLHandlerState.VolumeMuteEnabled); Map<String, XMLHandlerState> nowPlayingMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.NowPlaying, nowPlayingMap); nowPlayingMap.put("album", XMLHandlerState.NowPlayingAlbum); nowPlayingMap.put("art", XMLHandlerState.NowPlayingArt); nowPlayingMap.put("artist", XMLHandlerState.NowPlayingArtist); nowPlayingMap.put("ContentItem", XMLHandlerState.ContentItem); nowPlayingMap.put("description", XMLHandlerState.NowPlayingDescription); nowPlayingMap.put("playStatus", XMLHandlerState.NowPlayingPlayStatus); nowPlayingMap.put("rateEnabled", XMLHandlerState.NowPlayingRateEnabled); nowPlayingMap.put("skipEnabled", XMLHandlerState.NowPlayingSkipEnabled); nowPlayingMap.put("skipPreviousEnabled", XMLHandlerState.NowPlayingSkipPreviousEnabled); nowPlayingMap.put("stationLocation", XMLHandlerState.NowPlayingStationLocation); nowPlayingMap.put("stationName", XMLHandlerState.NowPlayingStationName); nowPlayingMap.put("track", XMLHandlerState.NowPlayingTrack); nowPlayingMap.put("connectionStatusInfo", XMLHandlerState.Unprocessed); // TODO active when Source==Bluetooth // TODO active when Source==Pandora and maybe also other sources - seems to be rating related nowPlayingMap.put("time", XMLHandlerState.Unprocessed); nowPlayingMap.put("rating", XMLHandlerState.Unprocessed); nowPlayingMap.put("rateEnabled", XMLHandlerState.Unprocessed); // ContentItem specifies a resource (that also could be bookmarked in a preset) Map<String, XMLHandlerState> contentItemMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.ContentItem, contentItemMap); contentItemMap.put("itemName", XMLHandlerState.ContentItemItemName); contentItemMap.put("containerArt", XMLHandlerState.ContentItemContainerArt); Map<String, XMLHandlerState> presetMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Preset, presetMap); presetMap.put("ContentItem", XMLHandlerState.ContentItem); Map<String, XMLHandlerState> zoneMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Zone, zoneMap); zoneMap.put("member", XMLHandlerState.ZoneMember); Map<String, XMLHandlerState> bassMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Bass, bassMap); bassMap.put("targetbass", XMLHandlerState.BassTarget); bassMap.put("actualbass", XMLHandlerState.BassActual); Map<String, XMLHandlerState> sourceMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Sources, sourceMap); Map<String, XMLHandlerState> bassCapabilitiesMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.BassCapabilities, bassCapabilitiesMap); bassCapabilitiesMap.put("bassAvailable", XMLHandlerState.BassAvailable); bassCapabilitiesMap.put("bassMin", XMLHandlerState.BassMin); bassCapabilitiesMap.put("bassMax", XMLHandlerState.BassMax); bassCapabilitiesMap.put("bassDefault", XMLHandlerState.BassDefault); Map<String, XMLHandlerState> groupsMap = new HashMap<>(); stateSwitchingMap.put(XMLHandlerState.Group, groupsMap); groupsMap.put("name", XMLHandlerState.GroupName); groupsMap.put("masterDeviceId", XMLHandlerState.MasterDeviceId); groupsMap.put("roles", XMLHandlerState.Unprocessed); groupsMap.put("senderIPAddress", XMLHandlerState.Unprocessed); groupsMap.put("status", XMLHandlerState.Unprocessed); groupsMap.put("roles", XMLHandlerState.Unprocessed); groupsMap.put("groupRole", XMLHandlerState.Unprocessed); groupsMap.put("deviceId", XMLHandlerState.DeviceId); groupsMap.put("role", XMLHandlerState.Unprocessed); groupsMap.put("ipAddress", XMLHandlerState.DeviceIp); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_3
crossvul-java_data_bad_1969_1
// Copyright (C) 2012 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.json; import static com.google.json.JsonSanitizer.DEFAULT_NESTING_DEPTH; import static com.google.json.JsonSanitizer.sanitize; import java.util.logging.Level; import java.util.logging.Logger; import junit.framework.TestCase; import org.junit.Test; @SuppressWarnings("javadoc") public final class JsonSanitizerTest extends TestCase { private static void assertSanitized(String golden, String input) { assertSanitized(golden, input, DEFAULT_NESTING_DEPTH); } private static void assertSanitized(String golden, String input, int maximumNestingDepth) { String actual = sanitize(input, maximumNestingDepth); assertEquals(input, golden, actual); if (actual.equals(input)) { assertSame(input, input, actual); } } private static void assertSanitized(String sanitary) { assertSanitized(sanitary, sanitary); } @Test public static final void testSanitize() { // On the left is the sanitized output, and on the right the input. // If there is a single string, then the input is fine as-is. assertSanitized("null", null); assertSanitized("null", ""); assertSanitized("null"); assertSanitized("false"); assertSanitized("true"); assertSanitized(" false "); assertSanitized(" false"); assertSanitized("false\n"); assertSanitized("false", "false,true"); assertSanitized("\"foo\""); assertSanitized("\"foo\"", "'foo'"); assertSanitized( "\"\\u003cscript>foo()\\u003c/script>\"", "\"<script>foo()</script>\""); assertSanitized("\"\\u003c/SCRIPT\\n>\"", "\"</SCRIPT\n>\""); assertSanitized("\"\\u003c/ScRIpT\"", "\"</ScRIpT\""); // \u0130 is a Turkish dotted upper-case 'I' so the lower case version of // the tag name is "script". assertSanitized("\"\\u003c/ScR\u0130pT\"", "\"</ScR\u0130pT\""); assertSanitized("\"<b>Hello</b>\""); assertSanitized("\"<s>Hello</s>\""); assertSanitized("\"<[[\\u005d]>\"", "'<[[]]>'"); assertSanitized("\"\\u005d]>\"", "']]>'"); assertSanitized("[[0]]", "[[0]]>"); assertSanitized("[1,-1,0.0,-0.5,1e2]", "[1,-1,0.0,-0.5,1e2,"); assertSanitized("[1,2,3]", "[1,2,3,]"); assertSanitized("[1,null,3]", "[1,,3,]"); assertSanitized("[1 ,2 ,3]", "[1 2 3]"); assertSanitized("{ \"foo\": \"bar\" }"); assertSanitized("{ \"foo\": \"bar\" }", "{ \"foo\": \"bar\", }"); assertSanitized("{\"foo\":\"bar\"}", "{\"foo\",\"bar\"}"); assertSanitized("{ \"foo\": \"bar\" }", "{ foo: \"bar\" }"); assertSanitized("{ \"foo\": \"bar\"}", "{ foo: 'bar"); assertSanitized("{ \"foo\": [\"bar\"]}", "{ foo: ['bar"); assertSanitized("false", "// comment\nfalse"); assertSanitized("false", "false// comment"); assertSanitized("false", "false// comment\n"); assertSanitized("false", "false/* comment */"); assertSanitized("false", "false/* comment *"); assertSanitized("false", "false/* comment "); assertSanitized("false", "/*/true**/false"); assertSanitized("1"); assertSanitized("-1"); assertSanitized("1.0"); assertSanitized("-1.0"); assertSanitized("1.05"); assertSanitized("427.0953333"); assertSanitized("6.0221412927e+23"); assertSanitized("6.0221412927e23"); assertSanitized("6.0221412927e0", "6.0221412927e"); assertSanitized("6.0221412927e-0", "6.0221412927e-"); assertSanitized("6.0221412927e+0", "6.0221412927e+"); assertSanitized("1.660538920287695E-24"); assertSanitized("-6.02e-23"); assertSanitized("1.0", "1."); assertSanitized("0.5", ".5"); assertSanitized("-0.5", "-.5"); assertSanitized("0.5", "+.5"); assertSanitized("0.5e2", "+.5e2"); assertSanitized("1.5e+2", "+1.5e+2"); assertSanitized("0.5e-2", "+.5e-2"); assertSanitized("{\"0\":0}", "{0:0}"); assertSanitized("{\"0\":0}", "{-0:0}"); assertSanitized("{\"0\":0}", "{+0:0}"); assertSanitized("{\"1\":0}", "{1.0:0}"); assertSanitized("{\"1\":0}", "{1.:0}"); assertSanitized("{\"0.5\":0}", "{.5:0}"); assertSanitized("{\"-0.5\":0}", "{-.5:0}"); assertSanitized("{\"0.5\":0}", "{+.5:0}"); assertSanitized("{\"50\":0}", "{+.5e2:0}"); assertSanitized("{\"150\":0}", "{+1.5e+2:0}"); assertSanitized("{\"0.1\":0}", "{+.1:0}"); assertSanitized("{\"0.01\":0}", "{+.01:0}"); assertSanitized("{\"0.005\":0}", "{+.5e-2:0}"); assertSanitized("{\"1e+101\":0}", "{10e100:0}"); assertSanitized("{\"1e-99\":0}", "{10e-100:0}"); assertSanitized("{\"1.05e-99\":0}", "{10.5e-100:0}"); assertSanitized("{\"1.05e-99\":0}", "{10.500e-100:0}"); assertSanitized("{\"1.234e+101\":0}", "{12.34e100:0}"); assertSanitized("{\"1.234e-102\":0}", "{.01234e-100:0}"); assertSanitized("{\"1.234e-102\":0}", "{.01234e-100:0}"); assertSanitized("{}"); // Remove grouping parentheses. assertSanitized("{}", "({})"); // Escape code-points and isolated surrogates which are not XML embeddable. assertSanitized("\"\\u0000\\u0008\\u001f\"", "'\u0000\u0008\u001f'"); assertSanitized("\"\ud800\udc00\\udc00\\ud800\"", "'\ud800\udc00\udc00\ud800'"); assertSanitized("\"\ufffd\\ufffe\\uffff\"", "'\ufffd\ufffe\uffff'"); // These control characters should be elided if they appear outside a string // literal. assertSanitized("42", "\uffef\u000042\u0008\ud800\uffff\udc00"); assertSanitized("null", "\uffef\u0000\u0008\ud800\uffff\udc00"); assertSanitized("[null]", "[,]"); assertSanitized("[null]", "[null,]"); assertSanitized("{\"a\":0,\"false\":\"x\",\"\":{\"\":-1}}", "{\"a\":0,false\"x\":{\"\":-1}}"); assertSanitized("[true ,false]", "[true false]"); assertSanitized("[\"\\u00a0\\u1234\"]"); assertSanitized("{\"a\\b\":\"c\"}", "{a\\b\"c"); assertSanitized("{\"a\":\"b\",\"c\":null}", "{\"a\":\"b\",\"c\":"); assertSanitized( "{\"1e0001234567890123456789123456789123456789\":0}", // Exponent way out of representable range in a JS double. "{1e0001234567890123456789123456789123456789:0}" ); // Our octal recoder interprets an octal-like literal that includes a digit '8' or '9' as // decimal. assertSanitized("-16923547559", "-016923547559"); } @Test public static final void testIssue3() { // These triggered index out of bounds and assertion errors. assertSanitized("[{\"\":{}}]", "[{{},\u00E4"); assertSanitized("[{\"\":{}}]", "[{{\u00E4\u00E4},\u00E4"); } @Test public static final void testIssue4() { // Make sure that bare words are quoted. assertSanitized("\"dev\"", "dev"); assertSanitized("\"eval\"", "eval"); assertSanitized("\"comment\"", "comment"); assertSanitized("\"fasle\"", "fasle"); assertSanitized("\"FALSE\"", "FALSE"); assertSanitized("\"dev/comment\"", "dev/comment"); assertSanitized("\"devcomment\"", "dev\\comment"); assertSanitized("\"dev\\ncomment\"", "dev\\ncomment"); assertSanitized("[\"dev\", \"comment\"]", "[dev\\, comment]"); } @Test public static final void testMaximumNestingLevel() { String nestedMaps = "{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}"; String sanitizedNestedMaps = "{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{\"\":{}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}"; boolean exceptionIfTooMuchNesting = false; try { assertSanitized(sanitizedNestedMaps, nestedMaps, DEFAULT_NESTING_DEPTH); } catch (ArrayIndexOutOfBoundsException e) { Logger.getAnonymousLogger().log(Level.FINEST, "Expected exception in testing maximum nesting level", e); exceptionIfTooMuchNesting = true; } assertTrue("Expecting failure for too nested JSON", exceptionIfTooMuchNesting); assertSanitized(sanitizedNestedMaps, nestedMaps, DEFAULT_NESTING_DEPTH + 1); } @Test public static final void testMaximumNestingLevelAssignment() { assertEquals(1, new JsonSanitizer("", Integer.MIN_VALUE).getMaximumNestingDepth()); assertEquals(JsonSanitizer.MAXIMUM_NESTING_DEPTH, new JsonSanitizer("", Integer.MAX_VALUE).getMaximumNestingDepth()); } @Test public static final void testClosedArray() { // Discovered by fuzzer with seed -Dfuzz.seed=df3b4778ce54d00a assertSanitized("-1742461140214282", "\ufeff-01742461140214282]"); } @Test public static final void testIssue13() { assertSanitized( "[ { \"description\": \"aa##############aa\" }, 1 ]", "[ { \"description\": \"aa##############aa\" }, 1 ]"); } @Test public static final void testHtmlParserStateChanges() { assertSanitized("\"\\u003cscript\"", "\"<script\""); assertSanitized("\"\\u003cScript\"", "\"<Script\""); // \u0130 is a Turkish dotted upper-case 'I' so the lower case version of // the tag name is "script". assertSanitized("\"\\u003cScR\u0130pT\"", "\"<ScR\u0130pT\""); assertSanitized("\"\\u003cSCRIPT\\n>\"", "\"<SCRIPT\n>\""); assertSanitized("\"script\"", "<script"); assertSanitized("\"\\u003c!--\"", "\"<!--\""); assertSanitized("-0", "<!--"); assertSanitized("\"--\\u003e\"", "\"-->\""); assertSanitized("-0", "-->"); assertSanitized("\"\\u003c!--\\u003cscript>\"", "\"<!--<script>\""); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1969_1
crossvul-java_data_good_4033_5
/* * Copyright (c) 2020, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.xml; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; /** * Default implementation of PGXmlFactoryFactory that configures each factory per OWASP recommendations. * * @see <a href="https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html">https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html</a> */ public class DefaultPGXmlFactoryFactory implements PGXmlFactoryFactory { public static final DefaultPGXmlFactoryFactory INSTANCE = new DefaultPGXmlFactoryFactory(); private DefaultPGXmlFactoryFactory() { } private DocumentBuilderFactory getDocumentBuilderFactory() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); setFactoryProperties(factory); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); return factory; } @Override public DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { DocumentBuilder builder = getDocumentBuilderFactory().newDocumentBuilder(); builder.setEntityResolver(EmptyStringEntityResolver.INSTANCE); builder.setErrorHandler(NullErrorHandler.INSTANCE); return builder; } @Override public TransformerFactory newTransformerFactory() { TransformerFactory factory = TransformerFactory.newInstance(); setFactoryProperties(factory); return factory; } @Override public SAXTransformerFactory newSAXTransformerFactory() { SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); setFactoryProperties(factory); return factory; } @Override public XMLInputFactory newXMLInputFactory() { XMLInputFactory factory = XMLInputFactory.newInstance(); setPropertyQuietly(factory, XMLInputFactory.SUPPORT_DTD, false); setPropertyQuietly(factory, XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); return factory; } @Override public XMLOutputFactory newXMLOutputFactory() { XMLOutputFactory factory = XMLOutputFactory.newInstance(); return factory; } @Override public XMLReader createXMLReader() throws SAXException { XMLReader factory = XMLReaderFactory.createXMLReader(); setFeatureQuietly(factory, "http://apache.org/xml/features/disallow-doctype-decl", true); setFeatureQuietly(factory, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); setFeatureQuietly(factory, "http://xml.org/sax/features/external-general-entities", false); setFeatureQuietly(factory, "http://xml.org/sax/features/external-parameter-entities", false); factory.setErrorHandler(NullErrorHandler.INSTANCE); return factory; } private static void setFeatureQuietly(Object factory, String name, boolean value) { try { if (factory instanceof DocumentBuilderFactory) { ((DocumentBuilderFactory) factory).setFeature(name, value); } else if (factory instanceof TransformerFactory) { ((TransformerFactory) factory).setFeature(name, value); } else if (factory instanceof XMLReader) { ((XMLReader) factory).setFeature(name, value); } else { throw new Error("Invalid factory class: " + factory.getClass()); } return; } catch (Exception ignore) { } } private static void setAttributeQuietly(Object factory, String name, Object value) { try { if (factory instanceof DocumentBuilderFactory) { ((DocumentBuilderFactory) factory).setAttribute(name, value); } else if (factory instanceof TransformerFactory) { ((TransformerFactory) factory).setAttribute(name, value); } else { throw new Error("Invalid factory class: " + factory.getClass()); } } catch (Exception ignore) { } } private static void setFactoryProperties(Object factory) { setFeatureQuietly(factory, XMLConstants.FEATURE_SECURE_PROCESSING, true); setFeatureQuietly(factory, "http://apache.org/xml/features/disallow-doctype-decl", true); setFeatureQuietly(factory, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false); setFeatureQuietly(factory, "http://xml.org/sax/features/external-general-entities", false); setFeatureQuietly(factory, "http://xml.org/sax/features/external-parameter-entities", false); // Values from XMLConstants inlined for JDK 1.6 compatibility setAttributeQuietly(factory, "http://javax.xml.XMLConstants/property/accessExternalDTD", ""); setAttributeQuietly(factory, "http://javax.xml.XMLConstants/property/accessExternalSchema", ""); setAttributeQuietly(factory, "http://javax.xml.XMLConstants/property/accessExternalStylesheet", ""); } private static void setPropertyQuietly(Object factory, String name, Object value) { try { if (factory instanceof XMLReader) { ((XMLReader) factory).setProperty(name, value); } else if (factory instanceof XMLInputFactory) { ((XMLInputFactory) factory).setProperty(name, value); } else { throw new Error("Invalid factory class: " + factory.getClass()); } } catch (Exception ignore) { } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4033_5
crossvul-java_data_good_4033_6
/* * Copyright (c) 2020, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.xml; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.IOException; import java.io.StringReader; public class EmptyStringEntityResolver implements EntityResolver { public static final EmptyStringEntityResolver INSTANCE = new EmptyStringEntityResolver(); @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4033_6
crossvul-java_data_bad_497_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-611/java/bad_497_0
crossvul-java_data_good_3875_0
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j; import java.io.StringReader; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import org.dom4j.io.SAXReader; import org.dom4j.rule.Pattern; import org.jaxen.VariableContext; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * <code>DocumentHelper</code> is a collection of helper methods for using * DOM4J. * * @author <a href="mailto:jstrachan@apache.org">James Strachan </a> * @version $Revision: 1.26 $ */ @SuppressWarnings("unused") public final class DocumentHelper { private DocumentHelper() { } private static DocumentFactory getDocumentFactory() { return DocumentFactory.getInstance(); } // Static helper methods public static Document createDocument() { return getDocumentFactory().createDocument(); } public static Document createDocument(Element rootElement) { return getDocumentFactory().createDocument(rootElement); } public static Element createElement(QName qname) { return getDocumentFactory().createElement(qname); } public static Element createElement(String name) { return getDocumentFactory().createElement(name); } public static Attribute createAttribute(Element owner, QName qname, String value) { return getDocumentFactory().createAttribute(owner, qname, value); } public static Attribute createAttribute(Element owner, String name, String value) { return getDocumentFactory().createAttribute(owner, name, value); } public static CDATA createCDATA(String text) { return DocumentFactory.getInstance().createCDATA(text); } public static Comment createComment(String text) { return DocumentFactory.getInstance().createComment(text); } public static Text createText(String text) { return DocumentFactory.getInstance().createText(text); } public static Entity createEntity(String name, String text) { return DocumentFactory.getInstance().createEntity(name, text); } public static Namespace createNamespace(String prefix, String uri) { return DocumentFactory.getInstance().createNamespace(prefix, uri); } public static ProcessingInstruction createProcessingInstruction(String pi, String d) { return getDocumentFactory().createProcessingInstruction(pi, d); } public static ProcessingInstruction createProcessingInstruction(String pi, Map<String, String> data) { return getDocumentFactory().createProcessingInstruction(pi, data); } public static QName createQName(String localName, Namespace namespace) { return getDocumentFactory().createQName(localName, namespace); } public static QName createQName(String localName) { return getDocumentFactory().createQName(localName); } /** * <p> * <code>createXPath</code> parses an XPath expression and creates a new * XPath <code>XPath</code> instance using the singleton {@link * DocumentFactory}. * </p> * * @param xpathExpression * is the XPath expression to create * * @return a new <code>XPath</code> instance * * @throws InvalidXPathException * if the XPath expression is invalid */ public static XPath createXPath(String xpathExpression) throws InvalidXPathException { return getDocumentFactory().createXPath(xpathExpression); } /** * <p> * <code>createXPath</code> parses an XPath expression and creates a new * XPath <code>XPath</code> instance using the singleton {@link * DocumentFactory}. * </p> * * @param xpathExpression * is the XPath expression to create * @param context * is the variable context to use when evaluating the XPath * * @return a new <code>XPath</code> instance * * @throws InvalidXPathException * if the XPath expression is invalid */ public static XPath createXPath(String xpathExpression, VariableContext context) throws InvalidXPathException { return getDocumentFactory().createXPath(xpathExpression, context); } /** * <p> * <code>createXPathFilter</code> parses a NodeFilter from the given XPath * filter expression using the singleton {@link DocumentFactory}. XPath * filter expressions occur within XPath expressions such as * <code>self::node()[ filterExpression ]</code> * </p> * * @param xpathFilterExpression * is the XPath filter expression to create * * @return a new <code>NodeFilter</code> instance */ public static NodeFilter createXPathFilter(String xpathFilterExpression) { return getDocumentFactory().createXPathFilter(xpathFilterExpression); } /** * <p> * <code>createPattern</code> parses the given XPath expression to create * an XSLT style {@link Pattern}instance which can then be used in an XSLT * processing model. * </p> * * @param xpathPattern * is the XPath pattern expression to create * * @return a new <code>Pattern</code> instance */ public static Pattern createPattern(String xpathPattern) { return getDocumentFactory().createPattern(xpathPattern); } /** * <p> * <code>selectNodes</code> performs the given XPath expression on the * {@link List}of {@link Node}instances appending all the results together * into a single list. * </p> * * @param xpathFilterExpression * is the XPath filter expression to evaluate * @param nodes * is the list of nodes on which to evalute the XPath * * @return the results of all the XPath evaluations as a single list */ public static List<Node> selectNodes(String xpathFilterExpression, List<Node> nodes) { XPath xpath = createXPath(xpathFilterExpression); return xpath.selectNodes(nodes); } /** * <p> * <code>selectNodes</code> performs the given XPath expression on the * {@link List}of {@link Node}instances appending all the results together * into a single list. * </p> * * @param xpathFilterExpression * is the XPath filter expression to evaluate * @param node * is the Node on which to evalute the XPath * * @return the results of all the XPath evaluations as a single list */ public static List<Node> selectNodes(String xpathFilterExpression, Node node) { XPath xpath = createXPath(xpathFilterExpression); return xpath.selectNodes(node); } /** * <p> * <code>sort</code> sorts the given List of Nodes using an XPath * expression as a {@link java.util.Comparator}. * </p> * * @param list * is the list of Nodes to sort * @param xpathExpression * is the XPath expression used for comparison */ public static void sort(List<Node> list, String xpathExpression) { XPath xpath = createXPath(xpathExpression); xpath.sort(list); } /** * <p> * <code>sort</code> sorts the given List of Nodes using an XPath * expression as a {@link java.util.Comparator}and optionally removing * duplicates. * </p> * * @param list * is the list of Nodes to sort * @param expression * is the XPath expression used for comparison * @param distinct * if true then duplicate values (using the sortXPath for * comparisions) will be removed from the List */ public static void sort(List<Node> list, String expression, boolean distinct) { XPath xpath = createXPath(expression); xpath.sort(list, distinct); } /** * <p> * <code>parseText</code> parses the given text as an XML document and * returns the newly created Document. * </p> * * Loading external DTD and entities is disabled (if it is possible) for security reasons. * * @param text * the XML text to be parsed * * @return a newly parsed Document * * @throws DocumentException * if the document could not be parsed */ public static Document parseText(String text) throws DocumentException { SAXReader reader = SAXReader.createDefault(); String encoding = getEncoding(text); InputSource source = new InputSource(new StringReader(text)); source.setEncoding(encoding); Document result = reader.read(source); // if the XML parser doesn't provide a way to retrieve the encoding, // specify it manually if (result.getXMLEncoding() == null) { result.setXMLEncoding(encoding); } return result; } private static String getEncoding(String text) { String result = null; String xml = text.trim(); if (xml.startsWith("<?xml")) { int end = xml.indexOf("?>"); String sub = xml.substring(0, end); StringTokenizer tokens = new StringTokenizer(sub, " =\"\'"); while (tokens.hasMoreTokens()) { String token = tokens.nextToken(); if ("encoding".equals(token)) { if (tokens.hasMoreTokens()) { result = tokens.nextToken(); } break; } } } return result; } /** * <p> * makeElement * </p> * a helper method which navigates from the given Document or Element node * to some Element using the path expression, creating any necessary * elements along the way. For example the path <code>a/b/c</code> would * get the first child &lt;a&gt; element, which would be created if it did * not exist, then the next child &lt;b&gt; and so on until finally a * &lt;c&gt; element is returned. * * @param source * is the Element or Document to start navigating from * @param path * is a simple path expression, seperated by '/' which denotes * the path from the source to the resulting element such as * a/b/c * * @return the first Element on the given path which either already existed * on the path or were created by this method. */ public static Element makeElement(Branch source, String path) { StringTokenizer tokens = new StringTokenizer(path, "/"); Element parent; if (source instanceof Document) { Document document = (Document) source; parent = document.getRootElement(); // lets throw a NoSuchElementException // if we are given an empty path String name = tokens.nextToken(); if (parent == null) { parent = document.addElement(name); } } else { parent = (Element) source; } Element element = null; while (tokens.hasMoreTokens()) { String name = tokens.nextToken(); if (name.indexOf(':') > 0) { element = parent.element(parent.getQName(name)); } else { element = parent.element(name); } if (element == null) { element = parent.addElement(name); } parent = element; } return element; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-611/java/good_3875_0
crossvul-java_data_bad_1910_13
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.ihc.internal.ws.projectfile; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.io.FileUtils; import org.openhab.binding.ihc.internal.ws.datatypes.WSProjectInfo; import org.openhab.binding.ihc.internal.ws.exeptions.IhcExecption; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Generic methods related to IHC / ELKO project file handling. * * @author Pauli Anttila - Initial contribution */ public class ProjectFileUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ProjectFileUtils.class); /** * Read IHC project file from local file. * * @param filePath File to read. * @return XML document. * @throws IhcExecption when file read fails. */ public static Document readFromFile(String filePath) throws IhcExecption { File fXmlFile = new File(filePath); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); return doc; } catch (IOException | ParserConfigurationException | SAXException e) { throw new IhcExecption(e); } } /** * Save IHC project file to local file. * * @param filePath File path. * @param data Data to write * @throws IhcExecption when file write fails. */ public static void saveToFile(String filePath, byte[] data) throws IhcExecption { try { FileUtils.writeByteArrayToFile(new File(filePath), data); } catch (IOException e) { throw new IhcExecption(e); } } /** * Convert bytes to XML document. * * @return XML document or null if conversion fails. */ public static Document converteBytesToDocument(byte[] data) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); try { DocumentBuilder builder = factory.newDocumentBuilder(); return builder.parse(new ByteArrayInputStream(data)); } catch (ParserConfigurationException | SAXException | IOException e) { LOGGER.warn("Error occured when trying to convert data to XML, reason {}", e.getMessage()); } return null; } /** * Compare XML document header information to project info. * * @return true if information is equal and false if not. */ public static boolean projectEqualsToControllerProject(Document projectfile, WSProjectInfo projectInfo) { if (projectInfo != null) { try { NodeList nodes = projectfile.getElementsByTagName("modified"); if (nodes.getLength() == 1) { Element node = (Element) nodes.item(0); int year = Integer.parseInt(node.getAttribute("year")); int month = Integer.parseInt(node.getAttribute("month")); int day = Integer.parseInt(node.getAttribute("day")); int hour = Integer.parseInt(node.getAttribute("hour")); int minute = Integer.parseInt(node.getAttribute("minute")); LOGGER.debug("Project file from file, date: {}.{}.{} {}:{}", year, month, day, hour, minute); LOGGER.debug("Project file in controller, date: {}.{}.{} {}:{}", projectInfo.getLastmodified().getYear(), projectInfo.getLastmodified().getMonthWithJanuaryAsOne(), projectInfo.getLastmodified().getDay(), projectInfo.getLastmodified().getHours(), projectInfo.getLastmodified().getMinutes()); if (projectInfo.getLastmodified().getYear() == year && projectInfo.getLastmodified().getMonthWithJanuaryAsOne() == month && projectInfo.getLastmodified().getDay() == day && projectInfo.getLastmodified().getHours() == hour && projectInfo.getLastmodified().getMinutes() == minute) { return true; } } } catch (RuntimeException e) { LOGGER.debug("Error occured during project file date comparasion, reason {}.", e.getMessage(), e); // There is no documentation available for XML content. This is part of inessential feature, so do // nothing, but return false } } return false; } /** * Parse all enum values from IHC project file. * * @param doc IHC project file in XML format. * @return enum dictionary. */ public static Map<Integer, List<IhcEnumValue>> parseEnums(Document doc) { Map<Integer, List<IhcEnumValue>> enumDictionary = new HashMap<>(); if (doc != null) { NodeList nodes = doc.getElementsByTagName("enum_definition"); // iterate enum definitions from project for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); int typedefId = Integer.parseInt(element.getAttribute("id").replace("_0x", ""), 16); String enumName = element.getAttribute("name"); List<IhcEnumValue> enumValues = new ArrayList<>(); NodeList name = element.getElementsByTagName("enum_value"); for (int j = 0; j < name.getLength(); j++) { Element val = (Element) name.item(j); int id = Integer.parseInt(val.getAttribute("id").replace("_0x", ""), 16); String n = val.getAttribute("name"); IhcEnumValue enumVal = new IhcEnumValue(id, n); enumValues.add(enumVal); } LOGGER.debug("Enum values found: typedefId={}, name={}: {}", typedefId, enumName, enumValues); enumDictionary.put(typedefId, enumValues); } } return enumDictionary; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_13
crossvul-java_data_bad_1910_0
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.avmfritz.internal.hardware.callbacks; import static org.eclipse.jetty.http.HttpMethod.GET; import java.io.StringReader; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.openhab.binding.avmfritz.internal.dto.DeviceListModel; import org.openhab.binding.avmfritz.internal.handler.AVMFritzBaseBridgeHandler; import org.openhab.binding.avmfritz.internal.hardware.FritzAhaWebInterface; import org.openhab.binding.avmfritz.internal.util.JAXBUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Callback implementation for updating multiple numbers decoded from a xml * response. Supports reauthorization. * * @author Robert Bausdorf - Initial contribution * @author Christoph Weitkamp - Added support for groups */ @NonNullByDefault public class FritzAhaUpdateCallback extends FritzAhaReauthCallback { private final Logger logger = LoggerFactory.getLogger(FritzAhaUpdateCallback.class); private static final String WEBSERVICE_COMMAND = "switchcmd=getdevicelistinfos"; private final AVMFritzBaseBridgeHandler handler; /** * Constructor * * @param webIface Webinterface to FRITZ!Box * @param handler Bridge handler that will update things. */ public FritzAhaUpdateCallback(FritzAhaWebInterface webIface, AVMFritzBaseBridgeHandler handler) { super(WEBSERVICE_PATH, WEBSERVICE_COMMAND, webIface, GET, 1); this.handler = handler; } @Override public void execute(int status, String response) { super.execute(status, response); logger.trace("Received State response {}", response); if (isValidRequest()) { try { Unmarshaller unmarshaller = JAXBUtils.JAXBCONTEXT_DEVICES.createUnmarshaller(); DeviceListModel model = (DeviceListModel) unmarshaller.unmarshal(new StringReader(response)); if (model != null) { handler.onDeviceListAdded(model.getDevicelist()); } else { logger.debug("no model in response"); } handler.setStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null); } catch (JAXBException e) { logger.error("Exception creating Unmarshaller: {}", e.getLocalizedMessage(), e); handler.setStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getLocalizedMessage()); } } else { logger.debug("request is invalid: {}", status); handler.setStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Request is invalid"); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_0
crossvul-java_data_bad_4290_6
/* * file: GanttProjectReader.java * author: Jon Iles * copyright: (c) Packwood Software 2017 * date: 22 March 2017 */ /* * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ package net.sf.mpxj.ganttproject; import java.io.InputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXSource; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import net.sf.mpxj.ChildTaskContainer; import net.sf.mpxj.ConstraintType; import net.sf.mpxj.CustomField; import net.sf.mpxj.Day; import net.sf.mpxj.Duration; import net.sf.mpxj.EventManager; import net.sf.mpxj.FieldType; import net.sf.mpxj.MPXJException; import net.sf.mpxj.Priority; import net.sf.mpxj.ProjectCalendar; import net.sf.mpxj.ProjectCalendarException; import net.sf.mpxj.ProjectCalendarHours; import net.sf.mpxj.ProjectCalendarWeek; import net.sf.mpxj.ProjectConfig; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.ProjectProperties; import net.sf.mpxj.Rate; import net.sf.mpxj.Relation; import net.sf.mpxj.RelationType; import net.sf.mpxj.Resource; import net.sf.mpxj.ResourceAssignment; import net.sf.mpxj.ResourceField; import net.sf.mpxj.Task; import net.sf.mpxj.TimeUnit; import net.sf.mpxj.common.DateHelper; import net.sf.mpxj.common.NumberHelper; import net.sf.mpxj.common.Pair; import net.sf.mpxj.common.ResourceFieldLists; import net.sf.mpxj.common.TaskFieldLists; import net.sf.mpxj.ganttproject.schema.Allocation; import net.sf.mpxj.ganttproject.schema.Allocations; import net.sf.mpxj.ganttproject.schema.Calendars; import net.sf.mpxj.ganttproject.schema.CustomPropertyDefinition; import net.sf.mpxj.ganttproject.schema.CustomResourceProperty; import net.sf.mpxj.ganttproject.schema.CustomTaskProperty; import net.sf.mpxj.ganttproject.schema.DayTypes; import net.sf.mpxj.ganttproject.schema.DefaultWeek; import net.sf.mpxj.ganttproject.schema.Depend; import net.sf.mpxj.ganttproject.schema.Project; import net.sf.mpxj.ganttproject.schema.Resources; import net.sf.mpxj.ganttproject.schema.Role; import net.sf.mpxj.ganttproject.schema.Roles; import net.sf.mpxj.ganttproject.schema.Taskproperty; import net.sf.mpxj.ganttproject.schema.Tasks; import net.sf.mpxj.listener.ProjectListener; import net.sf.mpxj.reader.AbstractProjectReader; /** * This class creates a new ProjectFile instance by reading a GanttProject file. */ public final class GanttProjectReader extends AbstractProjectReader { /** * {@inheritDoc} */ @Override public void addProjectListener(ProjectListener listener) { if (m_projectListeners == null) { m_projectListeners = new ArrayList<>(); } m_projectListeners.add(listener); } /** * {@inheritDoc} */ @Override public ProjectFile read(InputStream stream) throws MPXJException { try { m_projectFile = new ProjectFile(); m_eventManager = m_projectFile.getEventManager(); m_resourcePropertyDefinitions = new HashMap<>(); m_taskPropertyDefinitions = new HashMap<>(); m_roleDefinitions = new HashMap<>(); m_dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'"); ProjectConfig config = m_projectFile.getProjectConfig(); config.setAutoResourceUniqueID(false); config.setAutoTaskUniqueID(false); config.setAutoOutlineLevel(true); config.setAutoOutlineNumber(true); config.setAutoWBS(true); m_projectFile.getProjectProperties().setFileApplication("GanttProject"); m_projectFile.getProjectProperties().setFileType("GAN"); m_eventManager.addProjectListeners(m_projectListeners); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); SAXSource doc = new SAXSource(xmlReader, new InputSource(stream)); if (CONTEXT == null) { throw CONTEXT_EXCEPTION; } Unmarshaller unmarshaller = CONTEXT.createUnmarshaller(); Project ganttProject = (Project) unmarshaller.unmarshal(doc); readProjectProperties(ganttProject); readCalendars(ganttProject); readResources(ganttProject); readTasks(ganttProject); readRelationships(ganttProject); readResourceAssignments(ganttProject); // // Ensure that the unique ID counters are correct // config.updateUniqueCounters(); return m_projectFile; } catch (ParserConfigurationException ex) { throw new MPXJException("Failed to parse file", ex); } catch (JAXBException ex) { throw new MPXJException("Failed to parse file", ex); } catch (SAXException ex) { throw new MPXJException("Failed to parse file", ex); } finally { m_projectFile = null; m_mpxjCalendar = null; m_eventManager = null; m_projectListeners = null; m_localeDateFormat = null; m_resourcePropertyDefinitions = null; m_taskPropertyDefinitions = null; m_roleDefinitions = null; } } /** * This method extracts project properties from a GanttProject file. * * @param ganttProject GanttProject file */ private void readProjectProperties(Project ganttProject) { ProjectProperties mpxjProperties = m_projectFile.getProjectProperties(); mpxjProperties.setName(ganttProject.getName()); mpxjProperties.setCompany(ganttProject.getCompany()); mpxjProperties.setDefaultDurationUnits(TimeUnit.DAYS); String locale = ganttProject.getLocale(); if (locale == null) { locale = "en_US"; } m_localeDateFormat = DateFormat.getDateInstance(DateFormat.SHORT, new Locale(locale)); } /** * This method extracts calendar data from a GanttProject file. * * @param ganttProject Root node of the GanttProject file */ private void readCalendars(Project ganttProject) { m_mpxjCalendar = m_projectFile.addCalendar(); m_mpxjCalendar.setName(ProjectCalendar.DEFAULT_BASE_CALENDAR_NAME); Calendars gpCalendar = ganttProject.getCalendars(); setWorkingDays(m_mpxjCalendar, gpCalendar); setExceptions(m_mpxjCalendar, gpCalendar); m_eventManager.fireCalendarReadEvent(m_mpxjCalendar); } /** * Add working days and working time to a calendar. * * @param mpxjCalendar MPXJ calendar * @param gpCalendar GanttProject calendar */ private void setWorkingDays(ProjectCalendar mpxjCalendar, Calendars gpCalendar) { DayTypes dayTypes = gpCalendar.getDayTypes(); DefaultWeek defaultWeek = dayTypes.getDefaultWeek(); if (defaultWeek == null) { mpxjCalendar.setWorkingDay(Day.SUNDAY, false); mpxjCalendar.setWorkingDay(Day.MONDAY, true); mpxjCalendar.setWorkingDay(Day.TUESDAY, true); mpxjCalendar.setWorkingDay(Day.WEDNESDAY, true); mpxjCalendar.setWorkingDay(Day.THURSDAY, true); mpxjCalendar.setWorkingDay(Day.FRIDAY, true); mpxjCalendar.setWorkingDay(Day.SATURDAY, false); } else { mpxjCalendar.setWorkingDay(Day.MONDAY, isWorkingDay(defaultWeek.getMon())); mpxjCalendar.setWorkingDay(Day.TUESDAY, isWorkingDay(defaultWeek.getTue())); mpxjCalendar.setWorkingDay(Day.WEDNESDAY, isWorkingDay(defaultWeek.getWed())); mpxjCalendar.setWorkingDay(Day.THURSDAY, isWorkingDay(defaultWeek.getThu())); mpxjCalendar.setWorkingDay(Day.FRIDAY, isWorkingDay(defaultWeek.getFri())); mpxjCalendar.setWorkingDay(Day.SATURDAY, isWorkingDay(defaultWeek.getSat())); mpxjCalendar.setWorkingDay(Day.SUNDAY, isWorkingDay(defaultWeek.getSun())); } for (Day day : Day.values()) { if (mpxjCalendar.isWorkingDay(day)) { ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day); hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING); hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON); } } } /** * Returns true if the flag indicates a working day. * * @param value flag value * @return true if this is a working day */ private boolean isWorkingDay(Integer value) { return NumberHelper.getInt(value) == 0; } /** * Add exceptions to the calendar. * * @param mpxjCalendar MPXJ calendar * @param gpCalendar GanttProject calendar */ private void setExceptions(ProjectCalendar mpxjCalendar, Calendars gpCalendar) { List<net.sf.mpxj.ganttproject.schema.Date> dates = gpCalendar.getDate(); for (net.sf.mpxj.ganttproject.schema.Date date : dates) { addException(mpxjCalendar, date); } } /** * Add a single exception to a calendar. * * @param mpxjCalendar MPXJ calendar * @param date calendar exception */ private void addException(ProjectCalendar mpxjCalendar, net.sf.mpxj.ganttproject.schema.Date date) { String year = date.getYear(); if (year == null || year.isEmpty()) { // In order to process recurring exceptions using MPXJ, we need a start and end date // to constrain the number of dates we generate. // May need to pre-process the tasks in order to calculate a start and finish date. // TODO: handle recurring exceptions } else { Calendar calendar = DateHelper.popCalendar(); calendar.set(Calendar.YEAR, Integer.parseInt(year)); calendar.set(Calendar.MONTH, NumberHelper.getInt(date.getMonth())); calendar.set(Calendar.DAY_OF_MONTH, NumberHelper.getInt(date.getDate())); Date exceptionDate = calendar.getTime(); DateHelper.pushCalendar(calendar); ProjectCalendarException exception = mpxjCalendar.addCalendarException(exceptionDate, exceptionDate); // TODO: not sure how NEUTRAL should be handled if ("WORKING_DAY".equals(date.getType())) { exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING); exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON); } } } /** * This method extracts resource data from a GanttProject file. * * @param ganttProject parent node for resources */ private void readResources(Project ganttProject) { Resources resources = ganttProject.getResources(); readResourceCustomPropertyDefinitions(resources); readRoleDefinitions(ganttProject); for (net.sf.mpxj.ganttproject.schema.Resource gpResource : resources.getResource()) { readResource(gpResource); } } /** * Read custom property definitions for resources. * * @param gpResources GanttProject resources */ private void readResourceCustomPropertyDefinitions(Resources gpResources) { CustomField field = m_projectFile.getCustomFields().getCustomField(ResourceField.TEXT1); field.setAlias("Phone"); for (CustomPropertyDefinition definition : gpResources.getCustomPropertyDefinition()) { // // Find the next available field of the correct type. // String type = definition.getType(); FieldType fieldType = RESOURCE_PROPERTY_TYPES.get(type).getField(); // // If we have run out of fields of the right type, try using a text field. // if (fieldType == null) { fieldType = RESOURCE_PROPERTY_TYPES.get("text").getField(); } // // If we actually have a field available, set the alias to match // the name used in GanttProject. // if (fieldType != null) { field = m_projectFile.getCustomFields().getCustomField(fieldType); field.setAlias(definition.getName()); String defaultValue = definition.getDefaultValue(); if (defaultValue != null && defaultValue.isEmpty()) { defaultValue = null; } m_resourcePropertyDefinitions.put(definition.getId(), new Pair<>(fieldType, defaultValue)); } } } /** * Read custom property definitions for tasks. * * @param gpTasks GanttProject tasks */ private void readTaskCustomPropertyDefinitions(Tasks gpTasks) { for (Taskproperty definition : gpTasks.getTaskproperties().getTaskproperty()) { // // Ignore everything but custom values // if (!"custom".equals(definition.getType())) { continue; } // // Find the next available field of the correct type. // String type = definition.getValuetype(); FieldType fieldType = TASK_PROPERTY_TYPES.get(type).getField(); // // If we have run out of fields of the right type, try using a text field. // if (fieldType == null) { fieldType = TASK_PROPERTY_TYPES.get("text").getField(); } // // If we actually have a field available, set the alias to match // the name used in GanttProject. // if (fieldType != null) { CustomField field = m_projectFile.getCustomFields().getCustomField(fieldType); field.setAlias(definition.getName()); String defaultValue = definition.getDefaultvalue(); if (defaultValue != null && defaultValue.isEmpty()) { defaultValue = null; } m_taskPropertyDefinitions.put(definition.getId(), new Pair<>(fieldType, defaultValue)); } } } /** * Read the role definitions from a GanttProject project. * * @param gpProject GanttProject project */ private void readRoleDefinitions(Project gpProject) { m_roleDefinitions.put("Default:1", "project manager"); for (Roles roles : gpProject.getRoles()) { if ("Default".equals(roles.getRolesetName())) { continue; } for (Role role : roles.getRole()) { m_roleDefinitions.put(role.getId(), role.getName()); } } } /** * This method extracts data for a single resource from a GanttProject file. * * @param gpResource resource data */ private void readResource(net.sf.mpxj.ganttproject.schema.Resource gpResource) { Resource mpxjResource = m_projectFile.addResource(); mpxjResource.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpResource.getId()) + 1)); mpxjResource.setName(gpResource.getName()); mpxjResource.setEmailAddress(gpResource.getContacts()); mpxjResource.setText(1, gpResource.getPhone()); mpxjResource.setGroup(m_roleDefinitions.get(gpResource.getFunction())); net.sf.mpxj.ganttproject.schema.Rate gpRate = gpResource.getRate(); if (gpRate != null) { mpxjResource.setStandardRate(new Rate(gpRate.getValueAttribute(), TimeUnit.DAYS)); } readResourceCustomFields(gpResource, mpxjResource); m_eventManager.fireResourceReadEvent(mpxjResource); } /** * Read custom fields for a GanttProject resource. * * @param gpResource GanttProject resource * @param mpxjResource MPXJ Resource instance */ private void readResourceCustomFields(net.sf.mpxj.ganttproject.schema.Resource gpResource, Resource mpxjResource) { // // Populate custom field default values // Map<FieldType, Object> customFields = new HashMap<>(); for (Pair<FieldType, String> definition : m_resourcePropertyDefinitions.values()) { customFields.put(definition.getFirst(), definition.getSecond()); } // // Update with custom field actual values // for (CustomResourceProperty property : gpResource.getCustomProperty()) { Pair<FieldType, String> definition = m_resourcePropertyDefinitions.get(property.getDefinitionId()); if (definition != null) { // // Retrieve the value. If it is empty, use the default. // String value = property.getValueAttribute(); if (value.isEmpty()) { value = null; } // // If we have a value,convert it to the correct type // if (value != null) { Object result; switch (definition.getFirst().getDataType()) { case NUMERIC: { if (value.indexOf('.') == -1) { result = Integer.valueOf(value); } else { result = Double.valueOf(value); } break; } case DATE: { try { result = m_localeDateFormat.parse(value); } catch (ParseException ex) { result = null; } break; } case BOOLEAN: { result = Boolean.valueOf(value.equals("true")); break; } default: { result = value; break; } } if (result != null) { customFields.put(definition.getFirst(), result); } } } } for (Map.Entry<FieldType, Object> item : customFields.entrySet()) { if (item.getValue() != null) { mpxjResource.set(item.getKey(), item.getValue()); } } } /** * Read custom fields for a GanttProject task. * * @param gpTask GanttProject task * @param mpxjTask MPXJ Task instance */ private void readTaskCustomFields(net.sf.mpxj.ganttproject.schema.Task gpTask, Task mpxjTask) { // // Populate custom field default values // Map<FieldType, Object> customFields = new HashMap<>(); for (Pair<FieldType, String> definition : m_taskPropertyDefinitions.values()) { customFields.put(definition.getFirst(), definition.getSecond()); } // // Update with custom field actual values // for (CustomTaskProperty property : gpTask.getCustomproperty()) { Pair<FieldType, String> definition = m_taskPropertyDefinitions.get(property.getTaskpropertyId()); if (definition != null) { // // Retrieve the value. If it is empty, use the default. // String value = property.getValueAttribute(); if (value.isEmpty()) { value = null; } // // If we have a value,convert it to the correct type // if (value != null) { Object result; switch (definition.getFirst().getDataType()) { case NUMERIC: { if (value.indexOf('.') == -1) { result = Integer.valueOf(value); } else { result = Double.valueOf(value); } break; } case DATE: { try { result = m_dateFormat.parse(value); } catch (ParseException ex) { result = null; } break; } case BOOLEAN: { result = Boolean.valueOf(value.equals("true")); break; } default: { result = value; break; } } if (result != null) { customFields.put(definition.getFirst(), result); } } } } for (Map.Entry<FieldType, Object> item : customFields.entrySet()) { if (item.getValue() != null) { mpxjTask.set(item.getKey(), item.getValue()); } } } /** * Read the top level tasks from GanttProject. * * @param gpProject GanttProject project */ private void readTasks(Project gpProject) { Tasks tasks = gpProject.getTasks(); readTaskCustomPropertyDefinitions(tasks); for (net.sf.mpxj.ganttproject.schema.Task task : tasks.getTask()) { readTask(m_projectFile, task); } } /** * Recursively read a task, and any sub tasks. * * @param mpxjParent Parent for the MPXJ tasks * @param gpTask GanttProject task */ private void readTask(ChildTaskContainer mpxjParent, net.sf.mpxj.ganttproject.schema.Task gpTask) { Task mpxjTask = mpxjParent.addTask(); mpxjTask.setUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1)); mpxjTask.setName(gpTask.getName()); mpxjTask.setPercentageComplete(gpTask.getComplete()); mpxjTask.setPriority(getPriority(gpTask.getPriority())); mpxjTask.setHyperlink(gpTask.getWebLink()); Duration duration = Duration.getInstance(NumberHelper.getDouble(gpTask.getDuration()), TimeUnit.DAYS); mpxjTask.setDuration(duration); if (duration.getDuration() == 0) { mpxjTask.setMilestone(true); } else { mpxjTask.setStart(gpTask.getStart()); mpxjTask.setFinish(m_mpxjCalendar.getDate(gpTask.getStart(), mpxjTask.getDuration(), false)); } mpxjTask.setConstraintDate(gpTask.getThirdDate()); if (mpxjTask.getConstraintDate() != null) { // TODO: you don't appear to be able to change this setting in GanttProject // task.getThirdDateConstraint() mpxjTask.setConstraintType(ConstraintType.START_NO_EARLIER_THAN); } readTaskCustomFields(gpTask, mpxjTask); m_eventManager.fireTaskReadEvent(mpxjTask); // TODO: read custom values // // Process child tasks // for (net.sf.mpxj.ganttproject.schema.Task childTask : gpTask.getTask()) { readTask(mpxjTask, childTask); } } /** * Given a GanttProject priority value, turn this into an MPXJ Priority instance. * * @param gpPriority GanttProject priority * @return Priority instance */ private Priority getPriority(Integer gpPriority) { int result; if (gpPriority == null) { result = Priority.MEDIUM; } else { int index = gpPriority.intValue(); if (index < 0 || index >= PRIORITY.length) { result = Priority.MEDIUM; } else { result = PRIORITY[index]; } } return Priority.getInstance(result); } /** * Read all task relationships from a GanttProject. * * @param gpProject GanttProject project */ private void readRelationships(Project gpProject) { for (net.sf.mpxj.ganttproject.schema.Task gpTask : gpProject.getTasks().getTask()) { readRelationships(gpTask); } } /** * Read the relationships for an individual GanttProject task. * * @param gpTask GanttProject task */ private void readRelationships(net.sf.mpxj.ganttproject.schema.Task gpTask) { for (Depend depend : gpTask.getDepend()) { Task task1 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(gpTask.getId()) + 1)); Task task2 = m_projectFile.getTaskByUniqueID(Integer.valueOf(NumberHelper.getInt(depend.getId()) + 1)); if (task1 != null && task2 != null) { Duration lag = Duration.getInstance(NumberHelper.getInt(depend.getDifference()), TimeUnit.DAYS); Relation relation = task2.addPredecessor(task1, getRelationType(depend.getType()), lag); m_eventManager.fireRelationReadEvent(relation); } } } /** * Convert a GanttProject task relationship type into an MPXJ RelationType instance. * * @param gpType GanttProject task relation type * @return RelationType instance */ private RelationType getRelationType(Integer gpType) { RelationType result = null; if (gpType != null) { int index = NumberHelper.getInt(gpType); if (index > 0 && index < RELATION.length) { result = RELATION[index]; } } if (result == null) { result = RelationType.FINISH_START; } return result; } /** * Read all resource assignments from a GanttProject project. * * @param gpProject GanttProject project */ private void readResourceAssignments(Project gpProject) { Allocations allocations = gpProject.getAllocations(); if (allocations != null) { for (Allocation allocation : allocations.getAllocation()) { readResourceAssignment(allocation); } } } /** * Read an individual GanttProject resource assignment. * * @param gpAllocation GanttProject resource assignment. */ private void readResourceAssignment(Allocation gpAllocation) { Integer taskID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getTaskId()) + 1); Integer resourceID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getResourceId()) + 1); Task task = m_projectFile.getTaskByUniqueID(taskID); Resource resource = m_projectFile.getResourceByUniqueID(resourceID); if (task != null && resource != null) { ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource); mpxjAssignment.setUnits(gpAllocation.getLoad()); m_eventManager.fireAssignmentReadEvent(mpxjAssignment); } } private ProjectFile m_projectFile; private ProjectCalendar m_mpxjCalendar; private EventManager m_eventManager; private List<ProjectListener> m_projectListeners; private DateFormat m_localeDateFormat; private DateFormat m_dateFormat; private Map<String, Pair<FieldType, String>> m_resourcePropertyDefinitions; private Map<String, Pair<FieldType, String>> m_taskPropertyDefinitions; private Map<String, String> m_roleDefinitions; private static final Map<String, CustomProperty> RESOURCE_PROPERTY_TYPES = new HashMap<>(); static { CustomProperty numeric = new CustomProperty(ResourceFieldLists.CUSTOM_NUMBER); RESOURCE_PROPERTY_TYPES.put("int", numeric); RESOURCE_PROPERTY_TYPES.put("double", numeric); RESOURCE_PROPERTY_TYPES.put("text", new CustomProperty(ResourceFieldLists.CUSTOM_TEXT, 1)); RESOURCE_PROPERTY_TYPES.put("date", new CustomProperty(ResourceFieldLists.CUSTOM_DATE)); RESOURCE_PROPERTY_TYPES.put("boolean", new CustomProperty(ResourceFieldLists.CUSTOM_FLAG)); } private static final Map<String, CustomProperty> TASK_PROPERTY_TYPES = new HashMap<>(); static { CustomProperty numeric = new CustomProperty(TaskFieldLists.CUSTOM_NUMBER); TASK_PROPERTY_TYPES.put("int", numeric); TASK_PROPERTY_TYPES.put("double", numeric); TASK_PROPERTY_TYPES.put("text", new CustomProperty(TaskFieldLists.CUSTOM_TEXT)); TASK_PROPERTY_TYPES.put("date", new CustomProperty(TaskFieldLists.CUSTOM_DATE)); TASK_PROPERTY_TYPES.put("boolean", new CustomProperty(TaskFieldLists.CUSTOM_FLAG)); } private static final int[] PRIORITY = { Priority.LOW, // 0 - Low Priority.MEDIUM, // 1 - Normal Priority.HIGH, // 2 - High Priority.LOWEST, // 3- Lowest Priority.HIGHEST, // 4 - Highest }; static final RelationType[] RELATION = { null, //0 RelationType.START_START, // 1 - Start Start RelationType.FINISH_START, // 2 - Finish Start RelationType.FINISH_FINISH, // 3 - Finish Finish RelationType.START_FINISH // 4 - Start Finish }; /** * Cached context to minimise construction cost. */ private static JAXBContext CONTEXT; /** * Note any error occurring during context construction. */ private static JAXBException CONTEXT_EXCEPTION; static { try { // // JAXB RI property to speed up construction // System.setProperty("com.sun.xml.bind.v2.runtime.JAXBContextImpl.fastBoot", "true"); // // Construct the context // CONTEXT = JAXBContext.newInstance("net.sf.mpxj.ganttproject.schema", GanttProjectReader.class.getClassLoader()); } catch (JAXBException ex) { CONTEXT_EXCEPTION = ex; CONTEXT = null; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4290_6
crossvul-java_data_bad_4362_0
/** * (The MIT License) * * Copyright (c) 2008 - 2011: * * * {Aaron Patterson}[http://tenderlovemaking.com] * * {Mike Dalessio}[http://mike.daless.io] * * {Charles Nutter}[http://blog.headius.com] * * {Sergio Arbeo}[http://www.serabe.com] * * {Patrick Mahoney}[http://polycrystal.org] * * {Yoko Harada}[http://yokolet.blogspot.com] * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package nokogiri; import static nokogiri.internals.NokogiriHelpers.getNokogiriClass; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import javax.xml.transform.Source; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.iso_relax.verifier.Schema; import org.iso_relax.verifier.Verifier; import org.iso_relax.verifier.VerifierConfigurationException; import org.iso_relax.verifier.VerifierFactory; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.anno.JRubyClass; import org.jruby.runtime.ThreadContext; import org.w3c.dom.Document; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; /** * Class for Nokogiri::XML::RelaxNG * * @author sergio * @author Yoko Harada <yokolet@gmail.com> */ @JRubyClass(name="Nokogiri::XML::RelaxNG", parent="Nokogiri::XML::Schema") public class XmlRelaxng extends XmlSchema { private Verifier verifier; public XmlRelaxng(Ruby ruby, RubyClass klazz) { super(ruby, klazz); } private void setVerifier(Verifier verifier) { this.verifier = verifier; } static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source) { Ruby runtime = context.getRuntime(); XmlRelaxng xmlRelaxng = (XmlRelaxng) NokogiriService.XML_RELAXNG_ALLOCATOR.allocate(runtime, klazz); xmlRelaxng.setInstanceVariable("@errors", runtime.newEmptyArray()); try { Schema schema = xmlRelaxng.getSchema(source, context); xmlRelaxng.setVerifier(schema.newVerifier()); return xmlRelaxng; } catch (VerifierConfigurationException ex) { throw context.getRuntime().newRuntimeError("Could not parse document: " + ex.getMessage()); } } private Schema getSchema(Source source, ThreadContext context) { InputStream is; VerifierFactory factory = new com.thaiopensource.relaxng.jarv.VerifierFactoryImpl(); if (source instanceof StreamSource) { StreamSource ss = (StreamSource)source; is = ss.getInputStream(); } else { //if (this.source instanceof DOMSource) DOMSource ds = (DOMSource)source; StringWriter xmlAsWriter = new StringWriter(); StreamResult result = new StreamResult(xmlAsWriter); try { TransformerFactory.newInstance().newTransformer().transform(ds, result); } catch (TransformerConfigurationException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } catch (TransformerException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } try { is = new ByteArrayInputStream(xmlAsWriter.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } } try { return factory.compileSchema(is); } catch (VerifierConfigurationException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } catch (SAXException ex) { throw context.getRuntime() .newRuntimeError("Could not parse document: "+ex.getMessage()); } catch (IOException ex) { throw context.getRuntime().newIOError(ex.getMessage()); } } @Override protected void setErrorHandler(ErrorHandler errorHandler) { verifier.setErrorHandler(errorHandler); } @Override protected void validate(Document document) throws SAXException, IOException { verifier.verify(document); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4362_0
crossvul-java_data_bad_1910_5
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.denonmarantz.internal.handler; import static org.openhab.binding.denonmarantz.internal.DenonMarantzBindingConstants.*; import java.io.IOException; import java.io.StringReader; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.smarthome.config.core.Configuration; import org.eclipse.smarthome.core.thing.Channel; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.binding.BaseThingHandler; import org.eclipse.smarthome.core.thing.binding.builder.ChannelBuilder; import org.eclipse.smarthome.core.thing.type.ChannelTypeUID; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.openhab.binding.denonmarantz.internal.DenonMarantzState; import org.openhab.binding.denonmarantz.internal.DenonMarantzStateChangedListener; import org.openhab.binding.denonmarantz.internal.UnsupportedCommandTypeException; import org.openhab.binding.denonmarantz.internal.config.DenonMarantzConfiguration; import org.openhab.binding.denonmarantz.internal.connector.DenonMarantzConnector; import org.openhab.binding.denonmarantz.internal.connector.DenonMarantzConnectorFactory; import org.openhab.binding.denonmarantz.internal.connector.http.DenonMarantzHttpConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link DenonMarantzHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Jan-Willem Veldhuis - Initial contribution */ public class DenonMarantzHandler extends BaseThingHandler implements DenonMarantzStateChangedListener { private final Logger logger = LoggerFactory.getLogger(DenonMarantzHandler.class); private static final int RETRY_TIME_SECONDS = 30; private HttpClient httpClient; private DenonMarantzConnector connector; private DenonMarantzConfiguration config; private DenonMarantzConnectorFactory connectorFactory = new DenonMarantzConnectorFactory(); private DenonMarantzState denonMarantzState; private ScheduledFuture<?> retryJob; public DenonMarantzHandler(Thing thing, HttpClient httpClient) { super(thing); this.httpClient = httpClient; } @Override public void handleCommand(ChannelUID channelUID, Command command) { if (connector == null) { return; } if (connector instanceof DenonMarantzHttpConnector && command instanceof RefreshType) { // Refreshing individual channels isn't supported by the Http connector. // The connector refreshes all channels together at the configured polling interval. return; } try { switch (channelUID.getId()) { case CHANNEL_POWER: connector.sendPowerCommand(command, 0); break; case CHANNEL_MAIN_ZONE_POWER: connector.sendPowerCommand(command, 1); break; case CHANNEL_MUTE: connector.sendMuteCommand(command, 1); break; case CHANNEL_MAIN_VOLUME: connector.sendVolumeCommand(command, 1); break; case CHANNEL_MAIN_VOLUME_DB: connector.sendVolumeDbCommand(command, 1); break; case CHANNEL_INPUT: connector.sendInputCommand(command, 1); break; case CHANNEL_SURROUND_PROGRAM: connector.sendSurroundProgramCommand(command); break; case CHANNEL_COMMAND: connector.sendCustomCommand(command); break; case CHANNEL_ZONE2_POWER: connector.sendPowerCommand(command, 2); break; case CHANNEL_ZONE2_MUTE: connector.sendMuteCommand(command, 2); break; case CHANNEL_ZONE2_VOLUME: connector.sendVolumeCommand(command, 2); break; case CHANNEL_ZONE2_VOLUME_DB: connector.sendVolumeDbCommand(command, 2); break; case CHANNEL_ZONE2_INPUT: connector.sendInputCommand(command, 2); break; case CHANNEL_ZONE3_POWER: connector.sendPowerCommand(command, 3); break; case CHANNEL_ZONE3_MUTE: connector.sendMuteCommand(command, 3); break; case CHANNEL_ZONE3_VOLUME: connector.sendVolumeCommand(command, 3); break; case CHANNEL_ZONE3_VOLUME_DB: connector.sendVolumeDbCommand(command, 3); break; case CHANNEL_ZONE3_INPUT: connector.sendInputCommand(command, 3); break; case CHANNEL_ZONE4_POWER: connector.sendPowerCommand(command, 4); break; case CHANNEL_ZONE4_MUTE: connector.sendMuteCommand(command, 4); break; case CHANNEL_ZONE4_VOLUME: connector.sendVolumeCommand(command, 4); break; case CHANNEL_ZONE4_VOLUME_DB: connector.sendVolumeDbCommand(command, 4); break; case CHANNEL_ZONE4_INPUT: connector.sendInputCommand(command, 4); break; default: throw new UnsupportedCommandTypeException(); } } catch (UnsupportedCommandTypeException e) { logger.debug("Unsupported command {} for channel {}", command, channelUID.getId()); } } public boolean checkConfiguration() { // prevent too low values for polling interval if (config.httpPollingInterval < 5) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The polling interval should be at least 5 seconds!"); return false; } // Check zone count is within supported range if (config.getZoneCount() < 1 || config.getZoneCount() > 4) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "This binding supports 1 to 4 zones. Please update the zone count."); return false; } return true; } /** * Try to auto configure the connection type (Telnet or HTTP) * for Things not added through Paper UI. */ private void autoConfigure() { /* * The isTelnet parameter has no default. * When not set we will try to auto-detect the correct values * for isTelnet and zoneCount and update the Thing accordingly. */ if (config.isTelnet() == null) { logger.debug("Trying to auto-detect the connection."); ContentResponse response; boolean telnetEnable = true; int httpPort = 80; boolean httpApiUsable = false; // try to reach the HTTP API at port 80 (most models, except Denon ...H should respond. String host = config.getHost(); try { response = httpClient.newRequest("http://" + host + "/goform/Deviceinfo.xml") .timeout(3, TimeUnit.SECONDS).send(); if (response.getStatus() == HttpURLConnection.HTTP_OK) { logger.debug("We can access the HTTP API, disabling the Telnet mode by default."); telnetEnable = false; httpApiUsable = true; } } catch (InterruptedException | TimeoutException | ExecutionException e) { logger.debug("Error when trying to access AVR using HTTP on port 80, reverting to Telnet mode.", e); } if (telnetEnable) { // the above attempt failed. Let's try on port 8080, as for some models a subset of the HTTP API is // available try { response = httpClient.newRequest("http://" + host + ":8080/goform/Deviceinfo.xml") .timeout(3, TimeUnit.SECONDS).send(); if (response.getStatus() == HttpURLConnection.HTTP_OK) { logger.debug( "This model responds to HTTP port 8080, we use this port to retrieve the number of zones."); httpPort = 8080; httpApiUsable = true; } } catch (InterruptedException | TimeoutException | ExecutionException e) { logger.debug("Additionally tried to connect to port 8080, this also failed", e); } } // default zone count int zoneCount = 2; // try to determine the zone count by checking the Deviceinfo.xml file if (httpApiUsable) { int status = 0; response = null; try { response = httpClient.newRequest("http://" + host + ":" + httpPort + "/goform/Deviceinfo.xml") .timeout(3, TimeUnit.SECONDS).send(); status = response.getStatus(); } catch (InterruptedException | TimeoutException | ExecutionException e) { logger.debug("Failed in fetching the Deviceinfo.xml to determine zone count", e); } if (status == HttpURLConnection.HTTP_OK && response != null) { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = domFactory.newDocumentBuilder(); Document dDoc = builder.parse(new InputSource(new StringReader(response.getContentAsString()))); XPath xPath = XPathFactory.newInstance().newXPath(); Node node = (Node) xPath.evaluate("/Device_Info/DeviceZones/text()", dDoc, XPathConstants.NODE); if (node != null) { String nodeValue = node.getNodeValue(); logger.trace("/Device_Info/DeviceZones/text() = {}", nodeValue); zoneCount = Integer.parseInt(nodeValue); logger.debug("Discovered number of zones: {}", zoneCount); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | NumberFormatException e) { logger.debug("Something went wrong with looking up the zone count in Deviceinfo.xml: {}", e.getMessage()); } } } config.setTelnet(telnetEnable); config.setZoneCount(zoneCount); Configuration configuration = editConfiguration(); configuration.put(PARAMETER_TELNET_ENABLED, telnetEnable); configuration.put(PARAMETER_ZONE_COUNT, zoneCount); updateConfiguration(configuration); } } @Override public void initialize() { cancelRetry(); config = getConfigAs(DenonMarantzConfiguration.class); // Configure Connection type (Telnet/HTTP) and number of zones // Note: this only happens for discovered Things autoConfigure(); if (!checkConfiguration()) { return; } denonMarantzState = new DenonMarantzState(this); configureZoneChannels(); updateStatus(ThingStatus.UNKNOWN); // create connection (either Telnet or HTTP) // ThingStatus ONLINE/OFFLINE is set when AVR status is known. createConnection(); } private void createConnection() { if (connector != null) { connector.dispose(); } connector = connectorFactory.getConnector(config, denonMarantzState, scheduler, httpClient); connector.connect(); } private void cancelRetry() { ScheduledFuture<?> localRetryJob = retryJob; if (localRetryJob != null && !localRetryJob.isDone()) { localRetryJob.cancel(false); } } private void configureZoneChannels() { logger.debug("Configuring zone channels"); Integer zoneCount = config.getZoneCount(); List<Channel> channels = new ArrayList<>(this.getThing().getChannels()); boolean channelsUpdated = false; // construct a set with the existing channel type UIDs, to quickly check Set<String> currentChannels = new HashSet<>(); channels.forEach(channel -> currentChannels.add(channel.getUID().getId())); Set<Entry<String, ChannelTypeUID>> channelsToRemove = new HashSet<>(); if (zoneCount > 1) { List<Entry<String, ChannelTypeUID>> channelsToAdd = new ArrayList<>(ZONE2_CHANNEL_TYPES.entrySet()); if (zoneCount > 2) { // add channels for zone 3 channelsToAdd.addAll(ZONE3_CHANNEL_TYPES.entrySet()); if (zoneCount > 3) { // add channels for zone 4 (more zones currently not supported) channelsToAdd.addAll(ZONE4_CHANNEL_TYPES.entrySet()); } else { channelsToRemove.addAll(ZONE4_CHANNEL_TYPES.entrySet()); } } else { channelsToRemove.addAll(ZONE3_CHANNEL_TYPES.entrySet()); channelsToRemove.addAll(ZONE4_CHANNEL_TYPES.entrySet()); } // filter out the already existing channels channelsToAdd.removeIf(c -> currentChannels.contains(c.getKey())); // add the channels that were not yet added if (!channelsToAdd.isEmpty()) { for (Entry<String, ChannelTypeUID> entry : channelsToAdd) { String itemType = CHANNEL_ITEM_TYPES.get(entry.getKey()); Channel channel = ChannelBuilder .create(new ChannelUID(this.getThing().getUID(), entry.getKey()), itemType) .withType(entry.getValue()).build(); channels.add(channel); } channelsUpdated = true; } else { logger.debug("No zone channels have been added"); } } else { channelsToRemove.addAll(ZONE2_CHANNEL_TYPES.entrySet()); channelsToRemove.addAll(ZONE3_CHANNEL_TYPES.entrySet()); channelsToRemove.addAll(ZONE4_CHANNEL_TYPES.entrySet()); } // filter out the non-existing channels channelsToRemove.removeIf(c -> !currentChannels.contains(c.getKey())); // remove the channels that were not yet added if (!channelsToRemove.isEmpty()) { for (Entry<String, ChannelTypeUID> entry : channelsToRemove) { if (channels.removeIf(c -> (entry.getKey()).equals(c.getUID().getId()))) { logger.trace("Removed channel {}", entry.getKey()); } else { logger.trace("Could NOT remove channel {}", entry.getKey()); } } channelsUpdated = true; } else { logger.debug("No zone channels have been removed"); } // update Thing if channels changed if (channelsUpdated) { updateThing(editThing().withChannels(channels).build()); } } @Override public void dispose() { if (connector != null) { connector.dispose(); connector = null; } cancelRetry(); super.dispose(); } @Override public void channelLinked(ChannelUID channelUID) { super.channelLinked(channelUID); String channelID = channelUID.getId(); if (isLinked(channelID)) { State state = denonMarantzState.getStateForChannelID(channelID); if (state != null) { updateState(channelID, state); } } } @Override public void stateChanged(String channelID, State state) { logger.debug("Received state {} for channelID {}", state, channelID); // Don't flood the log with thing 'updated: ONLINE' each time a single channel changed if (this.getThing().getStatus() != ThingStatus.ONLINE) { updateStatus(ThingStatus.ONLINE); } updateState(channelID, state); } @Override public void connectionError(String errorMessage) { if (this.getThing().getStatus() != ThingStatus.OFFLINE) { // Don't flood the log with thing 'updated: OFFLINE' when already offline updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, errorMessage); } connector.dispose(); retryJob = scheduler.schedule(this::createConnection, RETRY_TIME_SECONDS, TimeUnit.SECONDS); } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_5
crossvul-java_data_bad_4290_2
404: Not Found
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4290_2
crossvul-java_data_bad_1910_8
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.fmiweather.internal.client; import java.io.IOException; import java.io.StringReader; import java.math.BigDecimal; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.stream.IntStream; import javax.xml.namespace.NamespaceContext; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.io.net.http.HttpUtil; import org.openhab.binding.fmiweather.internal.client.FMIResponse.Builder; import org.openhab.binding.fmiweather.internal.client.exception.FMIExceptionReportException; import org.openhab.binding.fmiweather.internal.client.exception.FMIIOException; import org.openhab.binding.fmiweather.internal.client.exception.FMIUnexpectedResponseException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * * Client for accessing FMI weather data * * Subject to license terms https://en.ilmatieteenlaitos.fi/open-data * * * All weather stations: * https://opendata.fmi.fi/wfs/fin?service=WFS&version=2.0.0&request=GetFeature&storedquery_id=fmi::ef::stations&networkid=121& * Networkid parameter isexplained in entries of * https://opendata.fmi.fi/wfs/fin?service=WFS&version=2.0.0&request=GetFeature&storedquery_id=fmi::ef::stations * * @author Sami Salonen - Initial contribution * */ @NonNullByDefault public class Client { private final Logger logger = LoggerFactory.getLogger(Client.class); public static final String WEATHER_STATIONS_URL = "https://opendata.fmi.fi/wfs/fin?service=WFS&version=2.0.0&request=GetFeature&storedquery_id=fmi::ef::stations&networkid=121&"; private static final Map<String, String> NAMESPACES = new HashMap<>(); static { NAMESPACES.put("target", "http://xml.fmi.fi/namespace/om/atmosphericfeatures/1.0"); NAMESPACES.put("gml", "http://www.opengis.net/gml/3.2"); NAMESPACES.put("xlink", "http://www.w3.org/1999/xlink"); NAMESPACES.put("ows", "http://www.opengis.net/ows/1.1"); NAMESPACES.put("gmlcov", "http://www.opengis.net/gmlcov/1.0"); NAMESPACES.put("swe", "http://www.opengis.net/swe/2.0"); NAMESPACES.put("wfs", "http://www.opengis.net/wfs/2.0"); NAMESPACES.put("ef", "http://inspire.ec.europa.eu/schemas/ef/4.0"); } private static final NamespaceContext NAMESPACE_CONTEXT = new NamespaceContext() { @Override public String getNamespaceURI(@Nullable String prefix) { return NAMESPACES.get(prefix); } @SuppressWarnings("rawtypes") @Override public @Nullable Iterator getPrefixes(@Nullable String val) { return null; } @Override public @Nullable String getPrefix(@Nullable String uri) { return null; } }; private DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); private DocumentBuilder documentBuilder; public Client() { documentBuilderFactory.setNamespaceAware(true); try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } /** * Query request and return the data * * @param request request to process * @param timeoutMillis timeout for the http call * @return data corresponding to the query * @throws FMIIOException on all I/O errors * @throws FMIUnexpectedResponseException on all unexpected content errors * @throw FMIExceptionReportException on explicit error responses from the server */ public FMIResponse query(Request request, int timeoutMillis) throws FMIExceptionReportException, FMIUnexpectedResponseException, FMIIOException { try { String url = request.toUrl(); String responseText = HttpUtil.executeUrl("GET", url, timeoutMillis); if (responseText == null) { throw new FMIIOException(String.format("HTTP error with %s", request.toUrl())); } FMIResponse response = parseMultiPointCoverageXml(responseText); logger.debug("Request {} translated to url {}. Response: {}", request, url, response); return response; } catch (IOException e) { throw new FMIIOException(e); } catch (SAXException | XPathExpressionException e) { throw new FMIUnexpectedResponseException(e); } } /** * Query all weather stations * * @param timeoutMillis timeout for the http call * @return locations representing stations * @throws FMIIOException on all I/O errors * @throws FMIUnexpectedResponseException on all unexpected content errors * @throw FMIExceptionReportException on explicit error responses from the server */ public Set<Location> queryWeatherStations(int timeoutMillis) throws FMIIOException, FMIUnexpectedResponseException, FMIExceptionReportException { try { String response = HttpUtil.executeUrl("GET", WEATHER_STATIONS_URL, timeoutMillis); if (response == null) { throw new FMIIOException(String.format("HTTP error with %s", WEATHER_STATIONS_URL)); } return parseStations(response); } catch (IOException e) { throw new FMIIOException(e); } catch (XPathExpressionException | SAXException e) { throw new FMIUnexpectedResponseException(e); } } private Set<Location> parseStations(String response) throws FMIExceptionReportException, FMIUnexpectedResponseException, SAXException, IOException, XPathExpressionException { Document document = documentBuilder.parse(new InputSource(new StringReader(response))); XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(NAMESPACE_CONTEXT); boolean isExceptionReport = ((Node) xPath.compile("/ows:ExceptionReport").evaluate(document, XPathConstants.NODE)) != null; if (isExceptionReport) { Node exceptionCode = (Node) xPath.compile("/ows:ExceptionReport/ows:Exception/@exceptionCode") .evaluate(document, XPathConstants.NODE); String[] exceptionText = queryNodeValues(xPath.compile("//ows:ExceptionText/text()"), document); throw new FMIExceptionReportException(exceptionCode.getNodeValue(), exceptionText); } String[] fmisids = queryNodeValues( xPath.compile( "/wfs:FeatureCollection/wfs:member/ef:EnvironmentalMonitoringFacility/gml:identifier/text()"), document); String[] names = queryNodeValues(xPath.compile( "/wfs:FeatureCollection/wfs:member/ef:EnvironmentalMonitoringFacility/gml:name[@codeSpace='http://xml.fmi.fi/namespace/locationcode/name']/text()"), document); String[] representativePoints = queryNodeValues(xPath.compile( "/wfs:FeatureCollection/wfs:member/ef:EnvironmentalMonitoringFacility/ef:representativePoint/gml:Point/gml:pos/text()"), document); if (fmisids.length != names.length || fmisids.length != representativePoints.length) { throw new FMIUnexpectedResponseException(String.format( "Could not all properties of locations: fmisids: %d, names: %d, representativePoints: %d", fmisids.length, names.length, representativePoints.length)); } Set<Location> locations = new HashSet<>(representativePoints.length); for (int i = 0; i < representativePoints.length; i++) { BigDecimal[] latlon = parseLatLon(representativePoints[i]); locations.add(new Location(names[i], fmisids[i], latlon[0], latlon[1])); } return locations; } /** * Parse FMI multipointcoverage formatted xml response * */ private FMIResponse parseMultiPointCoverageXml(String response) throws FMIUnexpectedResponseException, FMIExceptionReportException, SAXException, IOException, XPathExpressionException { Document document = documentBuilder.parse(new InputSource(new StringReader(response))); XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setNamespaceContext(NAMESPACE_CONTEXT); boolean isExceptionReport = ((Node) xPath.compile("/ows:ExceptionReport").evaluate(document, XPathConstants.NODE)) != null; if (isExceptionReport) { Node exceptionCode = (Node) xPath.compile("/ows:ExceptionReport/ows:Exception/@exceptionCode") .evaluate(document, XPathConstants.NODE); String[] exceptionText = queryNodeValues(xPath.compile("//ows:ExceptionText/text()"), document); throw new FMIExceptionReportException(exceptionCode.getNodeValue(), exceptionText); } Builder builder = new FMIResponse.Builder(); String[] parameters = queryNodeValues(xPath.compile("//swe:field/@name"), document); /** * Observations have FMISID (FMI Station ID?), with forecasts we use lat & lon */ String[] ids = queryNodeValues(xPath.compile( "//target:Location/gml:identifier[@codeSpace='http://xml.fmi.fi/namespace/stationcode/fmisid']/text()"), document); String[] names = queryNodeValues(xPath.compile( "//target:Location/gml:name[@codeSpace='http://xml.fmi.fi/namespace/locationcode/name']/text()"), document); String[] representativePointRefs = queryNodeValues( xPath.compile("//target:Location/target:representativePoint/@xlink:href"), document); if ((ids.length > 0 && ids.length != names.length) || names.length != representativePointRefs.length) { throw new FMIUnexpectedResponseException(String.format( "Could not all properties of locations: ids: %d, names: %d, representativePointRefs: %d", ids.length, names.length, representativePointRefs.length)); } Location[] locations = new Location[representativePointRefs.length]; for (int i = 0; i < locations.length; i++) { BigDecimal[] latlon = findLatLon(xPath, i, document, representativePointRefs[i]); String id = ids.length == 0 ? String.format("%s,%s", latlon[0].toPlainString(), latlon[1].toPlainString()) : ids[i]; locations[i] = new Location(names[i], id, latlon[0], latlon[1]); } logger.trace("names ({}): {}", names.length, names); logger.trace("parameters ({}): {}", parameters.length, parameters); if (names.length == 0) { // No data, e.g. when starttime=endtime return builder.build(); } String latLonTimeTripletText = takeFirstOrError("positions", queryNodeValues(xPath.compile("//gmlcov:positions/text()"), document)); String[] latLonTimeTripletEntries = latLonTimeTripletText.trim().split("\\s+"); logger.trace("latLonTimeTripletText: {}", latLonTimeTripletText); logger.trace("latLonTimeTripletEntries ({}): {}", latLonTimeTripletEntries.length, latLonTimeTripletEntries); int countTimestamps = latLonTimeTripletEntries.length / 3 / locations.length; long[] timestampsEpoch = IntStream.range(0, latLonTimeTripletEntries.length).filter(i -> i % 3 == 0) .limit(countTimestamps).mapToLong(i -> Long.parseLong(latLonTimeTripletEntries[i + 2])).toArray(); // Invariant assert countTimestamps == timestampsEpoch.length; logger.trace("countTimestamps ({}): {}", countTimestamps, timestampsEpoch); validatePositionEntries(locations, timestampsEpoch, latLonTimeTripletEntries); String valuesText = takeFirstOrError("doubleOrNilReasonTupleList", queryNodeValues(xPath.compile(".//gml:doubleOrNilReasonTupleList/text()"), document)); String[] valuesEntries = valuesText.trim().split("\\s+"); logger.trace("valuesText: {}", valuesText); logger.trace("valuesEntries ({}): {}", valuesEntries.length, valuesEntries); if (valuesEntries.length != locations.length * parameters.length * countTimestamps) { throw new FMIUnexpectedResponseException(String.format( "Wrong number of values (%d). Expecting %d * %d * %d = %d", valuesEntries.length, locations.length, parameters.length, countTimestamps, countTimestamps * locations.length * parameters.length)); } IntStream.range(0, locations.length).forEach(locationIndex -> { for (int parameterIndex = 0; parameterIndex < parameters.length; parameterIndex++) { for (int timestepIndex = 0; timestepIndex < countTimestamps; timestepIndex++) { BigDecimal val = toBigDecimalOrNullIfNaN( valuesEntries[locationIndex * countTimestamps * parameters.length + timestepIndex * parameters.length + parameterIndex]); logger.trace("Found value {}={} @ time={} for location {}", parameters[parameterIndex], val, timestampsEpoch[timestepIndex], locations[locationIndex].id); builder.appendLocationData(locations[locationIndex], countTimestamps, parameters[parameterIndex], timestampsEpoch[timestepIndex], val); } } }); return builder.build(); } /** * Find representative latitude and longitude matching given xlink href attribute value * * @param xPath xpath object used for query * @param entryIndex index of the location, for logging only on errors * @param document document object * @param href xlink href attribute value. Should start with # * @return latitude and longitude values as array * @throws FMIUnexpectedResponseException parsing errors or when entry is not found * @throws XPathExpressionException xpath errors */ private BigDecimal[] findLatLon(XPath xPath, int entryIndex, Document document, String href) throws FMIUnexpectedResponseException, XPathExpressionException { if (!href.startsWith("#")) { throw new FMIUnexpectedResponseException( "Could not find valid representativePoint xlink:href, does not start with #"); } String pointId = href.substring(1); String pointLatLon = takeFirstOrError(String.format("[%d]/pos", entryIndex), queryNodeValues(xPath.compile(".//gml:Point[@gml:id='" + pointId + "']/gml:pos/text()"), document)); return parseLatLon(pointLatLon); } /** * Parse string reprsenting latitude longitude string separated by space * * @param pointLatLon latitude longitude string separated by space * @return latitude and longitude values as array * @throws FMIUnexpectedResponseException on parsing errors */ private BigDecimal[] parseLatLon(String pointLatLon) throws FMIUnexpectedResponseException { String[] latlon = pointLatLon.split(" "); BigDecimal lat, lon; if (latlon.length != 2) { throw new FMIUnexpectedResponseException(String.format( "Invalid latitude or longitude format, expected two values separated by space, got %d values: '%s'", latlon.length, latlon)); } try { lat = new BigDecimal(latlon[0]); lon = new BigDecimal(latlon[1]); } catch (NumberFormatException e) { throw new FMIUnexpectedResponseException( String.format("Invalid latitude or longitude format: %s", e.getMessage())); } return new BigDecimal[] { lat, lon }; } private String[] queryNodeValues(XPathExpression expression, Object source) throws XPathExpressionException { NodeList nodeList = (NodeList) expression.evaluate(source, XPathConstants.NODESET); String[] values = new String[nodeList.getLength()]; for (int i = 0; i < nodeList.getLength(); i++) { values[i] = nodeList.item(i).getNodeValue(); } return values; } /** * Asserts that length of values is exactly 1, and returns it * * @param errorDescription error description for FMIResponseException * @param values * @return * @throws FMIUnexpectedResponseException when length of values != 1 */ private String takeFirstOrError(String errorDescription, String[] values) throws FMIUnexpectedResponseException { if (values.length != 1) { throw new FMIUnexpectedResponseException(String.format("No unique match found: %s", errorDescription)); } return values[0]; } /** * Convert string to BigDecimal. "NaN" string is converted to null * * @param value * @return null when value is "NaN". Otherwise BigDecimal representing the string */ private @Nullable BigDecimal toBigDecimalOrNullIfNaN(String value) { if ("NaN".equals(value)) { return null; } else { return new BigDecimal(value); } } /** * Validate ordering and values of gmlcov:positions (latLonTimeTripletEntries) * essentially * pos1_lat, pos1_lon, time1 * pos1_lat, pos1_lon, time2 * pos1_lat, pos1_lon, time3 * pos2_lat, pos2_lon, time1 * pos2_lat, pos2_lon, time2 * ..etc.. * * - lat, lon should be in correct order and match position entries ("locations") * - time should values should be exactly same for each point (above time1, time2, ...), and match given timestamps * ("timestampsEpoch") * * * @param locations previously discovered locations * @param timestampsEpoch expected timestamps * @param latLonTimeTripletEntries flat array of strings representing the array, [row1_cell1, row1_cell2, * row2_cell1, ...] * @throws FMIUnexpectedResponseException when value ordering is not matching the expected */ private void validatePositionEntries(Location[] locations, long[] timestampsEpoch, String[] latLonTimeTripletEntries) throws FMIUnexpectedResponseException { int countTimestamps = timestampsEpoch.length; for (int locationIndex = 0; locationIndex < locations.length; locationIndex++) { String firstLat = latLonTimeTripletEntries[locationIndex * countTimestamps * 3]; String fistLon = latLonTimeTripletEntries[locationIndex * countTimestamps * 3 + 1]; // step through entries for this position for (int timestepIndex = 0; timestepIndex < countTimestamps; timestepIndex++) { String lat = latLonTimeTripletEntries[locationIndex * countTimestamps * 3 + timestepIndex * 3]; String lon = latLonTimeTripletEntries[locationIndex * countTimestamps * 3 + timestepIndex * 3 + 1]; String timeEpochSec = latLonTimeTripletEntries[locationIndex * countTimestamps * 3 + timestepIndex * 3 + 2]; if (!lat.equals(firstLat) || !lon.equals(fistLon)) { throw new FMIUnexpectedResponseException(String.format( "positions[%d] lat, lon for time index [%d] was not matching expected ordering", locationIndex, timestepIndex)); } String expectedLat = locations[locationIndex].latitude.toPlainString(); String expectedLon = locations[locationIndex].longitude.toPlainString(); if (!lat.equals(expectedLat) || !lon.equals(expectedLon)) { throw new FMIUnexpectedResponseException(String.format( "positions[%d] lat, lon for time index [%d] was not matching representativePoint", locationIndex, timestepIndex)); } if (Long.parseLong(timeEpochSec) != timestampsEpoch[timestepIndex]) { throw new FMIUnexpectedResponseException(String.format( "positions[%d] time (%s) for time index [%d] was not matching expected (%d) ordering", locationIndex, timeEpochSec, timestepIndex, timestampsEpoch[timestepIndex])); } } } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_8
crossvul-java_data_good_1910_16
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.insteon.internal.message; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.insteon.internal.utils.Pair; import org.openhab.binding.insteon.internal.utils.Utils.DataTypeParser; import org.openhab.binding.insteon.internal.utils.Utils.ParsingException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Reads the Msg definitions from an XML file * * @author Daniel Pfrommer - Initial contribution * @author Rob Nielsen - Port to openHAB 2 insteon binding */ @NonNullByDefault @SuppressWarnings("null") public class XMLMessageReader { /** * Reads the message definitions from an xml file * * @param input input stream from which to read * @return what was read from file: the map between clear text string and Msg objects * @throws IOException couldn't read file etc * @throws ParsingException something wrong with the file format * @throws FieldException something wrong with the field definition */ public static HashMap<String, Msg> readMessageDefinitions(InputStream input) throws IOException, ParsingException, FieldException { HashMap<String, Msg> messageMap = new HashMap<>(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbFactory.setXIncludeAware(false); dbFactory.setExpandEntityReferences(false); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Parse it! Document doc = dBuilder.parse(input); doc.getDocumentElement().normalize(); Node root = doc.getDocumentElement(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("msg")) { Pair<String, Msg> msgDef = readMessageDefinition((Element) node); messageMap.put(msgDef.getKey(), msgDef.getValue()); } } } } catch (SAXException e) { throw new ParsingException("Failed to parse XML!", e); } catch (ParserConfigurationException e) { throw new ParsingException("Got parser config exception! ", e); } return messageMap; } private static Pair<String, Msg> readMessageDefinition(Element msg) throws FieldException, ParsingException { int length = 0; int hlength = 0; LinkedHashMap<Field, Object> fieldMap = new LinkedHashMap<>(); String dir = msg.getAttribute("direction"); String name = msg.getAttribute("name"); Msg.Direction direction = Msg.Direction.getDirectionFromString(dir); if (msg.hasAttribute("length")) { length = Integer.parseInt(msg.getAttribute("length")); } NodeList nodes = msg.getChildNodes(); int offset = 0; for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getNodeName().equals("header")) { int o = readHeaderElement((Element) node, fieldMap); hlength = o; // Increment the offset by the header length offset += o; } else { Pair<Field, Object> field = readField((Element) node, offset); fieldMap.put(field.getKey(), field.getValue()); // Increment the offset offset += field.getKey().getType().getSize(); } } } if (offset != length) { throw new ParsingException( "Actual msg length " + offset + " differs from given msg length " + length + "!"); } if (length == 0) { length = offset; } return new Pair<>(name, createMsg(fieldMap, length, hlength, direction)); } private static int readHeaderElement(Element header, LinkedHashMap<Field, Object> fields) throws ParsingException { int offset = 0; int headerLen = Integer.parseInt(header.getAttribute("length")); NodeList nodes = header.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { @Nullable Pair<Field, Object> definition = readField((Element) node, offset); if (definition != null) { offset += definition.getKey().getType().getSize(); fields.put(definition.getKey(), definition.getValue()); } } } if (headerLen != offset) { throw new ParsingException( "Actual header length " + offset + " differs from given length " + headerLen + "!"); } return headerLen; } private static Pair<Field, Object> readField(Element field, int offset) { DataType dType = DataType.getDataType(field.getTagName()); // Will return blank if no name attribute String name = field.getAttribute("name"); Field f = new Field(name, dType, offset); // Now we have field, only need value String sVal = field.getTextContent(); Object val = DataTypeParser.parseDataType(dType, sVal); Pair<Field, Object> pair = new Pair<>(f, val); return pair; } private static Msg createMsg(HashMap<Field, Object> values, int length, int headerLength, Msg.Direction dir) throws FieldException { Msg msg = new Msg(headerLength, new byte[length], length, dir); for (Entry<Field, Object> e : values.entrySet()) { Field f = e.getKey(); f.set(msg.getData(), e.getValue()); if (f.getName() != null && !f.getName().equals("")) { msg.addField(f); } } return msg; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_16
crossvul-java_data_good_1736_0
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.milton.http.webdav; import io.milton.common.StreamUtils; import java.io.ByteArrayInputStream; import org.apache.commons.io.output.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.LinkedHashSet; import java.util.Set; import javax.xml.namespace.QName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * Simple implmentation which just parses the request body. If no xml is present * it will return an empty set. * * Note this generally shouldnt be used directly, but should be wrapped by * MSPropFindRequestFieldParser to support windows clients. * * @author brad */ public class DefaultPropFindRequestFieldParser implements PropFindRequestFieldParser { private static final Logger log = LoggerFactory.getLogger( DefaultPropFindRequestFieldParser.class ); public DefaultPropFindRequestFieldParser() { } @Override public PropertiesRequest getRequestedFields( InputStream in ) { final Set<QName> set = new LinkedHashSet<QName>(); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); StreamUtils.readTo( in, bout, false, true ); byte[] arr = bout.toByteArray(); if( arr.length > 1 ) { ByteArrayInputStream bin = new ByteArrayInputStream( arr ); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); // https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Processing reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); reader.setFeature("http://xml.org/sax/features/external-general-entities", false); PropFindSaxHandler handler = new PropFindSaxHandler(); reader.setContentHandler( handler ); try { reader.parse( new InputSource( bin ) ); if( handler.isAllProp() ) { return new PropertiesRequest(); } else { set.addAll( handler.getAttributes().keySet() ); } } catch( IOException e ) { log.warn( "exception parsing request body", e ); // ignore } catch( SAXException e ) { log.warn( "exception parsing request body", e ); // ignore } } } catch( Exception ex ) { // There's a report of an exception being thrown here by IT Hit Webdav client // Perhaps we can just log the error and return an empty set. Usually this // class is wrapped by the MsPropFindRequestFieldParser which will use a default // set of properties if this returns an empty set log.warn("Exception parsing PROPFIND request fields. Returning empty property set", ex); //throw new RuntimeException( ex ); } return PropertiesRequest.toProperties(set); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1736_0
crossvul-java_data_good_1910_7
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.enigma2.internal; import java.io.IOException; import java.io.StringReader; import java.time.LocalDateTime; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang.StringUtils; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jetty.util.UrlEncoded; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link Enigma2Client} class is responsible for communicating with the Enigma2 device. * * @see <a href= * "https://github.com/E2OpenPlugins/e2openplugin-OpenWebif/wiki/OpenWebif-API-documentation">OpenWebif-API-documentation</a> * * @author Guido Dolfen - Initial contribution */ @NonNullByDefault public class Enigma2Client { private final Logger logger = LoggerFactory.getLogger(Enigma2Client.class); static final String PATH_REMOTE_CONTROL = "/web/remotecontrol?command="; static final String PATH_POWER = "/web/powerstate"; static final String PATH_VOLUME = "/web/vol"; static final String PATH_SET_VOLUME = "/web/vol?set=set"; static final String PATH_TOGGLE_MUTE = "/web/vol?set=mute"; static final String PATH_TOGGLE_POWER = "/web/powerstate?newstate=0"; static final String PATH_MESSAGE = "/web/message?type="; static final String PATH_ALL_SERVICES = "/web/getallservices"; static final String PATH_ZAP = "/web/zap?sRef="; static final String PATH_CHANNEL = "/web/subservices"; static final String PATH_EPG = "/web/epgservicenow?sRef="; static final String PATH_ANSWER = "/web/messageanswer?getanswer=now"; static final int TYPE_QUESTION = 0; static final int TYPE_INFO = 1; static final int TYPE_WARNING = 2; static final int TYPE_ERROR = 3; private final Map<String, @Nullable String> channels = new ConcurrentHashMap<>(); private final String host; private boolean power; private String channel = ""; private String title = ""; private String description = ""; private String answer = ""; private int volume = 0; private boolean mute; private boolean online; private boolean initialized; private boolean asking; private LocalDateTime lastAnswerTime = LocalDateTime.of(2020, 1, 1, 0, 0); // Date in the past private final Enigma2HttpClient enigma2HttpClient; private final DocumentBuilderFactory factory; public Enigma2Client(String host, @Nullable String user, @Nullable String password, int requestTimeout) { enigma2HttpClient = new Enigma2HttpClient(requestTimeout); factory = DocumentBuilderFactory.newInstance(); // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html try { factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); } catch (ParserConfigurationException e) { logger.warn("Failed setting parser features against XXE attacks!", e); } if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(password)) { this.host = "http://" + user + ":" + password + "@" + host; } else { this.host = "http://" + host; } } public boolean refresh() { boolean wasOnline = online; refreshPower(); if (!wasOnline && online) { // Only refresh all services if the box changed from offline to online and power is on // because it is a performance intensive action. refreshAllServices(); } refreshChannel(); refreshEpg(); refreshVolume(); refreshAnswer(); return online; } public void refreshPower() { Optional<Document> document = transmitWithResult(PATH_POWER); if (document.isPresent()) { online = true; processPowerResult(document.get()); } else { online = false; power = false; } initialized = true; } public void refreshAllServices() { if (power || channels.isEmpty()) { transmitWithResult(PATH_ALL_SERVICES).ifPresent(this::processAllServicesResult); } } public void refreshChannel() { if (power) { transmitWithResult(PATH_CHANNEL).ifPresent(this::processChannelResult); } } public void refreshAnswer() { if (asking) { transmitWithResult(PATH_ANSWER).ifPresent(this::processAnswerResult); } } public void refreshVolume() { if (power) { transmitWithResult(PATH_VOLUME).ifPresent(this::processVolumeResult); } } public void refreshEpg() { if (power) { Optional.ofNullable(channels.get(channel)) .flatMap(name -> transmitWithResult(PATH_EPG + UrlEncoded.encodeString(name))) .ifPresent(this::processEpgResult); } } private Optional<Document> transmitWithResult(String path) { try { Optional<String> xml = transmit(path); if (xml.isPresent()) { DocumentBuilder builder = factory.newDocumentBuilder(); return Optional.ofNullable(builder.parse(new InputSource(new StringReader(xml.get())))); } return Optional.empty(); } catch (IOException | SAXException | ParserConfigurationException | IllegalArgumentException e) { if (online || !initialized) { logger.debug("Error on transmit {}{}.", host, path, e); } return Optional.empty(); } } private Optional<String> transmit(String path) { String url = host + path; try { logger.debug("Transmitting {}", url); String result = getEnigma2HttpClient().get(url); logger.debug("Transmitting result is {}", result); return Optional.ofNullable(result); } catch (IOException | IllegalArgumentException e) { if (online || !initialized) { logger.debug("Error on transmit {}.", url, e); } return Optional.empty(); } } public void setMute(boolean mute) { refreshVolume(); if (this.mute != mute) { transmitWithResult(PATH_TOGGLE_MUTE).ifPresent(this::processVolumeResult); } } public void setPower(boolean power) { refreshPower(); if (this.power != power) { transmitWithResult(PATH_TOGGLE_POWER).ifPresent(this::processPowerResult); } } public void setVolume(int volume) { transmitWithResult(PATH_SET_VOLUME + volume).ifPresent(this::processVolumeResult); } public void setChannel(String name) { if (channels.containsKey(name)) { String id = channels.get(name); transmitWithResult(PATH_ZAP + UrlEncoded.encodeString(id)).ifPresent(document -> channel = name); } else { logger.warn("Channel {} not found.", name); } } public void sendRcCommand(int key) { transmit(PATH_REMOTE_CONTROL + key); } public void sendError(int timeout, String text) { sendMessage(TYPE_ERROR, timeout, text); } public void sendWarning(int timeout, String text) { sendMessage(TYPE_WARNING, timeout, text); } public void sendInfo(int timeout, String text) { sendMessage(TYPE_INFO, timeout, text); } public void sendQuestion(int timeout, String text) { asking = true; sendMessage(TYPE_QUESTION, timeout, text); } private void sendMessage(int type, int timeout, String text) { transmit(PATH_MESSAGE + type + "&timeout=" + timeout + "&text=" + UrlEncoded.encodeString(text)); } private void processPowerResult(Document document) { power = !getBoolean(document, "e2instandby"); if (!power) { title = ""; description = ""; channel = ""; } } private void processChannelResult(Document document) { channel = getString(document, "e2servicename"); // Add channel-Reference-ID if not known if (!channels.containsKey(channel)) { channels.put(channel, getString(document, "e2servicereference")); } } private void processAnswerResult(Document document) { if (asking) { boolean state = getBoolean(document, "e2state"); if (state) { String[] text = getString(document, "e2statetext").split(" "); answer = text[text.length - 1].replace("!", ""); asking = false; lastAnswerTime = LocalDateTime.now(); } } } private void processVolumeResult(Document document) { volume = getInt(document, "e2current"); mute = getBoolean(document, "e2ismuted"); } private void processEpgResult(Document document) { title = getString(document, "e2eventtitle"); description = getString(document, "e2eventdescription"); } private void processAllServicesResult(Document document) { NodeList bouquetList = document.getElementsByTagName("e2bouquet"); channels.clear(); for (int i = 0; i < bouquetList.getLength(); i++) { Element bouquet = (Element) bouquetList.item(i); NodeList serviceList = bouquet.getElementsByTagName("e2service"); for (int j = 0; j < serviceList.getLength(); j++) { Element service = (Element) serviceList.item(j); String id = service.getElementsByTagName("e2servicereference").item(0).getTextContent(); String name = service.getElementsByTagName("e2servicename").item(0).getTextContent(); channels.put(name, id); } } } private String getString(Document document, String elementId) { return Optional.ofNullable(document.getElementsByTagName(elementId)).map(nodeList -> nodeList.item(0)) .map(Node::getTextContent).map(String::trim).orElse(""); } private boolean getBoolean(Document document, String elementId) { return Boolean.parseBoolean(getString(document, elementId)); } private int getInt(Document document, String elementId) { try { return Integer.parseInt(getString(document, elementId)); } catch (NumberFormatException e) { return 0; } } public int getVolume() { return volume; } public boolean isMute() { return mute; } public boolean isPower() { return power; } public LocalDateTime getLastAnswerTime() { return lastAnswerTime; } public String getChannel() { return channel; } public String getTitle() { return title; } public String getDescription() { return description; } public String getAnswer() { return answer; } public Collection<String> getChannels() { return channels.keySet(); } /** * Getter for Test-Injection * * @return HttpGet. */ Enigma2HttpClient getEnigma2HttpClient() { return enigma2HttpClient; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_7
crossvul-java_data_bad_4033_5
404: Not Found
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4033_5
crossvul-java_data_good_1910_14
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.insteon.internal.device; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.insteon.internal.device.DeviceType.FeatureGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Reads the device types from an xml file. * * @author Daniel Pfrommer - Initial contribution * @author Bernd Pfrommer - openHAB 1 insteonplm binding * @author Rob Nielsen - Port to openHAB 2 insteon binding */ @NonNullByDefault @SuppressWarnings("null") public class DeviceTypeLoader { private static final Logger logger = LoggerFactory.getLogger(DeviceTypeLoader.class); private HashMap<String, DeviceType> deviceTypes = new HashMap<>(); private @Nullable static DeviceTypeLoader deviceTypeLoader = null; private DeviceTypeLoader() { } // private so nobody can call it /** * Finds the device type for a given product key * * @param aProdKey product key to search for * @return the device type, or null if not found */ public @Nullable DeviceType getDeviceType(String aProdKey) { return (deviceTypes.get(aProdKey)); } /** * Must call loadDeviceTypesXML() before calling this function! * * @return currently known device types */ public HashMap<String, DeviceType> getDeviceTypes() { return (deviceTypes); } /** * Reads the device types from input stream and stores them in memory for * later access. * * @param is the input stream from which to read */ public void loadDeviceTypesXML(InputStream in) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbFactory.setXIncludeAware(false); dbFactory.setExpandEntityReferences(false); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(in); doc.getDocumentElement().normalize(); Node root = doc.getDocumentElement(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("device")) { processDevice((Element) node); } } } /** * Reads the device types from file and stores them in memory for later access. * * @param aFileName The name of the file to read from * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ public void loadDeviceTypesXML(String aFileName) throws ParserConfigurationException, SAXException, IOException { File file = new File(aFileName); InputStream in = new FileInputStream(file); loadDeviceTypesXML(in); } /** * Process device node * * @param e name of the element to process * @throws SAXException */ private void processDevice(Element e) throws SAXException { String productKey = e.getAttribute("productKey"); if (productKey.equals("")) { throw new SAXException("device in device_types file has no product key!"); } if (deviceTypes.containsKey(productKey)) { logger.warn("overwriting previous definition of device {}", productKey); deviceTypes.remove(productKey); } DeviceType devType = new DeviceType(productKey); NodeList nodes = e.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } Element subElement = (Element) node; if (subElement.getNodeName().equals("model")) { devType.setModel(subElement.getTextContent()); } else if (subElement.getNodeName().equals("description")) { devType.setDescription(subElement.getTextContent()); } else if (subElement.getNodeName().equals("feature")) { processFeature(devType, subElement); } else if (subElement.getNodeName().equals("feature_group")) { processFeatureGroup(devType, subElement); } deviceTypes.put(productKey, devType); } } private String processFeature(DeviceType devType, Element e) throws SAXException { String name = e.getAttribute("name"); if (name.equals("")) { throw new SAXException("feature " + e.getNodeName() + " has feature without name!"); } if (!name.equals(name.toLowerCase())) { throw new SAXException("feature name '" + name + "' must be lower case"); } if (!devType.addFeature(name, e.getTextContent())) { throw new SAXException("duplicate feature: " + name); } return (name); } private String processFeatureGroup(DeviceType devType, Element e) throws SAXException { String name = e.getAttribute("name"); if (name.equals("")) { throw new SAXException("feature group " + e.getNodeName() + " has no name attr!"); } String type = e.getAttribute("type"); if (type.equals("")) { throw new SAXException("feature group " + e.getNodeName() + " has no type attr!"); } FeatureGroup fg = new FeatureGroup(name, type); NodeList nodes = e.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) { continue; } Element subElement = (Element) node; if (subElement.getNodeName().equals("feature")) { fg.addFeature(processFeature(devType, subElement)); } else if (subElement.getNodeName().equals("feature_group")) { fg.addFeature(processFeatureGroup(devType, subElement)); } } if (!devType.addFeatureGroup(name, fg)) { throw new SAXException("duplicate feature group " + name); } return (name); } /** * Helper function for debugging */ private void logDeviceTypes() { for (Entry<String, DeviceType> dt : getDeviceTypes().entrySet()) { String msg = String.format("%-10s->", dt.getKey()) + dt.getValue(); logger.debug("{}", msg); } } /** * Singleton instance function, creates DeviceTypeLoader * * @return DeviceTypeLoader singleton reference */ @Nullable public static synchronized DeviceTypeLoader instance() { if (deviceTypeLoader == null) { deviceTypeLoader = new DeviceTypeLoader(); InputStream input = DeviceTypeLoader.class.getResourceAsStream("/device_types.xml"); try { deviceTypeLoader.loadDeviceTypesXML(input); } catch (ParserConfigurationException e) { logger.warn("parser config error when reading device types xml file: ", e); } catch (SAXException e) { logger.warn("SAX exception when reading device types xml file: ", e); } catch (IOException e) { logger.warn("I/O exception when reading device types xml file: ", e); } logger.debug("loaded {} devices: ", deviceTypeLoader.getDeviceTypes().size()); deviceTypeLoader.logDeviceTypes(); } return deviceTypeLoader; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_14
crossvul-java_data_bad_1910_11
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.homematic.internal.communicator.message; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.Base64; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Decodes a XML-RPC message from the Homematic server. * * @author Gerhard Riegler - Initial contribution */ public class XmlRpcResponse implements RpcResponse { private String methodName; private Object[] responseData; /** * Decodes a XML-RPC message from the given InputStream. */ public XmlRpcResponse(InputStream is, String encoding) throws SAXException, ParserConfigurationException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); InputSource inputSource = new InputSource(is); inputSource.setEncoding(encoding); saxParser.parse(inputSource, new XmlRpcHandler()); } @Override public Object[] getResponseData() { return responseData; } @Override public String getMethodName() { return methodName; } @Override public String toString() { return RpcUtils.dumpRpcMessage(methodName, responseData); } /** * SAX parser implementation to decode XML-RPC. * * @author Gerhard Riegler */ private class XmlRpcHandler extends DefaultHandler { private List<Object> result = new ArrayList<>(); private LinkedList<List<Object>> currentDataObject = new LinkedList<>(); private StringBuilder tagValue; private boolean isValueTag; @Override public void startDocument() throws SAXException { currentDataObject.addLast(new ArrayList<>()); } @Override public void endDocument() throws SAXException { result.addAll(currentDataObject.removeLast()); responseData = result.toArray(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String tag = qName.toLowerCase(); if (tag.equals("array") || tag.equals("struct")) { currentDataObject.addLast(new ArrayList<>()); } isValueTag = tag.equals("value"); tagValue = new StringBuilder(); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { String currentTag = qName.toLowerCase(); String currentValue = tagValue.toString(); List<Object> data = currentDataObject.peekLast(); switch (currentTag) { case "boolean": data.add("1".equals(currentValue) ? Boolean.TRUE : Boolean.FALSE); break; case "int": case "i4": data.add(new Integer(currentValue)); break; case "double": data.add(new Double(currentValue)); break; case "string": case "name": data.add(currentValue); break; case "value": if (isValueTag) { data.add(currentValue); isValueTag = false; } break; case "array": List<Object> arrayData = currentDataObject.removeLast(); currentDataObject.peekLast().add(arrayData.toArray()); break; case "struct": List<Object> mapData = currentDataObject.removeLast(); Map<Object, Object> resultMap = new HashMap<>(); for (int i = 0; i < mapData.size(); i += 2) { resultMap.put(mapData.get(i), mapData.get(i + 1)); } currentDataObject.peekLast().add(resultMap); break; case "base64": data.add(Base64.getDecoder().decode(currentValue)); break; case "datetime.iso8601": try { data.add(XmlRpcRequest.xmlRpcDateFormat.parse(currentValue)); } catch (ParseException ex) { throw new SAXException(ex.getMessage(), ex); } break; case "methodname": methodName = currentValue; break; case "params": case "param": case "methodcall": case "methodresponse": case "member": case "data": case "fault": break; default: throw new SAXException("Unknown XML-RPC tag: " + currentTag); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { tagValue.append(new String(ch, start, length)); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_11
crossvul-java_data_bad_1397_0
/* * Copyright 2017 - 2018 Anton Tananaev (anton@traccar.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.traccar.protocol; import com.fasterxml.jackson.databind.util.ByteBufferBackedInputStream; import io.netty.channel.Channel; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpResponseStatus; import org.traccar.BaseHttpProtocolDecoder; import org.traccar.DeviceSession; import org.traccar.Protocol; import org.traccar.helper.DateUtil; import org.traccar.model.Position; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.net.SocketAddress; import java.util.LinkedList; import java.util.List; public class SpotProtocolDecoder extends BaseHttpProtocolDecoder { private DocumentBuilder documentBuilder; private XPath xPath; private XPathExpression messageExpression; public SpotProtocolDecoder(Protocol protocol) { super(protocol); try { documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); xPath = XPathFactory.newInstance().newXPath(); messageExpression = xPath.compile("//messageList/message"); } catch (ParserConfigurationException | XPathExpressionException e) { throw new RuntimeException(e); } } @Override protected Object decode( Channel channel, SocketAddress remoteAddress, Object msg) throws Exception { FullHttpRequest request = (FullHttpRequest) msg; Document document = documentBuilder.parse(new ByteBufferBackedInputStream(request.content().nioBuffer())); NodeList nodes = (NodeList) messageExpression.evaluate(document, XPathConstants.NODESET); List<Position> positions = new LinkedList<>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, xPath.evaluate("esnName", node)); if (deviceSession != null) { Position position = new Position(getProtocolName()); position.setDeviceId(deviceSession.getDeviceId()); position.setValid(true); position.setTime(DateUtil.parseDate(xPath.evaluate("timestamp", node))); position.setLatitude(Double.parseDouble(xPath.evaluate("latitude", node))); position.setLongitude(Double.parseDouble(xPath.evaluate("longitude", node))); position.set(Position.KEY_EVENT, xPath.evaluate("messageType", node)); positions.add(position); } } sendResponse(channel, HttpResponseStatus.OK); return positions; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1397_0
crossvul-java_data_good_1910_6
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.dlinksmarthome.internal; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.soap.MessageFactory; import javax.xml.soap.MimeHeader; import javax.xml.soap.MimeHeaders; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.client.util.BytesContentProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * The {@link DLinkHNAPCommunication} is responsible for communicating with D-Link * Smart Home devices using the HNAP interface. * * This abstract class handles login and authentication which is common between devices. * * Reverse engineered from Login.html and soapclient.js retrieved from the device. * * @author Mike Major - Initial contribution */ public abstract class DLinkHNAPCommunication { // SOAP actions private static final String LOGIN_ACTION = "\"http://purenetworks.com/HNAP1/LOGIN\""; // Strings used more than once private static final String LOGIN = "LOGIN"; private static final String ACTION = "Action"; private static final String USERNAME = "Username"; private static final String LOGINPASSWORD = "LoginPassword"; private static final String CAPTCHA = "Captcha"; private static final String ADMIN = "Admin"; private static final String LOGINRESULT = "LOGINResult"; private static final String COOKIE = "Cookie"; /** * HNAP XMLNS */ protected static final String HNAP_XMLNS = "http://purenetworks.com/HNAP1"; /** * The SOAP action HTML header */ protected static final String SOAPACTION = "SOAPAction"; /** * OK represents a successful action */ protected static final String OK = "OK"; /** * Use to log connection issues */ private final Logger logger = LoggerFactory.getLogger(DLinkHNAPCommunication.class); private URI uri; private final HttpClient httpClient; private final String pin; private String privateKey; private DocumentBuilder parser; private SOAPMessage requestAction; private SOAPMessage loginAction; private HNAPStatus status = HNAPStatus.INITIALISED; /** * Indicates the status of the HNAP interface * */ protected enum HNAPStatus { /** * Ready to start communication with device */ INITIALISED, /** * Successfully logged in to device */ LOGGED_IN, /** * Problem communicating with device */ COMMUNICATION_ERROR, /** * Internal error */ INTERNAL_ERROR, /** * Error due to unsupported firmware */ UNSUPPORTED_FIRMWARE, /** * Error due to invalid pin code */ INVALID_PIN } /** * Use {@link #getHNAPStatus()} to determine the status of the HNAP connection * after construction. * * @param ipAddress * @param pin */ public DLinkHNAPCommunication(final String ipAddress, final String pin) { this.pin = pin; httpClient = new HttpClient(); try { uri = new URI("http://" + ipAddress + "/HNAP1"); httpClient.start(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); dbf.setXIncludeAware(false); dbf.setExpandEntityReferences(false); parser = dbf.newDocumentBuilder(); final MessageFactory messageFactory = MessageFactory.newInstance(); requestAction = messageFactory.createMessage(); loginAction = messageFactory.createMessage(); buildRequestAction(); buildLoginAction(); } catch (final SOAPException e) { logger.debug("DLinkHNAPCommunication - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final URISyntaxException e) { logger.debug("DLinkHNAPCommunication - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final ParserConfigurationException e) { logger.debug("DLinkHNAPCommunication - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final Exception e) { // Thrown by httpClient.start() logger.debug("DLinkHNAPCommunication - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } } /** * Stop communicating with the device */ public void dispose() { try { httpClient.stop(); } catch (final Exception e) { // Ignored } } /** * This is the first SOAP message used in the login process and is used to retrieve * the cookie, challenge and public key used for authentication. * * @throws SOAPException */ private void buildRequestAction() throws SOAPException { requestAction.getSOAPHeader().detachNode(); final SOAPBody soapBody = requestAction.getSOAPBody(); final SOAPElement soapBodyElem = soapBody.addChildElement(LOGIN, "", HNAP_XMLNS); soapBodyElem.addChildElement(ACTION).addTextNode("request"); soapBodyElem.addChildElement(USERNAME).addTextNode(ADMIN); soapBodyElem.addChildElement(LOGINPASSWORD); soapBodyElem.addChildElement(CAPTCHA); final MimeHeaders headers = requestAction.getMimeHeaders(); headers.addHeader(SOAPACTION, LOGIN_ACTION); requestAction.saveChanges(); } /** * This is the second SOAP message used in the login process and uses a password derived * from the challenge, public key and the device's pin code. * * @throws SOAPException */ private void buildLoginAction() throws SOAPException { loginAction.getSOAPHeader().detachNode(); final SOAPBody soapBody = loginAction.getSOAPBody(); final SOAPElement soapBodyElem = soapBody.addChildElement(LOGIN, "", HNAP_XMLNS); soapBodyElem.addChildElement(ACTION).addTextNode("login"); soapBodyElem.addChildElement(USERNAME).addTextNode(ADMIN); soapBodyElem.addChildElement(LOGINPASSWORD); soapBodyElem.addChildElement(CAPTCHA); final MimeHeaders headers = loginAction.getMimeHeaders(); headers.addHeader(SOAPACTION, LOGIN_ACTION); } /** * Sets the password for the second login message based on the data received from the * first login message. Also sets the private key used to generate the authentication header. * * @param challenge * @param cookie * @param publicKey * @throws SOAPException * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ private void setAuthenticationData(final String challenge, final String cookie, final String publicKey) throws SOAPException, InvalidKeyException, NoSuchAlgorithmException { final MimeHeaders loginHeaders = loginAction.getMimeHeaders(); loginHeaders.setHeader(COOKIE, "uid=" + cookie); privateKey = hash(challenge, publicKey + pin); final String password = hash(challenge, privateKey); loginAction.getSOAPBody().getElementsByTagName(LOGINPASSWORD).item(0).setTextContent(password); loginAction.saveChanges(); } /** * Used to hash the authentication data such as the login password and the authentication header * for the detection message. * * @param data * @param key * @return The hashed data * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ private String hash(final String data, final String key) throws NoSuchAlgorithmException, InvalidKeyException { final Mac mac = Mac.getInstance("HMACMD5"); final SecretKeySpec sKey = new SecretKeySpec(key.getBytes(), "ASCII"); mac.init(sKey); final byte[] bytes = mac.doFinal(data.getBytes()); final StringBuilder hashBuf = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { final String hex = Integer.toHexString(0xFF & bytes[i]).toUpperCase(); if (hex.length() == 1) { hashBuf.append('0'); } hashBuf.append(hex); } return hashBuf.toString(); } /** * Output unexpected responses to the debug log and sets the FIRMWARE error. * * @param message * @param soapResponse */ private void unexpectedResult(final String message, final Document soapResponse) { logUnexpectedResult(message, soapResponse); // Best guess when receiving unexpected responses status = HNAPStatus.UNSUPPORTED_FIRMWARE; } /** * Get the status of the HNAP interface * * @return the HNAP status */ protected HNAPStatus getHNAPStatus() { return status; } /** * Sends the two login messages and stores the private key used to generate the * authentication header required for actions. * * Use {@link #getHNAPStatus()} to determine the status of the HNAP connection * after calling this method. * * @param timeout - Connection timeout in milliseconds */ protected void login(final int timeout) { if (status != HNAPStatus.INTERNAL_ERROR) { try { Document soapResponse = sendReceive(requestAction, timeout); Node result = soapResponse.getElementsByTagName(LOGINRESULT).item(0); if (result != null && OK.equals(result.getTextContent())) { final Node challengeNode = soapResponse.getElementsByTagName("Challenge").item(0); final Node cookieNode = soapResponse.getElementsByTagName(COOKIE).item(0); final Node publicKeyNode = soapResponse.getElementsByTagName("PublicKey").item(0); if (challengeNode != null && cookieNode != null && publicKeyNode != null) { setAuthenticationData(challengeNode.getTextContent(), cookieNode.getTextContent(), publicKeyNode.getTextContent()); soapResponse = sendReceive(loginAction, timeout); result = soapResponse.getElementsByTagName(LOGINRESULT).item(0); if (result != null) { if ("success".equals(result.getTextContent())) { status = HNAPStatus.LOGGED_IN; } else { logger.debug("login - Check pin is correct"); // Assume pin code problem rather than a firmware change status = HNAPStatus.INVALID_PIN; } } else { unexpectedResult("login - Unexpected login response", soapResponse); } } else { unexpectedResult("login - Unexpected request response", soapResponse); } } else { unexpectedResult("login - Unexpected request response", soapResponse); } } catch (final InvalidKeyException e) { logger.debug("login - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final NoSuchAlgorithmException e) { logger.debug("login - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final Exception e) { // Assume there has been some problem trying to send one of the messages if (status != HNAPStatus.COMMUNICATION_ERROR) { logger.debug("login - Communication error", e); status = HNAPStatus.COMMUNICATION_ERROR; } } } } /** * Sets the authentication headers for the action message. This should only be called * after a successful login. * * Use {@link #getHNAPStatus()} to determine the status of the HNAP connection * after calling this method. * * @param action - SOAP Action to add headers */ protected void setAuthenticationHeaders(final SOAPMessage action) { if (status == HNAPStatus.LOGGED_IN) { try { final MimeHeaders loginHeaders = loginAction.getMimeHeaders(); final MimeHeaders actionHeaders = action.getMimeHeaders(); actionHeaders.setHeader(COOKIE, loginHeaders.getHeader(COOKIE)[0]); final String timeStamp = String.valueOf(System.currentTimeMillis() / 1000); final String auth = hash(timeStamp + actionHeaders.getHeader(SOAPACTION)[0], privateKey) + " " + timeStamp; actionHeaders.setHeader("HNAP_AUTH", auth); action.saveChanges(); } catch (final InvalidKeyException e) { logger.debug("setAuthenticationHeaders - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final NoSuchAlgorithmException e) { logger.debug("setAuthenticationHeaders - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } catch (final SOAPException e) { // No communication happening so assume system error logger.debug("setAuthenticationHeaders - Internal error", e); status = HNAPStatus.INTERNAL_ERROR; } } } /** * Send the SOAP message using Jetty HTTP client. Jetty is used in preference to * HttpURLConnection which can result in the HNAP interface becoming unresponsive. * * @param action - SOAP Action to send * @param timeout - Connection timeout in milliseconds * @return The result * @throws IOException * @throws SOAPException * @throws SAXException * @throws ExecutionException * @throws TimeoutException * @throws InterruptedException */ protected Document sendReceive(final SOAPMessage action, final int timeout) throws IOException, SOAPException, SAXException, InterruptedException, TimeoutException, ExecutionException { Document result; final Request request = httpClient.POST(uri); request.timeout(timeout, TimeUnit.MILLISECONDS); final Iterator<?> it = action.getMimeHeaders().getAllHeaders(); while (it.hasNext()) { final MimeHeader header = (MimeHeader) it.next(); request.header(header.getName(), header.getValue()); } try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { action.writeTo(os); request.content(new BytesContentProvider(os.toByteArray())); final ContentResponse response = request.send(); try (final ByteArrayInputStream is = new ByteArrayInputStream(response.getContent())) { result = parser.parse(is); } } return result; } /** * Output unexpected responses to the debug log. * * @param message * @param soapResponse */ protected void logUnexpectedResult(final String message, final Document soapResponse) { // No point formatting for output if debug logging is not enabled if (logger.isDebugEnabled()) { try { final TransformerFactory transFactory = TransformerFactory.newInstance(); final Transformer transformer = transFactory.newTransformer(); final StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(soapResponse), new StreamResult(buffer)); logger.debug("{} : {}", message, buffer); } catch (final TransformerException e) { logger.debug("{}", message); } } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_6
crossvul-java_data_bad_4362_1
/** * (The MIT License) * * Copyright (c) 2008 - 2011: * * * {Aaron Patterson}[http://tenderlovemaking.com] * * {Mike Dalessio}[http://mike.daless.io] * * {Charles Nutter}[http://blog.headius.com] * * {Sergio Arbeo}[http://www.serabe.com] * * {Patrick Mahoney}[http://polycrystal.org] * * {Yoko Harada}[http://yokolet.blogspot.com] * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package nokogiri; import static nokogiri.internals.NokogiriHelpers.adjustSystemIdIfNecessary; import static nokogiri.internals.NokogiriHelpers.getNokogiriClass; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import nokogiri.internals.IgnoreSchemaErrorsErrorHandler; import nokogiri.internals.SchemaErrorHandler; import nokogiri.internals.XmlDomParserContext; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyClass; import org.jruby.RubyFixnum; import org.jruby.RubyObject; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.RaiseException; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.Visibility; import org.jruby.runtime.builtin.IRubyObject; import org.w3c.dom.Document; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * Class for Nokogiri::XML::Schema * * @author sergio * @author Yoko Harada <yokolet@gmail.com> */ @JRubyClass(name="Nokogiri::XML::Schema") public class XmlSchema extends RubyObject { private Validator validator; public XmlSchema(Ruby ruby, RubyClass klazz) { super(ruby, klazz); } /** * Create and return a copy of this object. * * @return a clone of this object */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } private Schema getSchema(Source source, String currentDir, String scriptFileName, SchemaErrorHandler error_handler) throws SAXException { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); SchemaResourceResolver resourceResolver = new SchemaResourceResolver(currentDir, scriptFileName, null, error_handler); schemaFactory.setResourceResolver(resourceResolver); schemaFactory.setErrorHandler(error_handler); return schemaFactory.newSchema(source); } private void setValidator(Validator validator) { this.validator = validator; } static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source) { Ruby runtime = context.getRuntime(); XmlSchema xmlSchema = (XmlSchema) NokogiriService.XML_SCHEMA_ALLOCATOR.allocate(runtime, klazz); xmlSchema.setInstanceVariable("@errors", runtime.newEmptyArray()); try { SchemaErrorHandler error_handler = new SchemaErrorHandler(context.getRuntime(), (RubyArray)xmlSchema.getInstanceVariable("@errors")); Schema schema = xmlSchema.getSchema(source, context.getRuntime().getCurrentDirectory(), context.getRuntime().getInstanceConfig().getScriptFileName(), error_handler); xmlSchema.setValidator(schema.newValidator()); return xmlSchema; } catch (SAXException ex) { throw context.getRuntime().newRuntimeError("Could not parse document: " + ex.getMessage()); } } /* * call-seq: * from_document(doc) * * Create a new Schema from the Nokogiri::XML::Document +doc+ */ @JRubyMethod(meta=true) public static IRubyObject from_document(ThreadContext context, IRubyObject klazz, IRubyObject document) { XmlDocument doc = ((XmlDocument) ((XmlNode) document).document(context)); RubyArray errors = (RubyArray) doc.getInstanceVariable("@errors"); if (!errors.isEmpty()) { throw ((XmlSyntaxError) errors.first()).toThrowable(); } DOMSource source = new DOMSource(doc.getDocument()); IRubyObject uri = doc.url(context); if (!uri.isNil()) { source.setSystemId(uri.convertToString().asJavaString()); } return getSchema(context, (RubyClass)klazz, source); } private static IRubyObject getSchema(ThreadContext context, RubyClass klazz, Source source) { String moduleName = klazz.getName(); if ("Nokogiri::XML::Schema".equals(moduleName)) { return XmlSchema.createSchemaInstance(context, klazz, source); } else if ("Nokogiri::XML::RelaxNG".equals(moduleName)) { return XmlRelaxng.createSchemaInstance(context, klazz, source); } return context.getRuntime().getNil(); } @JRubyMethod(meta=true) public static IRubyObject read_memory(ThreadContext context, IRubyObject klazz, IRubyObject content) { String data = content.convertToString().asJavaString(); return getSchema(context, (RubyClass) klazz, new StreamSource(new StringReader(data))); } @JRubyMethod(visibility=Visibility.PRIVATE) public IRubyObject validate_document(ThreadContext context, IRubyObject document) { return validate_document_or_file(context, (XmlDocument)document); } @JRubyMethod(visibility=Visibility.PRIVATE) public IRubyObject validate_file(ThreadContext context, IRubyObject file) { Ruby runtime = context.runtime; XmlDomParserContext ctx = new XmlDomParserContext(runtime, RubyFixnum.newFixnum(runtime, 1L)); ctx.setInputSourceFile(context, file); XmlDocument xmlDocument = ctx.parse(context, getNokogiriClass(runtime, "Nokogiri::XML::Document"), context.nil); return validate_document_or_file(context, xmlDocument); } IRubyObject validate_document_or_file(ThreadContext context, XmlDocument xmlDocument) { RubyArray errors = (RubyArray) this.getInstanceVariable("@errors"); ErrorHandler errorHandler = new SchemaErrorHandler(context.runtime, errors); setErrorHandler(errorHandler); try { validate(xmlDocument.getDocument()); } catch (SAXException ex) { XmlSyntaxError xmlSyntaxError = XmlSyntaxError.createXMLSyntaxError(context.runtime); xmlSyntaxError.setException(ex); errors.append(xmlSyntaxError); } catch (IOException ex) { throw context.runtime.newIOError(ex.getMessage()); } return errors; } protected void setErrorHandler(ErrorHandler errorHandler) { validator.setErrorHandler(errorHandler); } protected void validate(Document document) throws SAXException, IOException { DOMSource docSource = new DOMSource(document); validator.validate(docSource); } private class SchemaResourceResolver implements LSResourceResolver { SchemaLSInput lsInput = new SchemaLSInput(); String currentDir; String scriptFileName; SchemaErrorHandler error_handler; //String defaultURI; SchemaResourceResolver(String currentDir, String scriptFileName, Object input, SchemaErrorHandler error_handler) { this.currentDir = currentDir; this.scriptFileName = scriptFileName; this.error_handler = error_handler; if (input == null) return; if (input instanceof String) { lsInput.setStringData((String)input); } else if (input instanceof Reader) { lsInput.setCharacterStream((Reader)input); } else if (input instanceof InputStream) { lsInput.setByteStream((InputStream)input); } } @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { String adjusted = adjustSystemIdIfNecessary(currentDir, scriptFileName, baseURI, systemId); lsInput.setPublicId(publicId); lsInput.setSystemId(adjusted != null? adjusted : systemId); lsInput.setBaseURI(baseURI); return lsInput; } } private class SchemaLSInput implements LSInput { protected String fPublicId; protected String fSystemId; protected String fBaseSystemId; protected InputStream fByteStream; protected Reader fCharStream; protected String fData; protected String fEncoding; protected boolean fCertifiedText = false; @Override public String getBaseURI() { return fBaseSystemId; } @Override public InputStream getByteStream() { return fByteStream; } @Override public boolean getCertifiedText() { return fCertifiedText; } @Override public Reader getCharacterStream() { return fCharStream; } @Override public String getEncoding() { return fEncoding; } @Override public String getPublicId() { return fPublicId; } @Override public String getStringData() { return fData; } @Override public String getSystemId() { return fSystemId; } @Override public void setBaseURI(String baseURI) { fBaseSystemId = baseURI; } @Override public void setByteStream(InputStream byteStream) { fByteStream = byteStream; } @Override public void setCertifiedText(boolean certified) { fCertifiedText = certified; } @Override public void setCharacterStream(Reader charStream) { fCharStream = charStream; } @Override public void setEncoding(String encoding) { fEncoding = encoding; } @Override public void setPublicId(String pubId) { fPublicId = pubId; } @Override public void setStringData(String stringData) { fData = stringData; } @Override public void setSystemId(String sysId) { fSystemId = sysId; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_4362_1
crossvul-java_data_bad_1910_4
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.denonmarantz.internal.connector.http; import java.beans.Introspector; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.UnmarshalException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.util.StreamReaderDelegate; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.Response; import org.eclipse.jetty.client.api.Result; import org.eclipse.smarthome.io.net.http.HttpUtil; import org.openhab.binding.denonmarantz.internal.DenonMarantzState; import org.openhab.binding.denonmarantz.internal.config.DenonMarantzConfiguration; import org.openhab.binding.denonmarantz.internal.connector.DenonMarantzConnector; import org.openhab.binding.denonmarantz.internal.xml.entities.Deviceinfo; import org.openhab.binding.denonmarantz.internal.xml.entities.Main; import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatus; import org.openhab.binding.denonmarantz.internal.xml.entities.ZoneStatusLite; import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandRequest; import org.openhab.binding.denonmarantz.internal.xml.entities.commands.AppCommandResponse; import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandRx; import org.openhab.binding.denonmarantz.internal.xml.entities.commands.CommandTx; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class makes the connection to the receiver and manages it. * It is also responsible for sending commands to the receiver. * * * * @author Jeroen Idserda - Initial Contribution (1.x Binding) * @author Jan-Willem Veldhuis - Refactored for 2.x */ public class DenonMarantzHttpConnector extends DenonMarantzConnector { private Logger logger = LoggerFactory.getLogger(DenonMarantzHttpConnector.class); private static final int REQUEST_TIMEOUT_MS = 5000; // 5 seconds // Main URL for the receiver private static final String URL_MAIN = "formMainZone_MainZoneXml.xml"; // Main Zone Status URL private static final String URL_ZONE_MAIN = "formMainZone_MainZoneXmlStatus.xml"; // Secondary zone lite status URL (contains less info) private static final String URL_ZONE_SECONDARY_LITE = "formZone%d_Zone%dXmlStatusLite.xml"; // Device info URL private static final String URL_DEVICE_INFO = "Deviceinfo.xml"; // URL to send app commands to private static final String URL_APP_COMMAND = "AppCommand.xml"; private static final String CONTENT_TYPE_XML = "application/xml"; private final String cmdUrl; private final String statusUrl; private final HttpClient httpClient; private ScheduledFuture<?> pollingJob; public DenonMarantzHttpConnector(DenonMarantzConfiguration config, DenonMarantzState state, ScheduledExecutorService scheduler, HttpClient httpClient) { this.config = config; this.scheduler = scheduler; this.state = state; this.cmdUrl = String.format("http://%s:%d/goform/formiPhoneAppDirect.xml?", config.getHost(), config.getHttpPort()); this.statusUrl = String.format("http://%s:%d/goform/", config.getHost(), config.getHttpPort()); this.httpClient = httpClient; } public DenonMarantzState getState() { return state; } /** * Set up the connection to the receiver by starting to poll the HTTP API. */ @Override public void connect() { if (!isPolling()) { logger.debug("HTTP polling started."); try { setConfigProperties(); } catch (IOException e) { logger.debug("IO error while retrieving document:", e); state.connectionError("IO error while connecting to AVR: " + e.getMessage()); return; } pollingJob = scheduler.scheduleWithFixedDelay(() -> { try { refreshHttpProperties(); } catch (IOException e) { logger.debug("IO error while retrieving document", e); state.connectionError("IO error while connecting to AVR: " + e.getMessage()); stopPolling(); } catch (RuntimeException e) { /** * We need to catch this RuntimeException, as otherwise the polling stops. * Log as error as it could be a user configuration error. */ StringBuilder sb = new StringBuilder(); for (StackTraceElement s : e.getStackTrace()) { sb.append(s.toString()).append("\n"); } logger.error("Error while polling Http: \"{}\". Stacktrace: \n{}", e.getMessage(), sb.toString()); } }, 0, config.httpPollingInterval, TimeUnit.SECONDS); } } private boolean isPolling() { return pollingJob != null && !pollingJob.isCancelled(); } private void stopPolling() { if (isPolling()) { pollingJob.cancel(true); logger.debug("HTTP polling stopped."); } } /** * Shutdown the http client */ @Override public void dispose() { logger.debug("disposing connector"); stopPolling(); } @Override protected void internalSendCommand(String command) { logger.debug("Sending command '{}'", command); if (StringUtils.isBlank(command)) { logger.warn("Trying to send empty command"); return; } try { String url = cmdUrl + URLEncoder.encode(command, Charset.defaultCharset().displayName()); logger.trace("Calling url {}", url); httpClient.newRequest(url).timeout(5, TimeUnit.SECONDS).send(new Response.CompleteListener() { @Override public void onComplete(Result result) { if (result.getResponse().getStatus() != 200) { logger.warn("Error {} while sending command", result.getResponse().getReason()); } } }); } catch (UnsupportedEncodingException e) { logger.warn("Error sending command", e); } } private void updateMain() throws IOException { String url = statusUrl + URL_MAIN; logger.trace("Refreshing URL: {}", url); Main statusMain = getDocument(url, Main.class); if (statusMain != null) { state.setPower(statusMain.getPower().getValue()); } } private void updateMainZone() throws IOException { String url = statusUrl + URL_ZONE_MAIN; logger.trace("Refreshing URL: {}", url); ZoneStatus mainZone = getDocument(url, ZoneStatus.class); if (mainZone != null) { state.setInput(mainZone.getInputFuncSelect().getValue()); state.setMainVolume(mainZone.getMasterVolume().getValue()); state.setMainZonePower(mainZone.getPower().getValue()); state.setMute(mainZone.getMute().getValue()); if (config.inputOptions == null) { config.inputOptions = mainZone.getInputFuncList(); } if (mainZone.getSurrMode() == null) { logger.debug("Unable to get the SURROUND_MODE. MainZone update may not be correct."); } else { state.setSurroundProgram(mainZone.getSurrMode().getValue()); } } } private void updateSecondaryZones() throws IOException { for (int i = 2; i <= config.getZoneCount(); i++) { String url = String.format("%s" + URL_ZONE_SECONDARY_LITE, statusUrl, i, i); logger.trace("Refreshing URL: {}", url); ZoneStatusLite zoneSecondary = getDocument(url, ZoneStatusLite.class); if (zoneSecondary != null) { switch (i) { // maximum 2 secondary zones are supported case 2: state.setZone2Power(zoneSecondary.getPower().getValue()); state.setZone2Volume(zoneSecondary.getMasterVolume().getValue()); state.setZone2Mute(zoneSecondary.getMute().getValue()); state.setZone2Input(zoneSecondary.getInputFuncSelect().getValue()); break; case 3: state.setZone3Power(zoneSecondary.getPower().getValue()); state.setZone3Volume(zoneSecondary.getMasterVolume().getValue()); state.setZone3Mute(zoneSecondary.getMute().getValue()); state.setZone3Input(zoneSecondary.getInputFuncSelect().getValue()); break; case 4: state.setZone4Power(zoneSecondary.getPower().getValue()); state.setZone4Volume(zoneSecondary.getMasterVolume().getValue()); state.setZone4Mute(zoneSecondary.getMute().getValue()); state.setZone4Input(zoneSecondary.getInputFuncSelect().getValue()); break; } } } } private void updateDisplayInfo() throws IOException { String url = statusUrl + URL_APP_COMMAND; logger.trace("Refreshing URL: {}", url); AppCommandRequest request = AppCommandRequest.of(CommandTx.CMD_NET_STATUS); AppCommandResponse response = postDocument(url, AppCommandResponse.class, request); if (response != null) { CommandRx titleInfo = response.getCommands().get(0); state.setNowPlayingArtist(titleInfo.getText("artist")); state.setNowPlayingAlbum(titleInfo.getText("album")); state.setNowPlayingTrack(titleInfo.getText("track")); } } private boolean setConfigProperties() throws IOException { String url = statusUrl + URL_DEVICE_INFO; logger.debug("Refreshing URL: {}", url); Deviceinfo deviceinfo = getDocument(url, Deviceinfo.class); if (deviceinfo != null) { config.setZoneCount(deviceinfo.getDeviceZones()); } /** * The maximum volume is received from the telnet connection in the * form of the MVMAX property. It is not always received reliable however, * so we're using a default for now. */ config.setMainVolumeMax(DenonMarantzConfiguration.MAX_VOLUME); // if deviceinfo is null, something went wrong (and is logged in getDocument catch blocks) return (deviceinfo != null); } private void refreshHttpProperties() throws IOException { logger.trace("Refreshing Denon status"); updateMain(); updateMainZone(); updateSecondaryZones(); updateDisplayInfo(); } @Nullable private <T> T getDocument(String uri, Class<T> response) throws IOException { try { String result = HttpUtil.executeUrl("GET", uri, REQUEST_TIMEOUT_MS); logger.trace("result of getDocument for uri '{}':\r\n{}", uri, result); if (StringUtils.isNotBlank(result)) { JAXBContext jc = JAXBContext.newInstance(response); XMLInputFactory xif = XMLInputFactory.newInstance(); XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(result)); xsr = new PropertyRenamerDelegate(xsr); @SuppressWarnings("unchecked") T obj = (T) jc.createUnmarshaller().unmarshal(xsr); return obj; } } catch (UnmarshalException e) { logger.debug("Failed to unmarshal xml document: {}", e.getMessage()); } catch (JAXBException e) { logger.debug("Unexpected error occurred during unmarshalling of document: {}", e.getMessage()); } catch (XMLStreamException e) { logger.debug("Communication error: {}", e.getMessage()); } return null; } @Nullable private <T, S> T postDocument(String uri, Class<T> response, S request) throws IOException { try { JAXBContext jaxbContext = JAXBContext.newInstance(request.getClass()); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); StringWriter sw = new StringWriter(); jaxbMarshaller.marshal(request, sw); ByteArrayInputStream inputStream = new ByteArrayInputStream(sw.toString().getBytes(StandardCharsets.UTF_8)); String result = HttpUtil.executeUrl("POST", uri, inputStream, CONTENT_TYPE_XML, REQUEST_TIMEOUT_MS); if (StringUtils.isNotBlank(result)) { JAXBContext jcResponse = JAXBContext.newInstance(response); @SuppressWarnings("unchecked") T obj = (T) jcResponse.createUnmarshaller().unmarshal(IOUtils.toInputStream(result)); return obj; } } catch (JAXBException e) { logger.debug("Encoding error in post", e); } return null; } private static class PropertyRenamerDelegate extends StreamReaderDelegate { public PropertyRenamerDelegate(XMLStreamReader xsr) { super(xsr); } @Override public String getAttributeLocalName(int index) { return Introspector.decapitalize(super.getAttributeLocalName(index)); } @Override public String getLocalName() { return Introspector.decapitalize(super.getLocalName()); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_4
crossvul-java_data_bad_2449_11
/* Copyright 2018-2020 Accenture Technology Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.platformlambda.services; import org.platformlambda.core.exception.AppException; import org.platformlambda.core.models.LambdaFunction; import org.platformlambda.core.system.Platform; import org.platformlambda.models.SamplePoJo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Date; import java.util.Map; public class HelloPoJo implements LambdaFunction { private static final Logger log = LoggerFactory.getLogger(HelloPoJo.class); @Override public Object handleEvent(Map<String, String> headers, Object body, int instance) throws AppException, IOException { String id = headers.get("id"); if (id == null) { throw new IllegalArgumentException("Missing parameter 'id'"); } if (id.equals("1")) { // return some place-holder values to demonstrate the PoJo can be transported over the network SamplePoJo mock = new SamplePoJo(1, "Simple PoJo class", "100 World Blvd, Planet Earth"); // set current timestamp to indicate that the object is a new one mock.setDate(new Date()); // set instance count and service origin ID to show that the object comes from a different instance mock.setInstance(instance); mock.setOrigin(Platform.getInstance().getOrigin()); log.info("Pojo delivered by instance #{}", instance); return mock; } else { throw new AppException(404, "Not found. Try id = 1"); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_2449_11
crossvul-java_data_bad_1910_18
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.samsungtv.internal.service; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link SamsungTvUtils} provides some utilities for internal use. * * @author Pauli Anttila - Initial contribution */ @NonNullByDefault public class SamsungTvUtils { /** * Build {@link String} type {@link HashMap} from variable number of * {@link String}s. * * @param data * Variable number of {@link String} parameters which will be * added to hash map. */ public static HashMap<String, String> buildHashMap(String... data) { HashMap<String, String> result = new HashMap<>(); if (data.length % 2 != 0) { throw new IllegalArgumentException("Odd number of arguments"); } String key = null; Integer step = -1; for (String value : data) { step++; switch (step % 2) { case 0: if (value == null) { throw new IllegalArgumentException("Null key value"); } key = value; continue; case 1: if (key != null) { result.put(key, value); } break; } } return result; } /** * Build {@link Document} from {@link String} which contains XML content. * * @param xml * {@link String} which contains XML content. * @return {@link Document} or null if convert has failed. */ public static @Nullable Document loadXMLFromString(String xml) { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(xml)); return builder.parse(is); } catch (ParserConfigurationException | SAXException | IOException e) { // Silently ignore exception and return null. } return null; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_18
crossvul-java_data_good_1910_19
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.sonos.internal; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringEscapeUtils; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.XMLReaderFactory; /** * The {@link SonosXMLParser} is a class of helper functions * to parse XML data returned by the Zone Players * * @author Karel Goderis - Initial contribution */ @NonNullByDefault public class SonosXMLParser { static final Logger LOGGER = LoggerFactory.getLogger(SonosXMLParser.class); private static final MessageFormat METADATA_FORMAT = new MessageFormat( "<DIDL-Lite xmlns:dc=\"http://purl.org/dc/elements/1.1/\" " + "xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" " + "xmlns:r=\"urn:schemas-rinconnetworks-com:metadata-1-0/\" " + "xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\">" + "<item id=\"{0}\" parentID=\"{1}\" restricted=\"true\">" + "<dc:title>{2}</dc:title>" + "<upnp:class>{3}</upnp:class>" + "<desc id=\"cdudn\" nameSpace=\"urn:schemas-rinconnetworks-com:metadata-1-0/\">" + "{4}</desc>" + "</item></DIDL-Lite>"); private enum Element { TITLE, CLASS, ALBUM, ALBUM_ART_URI, CREATOR, RES, TRACK_NUMBER, RESMD, DESC } private enum CurrentElement { item, res, streamContent, albumArtURI, title, upnpClass, creator, album, albumArtist, desc } /** * @param xml * @return a list of alarms from the given xml string. * @throws IOException * @throws SAXException */ public static List<SonosAlarm> getAlarmsFromStringResult(String xml) { AlarmHandler handler = new AlarmHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { LOGGER.error("Could not parse Alarms from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse Alarms from string '{}'", xml); } return handler.getAlarms(); } /** * @param xml * @return a list of Entries from the given xml string. * @throws IOException * @throws SAXException */ public static List<SonosEntry> getEntriesFromString(String xml) { EntryHandler handler = new EntryHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { LOGGER.error("Could not parse Entries from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse Entries from string '{}'", xml); } return handler.getArtists(); } /** * Returns the meta data which is needed to play Pandora * (and others?) favorites * * @param xml * @return The value of the desc xml tag * @throws SAXException */ public static @Nullable SonosResourceMetaData getResourceMetaData(String xml) throws SAXException { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); ResourceMetaDataHandler handler = new ResourceMetaDataHandler(); reader.setContentHandler(handler); try { reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { LOGGER.error("Could not parse Resource MetaData from String '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse Resource MetaData from string '{}'", xml); } return handler.getMetaData(); } /** * @param controller * @param xml * @return zone group from the given xml * @throws IOException * @throws SAXException */ public static List<SonosZoneGroup> getZoneGroupFromXML(String xml) { ZoneGroupHandler handler = new ZoneGroupHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse ZoneGroup from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse ZoneGroup from string '{}'", xml); } return handler.getGroups(); } public static List<String> getRadioTimeFromXML(String xml) { OpmlHandler handler = new OpmlHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse RadioTime from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse RadioTime from string '{}'", xml); } return handler.getTextFields(); } public static Map<String, @Nullable String> getRenderingControlFromXML(String xml) { RenderingControlEventHandler handler = new RenderingControlEventHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse Rendering Control from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse Rendering Control from string '{}'", xml); } return handler.getChanges(); } public static Map<String, @Nullable String> getAVTransportFromXML(String xml) { AVTransportEventHandler handler = new AVTransportEventHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse AV Transport from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse AV Transport from string '{}'", xml); } return handler.getChanges(); } public static SonosMetaData getMetaDataFromXML(String xml) { MetaDataHandler handler = new MetaDataHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse MetaData from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse MetaData from string '{}'", xml); } return handler.getMetaData(); } public static List<SonosMusicService> getMusicServicesFromXML(String xml) { MusicServiceHandler handler = new MusicServiceHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(handler); reader.parse(new InputSource(new StringReader(xml))); } catch (IOException e) { // This should never happen - we're not performing I/O! LOGGER.error("Could not parse music services from string '{}'", xml); } catch (SAXException s) { LOGGER.error("Could not parse music services from string '{}'", xml); } return handler.getServices(); } private static class EntryHandler extends DefaultHandler { // Maintain a set of elements about which it is unuseful to complain about. // This list will be initialized on the first failure case private static @Nullable List<String> ignore; private String id = ""; private String parentId = ""; private StringBuilder upnpClass = new StringBuilder(); private StringBuilder res = new StringBuilder(); private StringBuilder title = new StringBuilder(); private StringBuilder album = new StringBuilder(); private StringBuilder albumArtUri = new StringBuilder(); private StringBuilder creator = new StringBuilder(); private StringBuilder trackNumber = new StringBuilder(); private StringBuilder desc = new StringBuilder(); private @Nullable Element element; private List<SonosEntry> artists = new ArrayList<>(); EntryHandler() { // shouldn't be used outside of this package. } @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { String name = qName == null ? "" : qName; switch (name) { case "container": case "item": if (attributes != null) { id = attributes.getValue("id"); parentId = attributes.getValue("parentID"); } break; case "res": element = Element.RES; break; case "dc:title": element = Element.TITLE; break; case "upnp:class": element = Element.CLASS; break; case "dc:creator": element = Element.CREATOR; break; case "upnp:album": element = Element.ALBUM; break; case "upnp:albumArtURI": element = Element.ALBUM_ART_URI; break; case "upnp:originalTrackNumber": element = Element.TRACK_NUMBER; break; case "r:resMD": element = Element.RESMD; break; default: List<String> curIgnore = ignore; if (curIgnore == null) { curIgnore = new ArrayList<>(); curIgnore.add("DIDL-Lite"); curIgnore.add("type"); curIgnore.add("ordinal"); curIgnore.add("description"); ignore = curIgnore; } if (!curIgnore.contains(localName)) { LOGGER.debug("Did not recognise element named {}", localName); } element = null; break; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { Element elt = element; if (elt == null) { return; } switch (elt) { case TITLE: title.append(ch, start, length); break; case CLASS: upnpClass.append(ch, start, length); break; case RES: res.append(ch, start, length); break; case ALBUM: album.append(ch, start, length); break; case ALBUM_ART_URI: albumArtUri.append(ch, start, length); break; case CREATOR: creator.append(ch, start, length); break; case TRACK_NUMBER: trackNumber.append(ch, start, length); break; case RESMD: desc.append(ch, start, length); break; case DESC: break; } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if (("container".equals(qName) || "item".equals(qName))) { element = null; int trackNumberVal = 0; try { trackNumberVal = Integer.parseInt(trackNumber.toString()); } catch (Exception e) { } SonosResourceMetaData md = null; // The resource description is needed for playing favorites on pandora if (!desc.toString().isEmpty()) { try { md = getResourceMetaData(desc.toString()); } catch (SAXException ignore) { LOGGER.debug("Failed to parse embeded", ignore); } } artists.add(new SonosEntry(id, title.toString(), parentId, album.toString(), albumArtUri.toString(), creator.toString(), upnpClass.toString(), res.toString(), trackNumberVal, md)); title = new StringBuilder(); upnpClass = new StringBuilder(); res = new StringBuilder(); album = new StringBuilder(); albumArtUri = new StringBuilder(); creator = new StringBuilder(); trackNumber = new StringBuilder(); desc = new StringBuilder(); } } public List<SonosEntry> getArtists() { return artists; } } private static class ResourceMetaDataHandler extends DefaultHandler { private String id = ""; private String parentId = ""; private StringBuilder title = new StringBuilder(); private StringBuilder upnpClass = new StringBuilder(); private StringBuilder desc = new StringBuilder(); private @Nullable Element element; private @Nullable SonosResourceMetaData metaData; ResourceMetaDataHandler() { // shouldn't be used outside of this package. } @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { String name = qName == null ? "" : qName; switch (name) { case "container": case "item": if (attributes != null) { id = attributes.getValue("id"); parentId = attributes.getValue("parentID"); } break; case "desc": element = Element.DESC; break; case "upnp:class": element = Element.CLASS; break; case "dc:title": element = Element.TITLE; break; default: element = null; break; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { Element elt = element; if (elt == null) { return; } switch (elt) { case TITLE: title.append(ch, start, length); break; case CLASS: upnpClass.append(ch, start, length); break; case DESC: desc.append(ch, start, length); break; default: break; } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if ("DIDL-Lite".equals(qName)) { metaData = new SonosResourceMetaData(id, parentId, title.toString(), upnpClass.toString(), desc.toString()); element = null; desc = new StringBuilder(); upnpClass = new StringBuilder(); title = new StringBuilder(); } } public @Nullable SonosResourceMetaData getMetaData() { return metaData; } } private static class AlarmHandler extends DefaultHandler { private @Nullable String id; private String startTime = ""; private String duration = ""; private String recurrence = ""; private @Nullable String enabled; private String roomUUID = ""; private String programURI = ""; private String programMetaData = ""; private String playMode = ""; private @Nullable String volume; private @Nullable String includeLinkedZones; private List<SonosAlarm> alarms = new ArrayList<>(); AlarmHandler() { // shouldn't be used outside of this package. } @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("Alarm".equals(qName) && attributes != null) { id = attributes.getValue("ID"); duration = attributes.getValue("Duration"); recurrence = attributes.getValue("Recurrence"); startTime = attributes.getValue("StartTime"); enabled = attributes.getValue("Enabled"); roomUUID = attributes.getValue("RoomUUID"); programURI = attributes.getValue("ProgramURI"); programMetaData = attributes.getValue("ProgramMetaData"); playMode = attributes.getValue("PlayMode"); volume = attributes.getValue("Volume"); includeLinkedZones = attributes.getValue("IncludeLinkedZones"); } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if ("Alarm".equals(qName)) { int finalID = 0; int finalVolume = 0; boolean finalEnabled = !"0".equals(enabled); boolean finalIncludeLinkedZones = !"0".equals(includeLinkedZones); try { finalID = Integer.parseInt(id); finalVolume = Integer.parseInt(volume); } catch (Exception e) { LOGGER.debug("Error parsing Integer"); } alarms.add(new SonosAlarm(finalID, startTime, duration, recurrence, finalEnabled, roomUUID, programURI, programMetaData, playMode, finalVolume, finalIncludeLinkedZones)); } } public List<SonosAlarm> getAlarms() { return alarms; } } private static class ZoneGroupHandler extends DefaultHandler { private final List<SonosZoneGroup> groups = new ArrayList<>(); private final List<String> currentGroupPlayers = new ArrayList<>(); private final List<String> currentGroupPlayerZones = new ArrayList<>(); private String coordinator = ""; private String groupId = ""; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("ZoneGroup".equals(qName) && attributes != null) { groupId = attributes.getValue("ID"); coordinator = attributes.getValue("Coordinator"); } else if ("ZoneGroupMember".equals(qName) && attributes != null) { currentGroupPlayers.add(attributes.getValue("UUID")); String zoneName = attributes.getValue("ZoneName"); if (zoneName != null) { currentGroupPlayerZones.add(zoneName); } String htInfoSet = attributes.getValue("HTSatChanMapSet"); if (htInfoSet != null) { currentGroupPlayers.addAll(getAllHomeTheaterMembers(htInfoSet)); } } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if ("ZoneGroup".equals(qName)) { groups.add(new SonosZoneGroup(groupId, coordinator, currentGroupPlayers, currentGroupPlayerZones)); currentGroupPlayers.clear(); currentGroupPlayerZones.clear(); } } public List<SonosZoneGroup> getGroups() { return groups; } private Set<String> getAllHomeTheaterMembers(String homeTheaterDescription) { Set<String> homeTheaterMembers = new HashSet<>(); Matcher matcher = Pattern.compile("(RINCON_\\w+)").matcher(homeTheaterDescription); while (matcher.find()) { String member = matcher.group(); homeTheaterMembers.add(member); } return homeTheaterMembers; } } private static class OpmlHandler extends DefaultHandler { // <opml version="1"> // <head> // <status>200</status> // // </head> // <body> // <outline type="text" text="Q-Music 103.3" guide_id="s2398" key="station" // image="http://radiotime-logos.s3.amazonaws.com/s87683q.png" preset_id="s2398"/> // <outline type="text" text="Bjorn Verhoeven" guide_id="p257265" seconds_remaining="2230" duration="7200" // key="show"/> // <outline type="text" text="Top 40-Pop"/> // <outline type="text" text="37m remaining"/> // <outline type="object" text="NowPlaying"> // <nowplaying> // <logo>http://radiotime-logos.s3.amazonaws.com/s87683.png</logo> // <twitter_id /> // </nowplaying> // </outline> // </body> // </opml> private final List<String> textFields = new ArrayList<>(); private @Nullable String textField; private @Nullable String type; // private String logo; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("outline".equals(qName)) { type = attributes == null ? null : attributes.getValue("type"); if ("text".equals(type)) { textField = attributes == null ? null : attributes.getValue("text"); } else { textField = null; } } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if ("outline".equals(qName)) { String field = textField; if (field != null) { textFields.add(field); } } } public List<String> getTextFields() { return textFields; } } private static class AVTransportEventHandler extends DefaultHandler { /* * <Event xmlns="urn:schemas-upnp-org:metadata-1-0/AVT/" xmlns:r="urn:schemas-rinconnetworks-com:metadata-1-0/"> * <InstanceID val="0"> * <TransportState val="PLAYING"/> * <CurrentPlayMode val="NORMAL"/> * <CurrentPlayMode val="0"/> * <NumberOfTracks val="29"/> * <CurrentTrack val="12"/> * <CurrentSection val="0"/> * <CurrentTrackURI val= * "x-file-cifs://192.168.1.1/Storage4/Sonos%20Music/Queens%20Of%20The%20Stone%20Age/Lullabies%20To%20Paralyze/Queens%20Of%20The%20Stone%20Age%20-%20Lullabies%20To%20Paralyze%20-%2012%20-%20Broken%20Box.wma" * /> * <CurrentTrackDuration val="0:03:02"/> * <CurrentTrackMetaData val= * "&lt;DIDL-Lite xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot; xmlns:upnp=&quot;urn:schemas-upnp-org:metadata-1-0/upnp/&quot; xmlns:r=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot; xmlns=&quot;urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/&quot;&gt;&lt;item id=&quot;-1&quot; parentID=&quot;-1&quot; restricted=&quot;true&quot;&gt;&lt;res protocolInfo=&quot;x-file-cifs:*:audio/x-ms-wma:*&quot; duration=&quot;0:03:02&quot;&gt;x-file-cifs://192.168.1.1/Storage4/Sonos%20Music/Queens%20Of%20The%20Stone%20Age/Lullabies%20To%20Paralyze/Queens%20Of%20The%20Stone%20Age%20-%20Lullabies%20To%20Paralyze%20-%2012%20-%20Broken%20Box.wma&lt;/res&gt;&lt;r:streamContent&gt;&lt;/r:streamContent&gt;&lt;dc:title&gt;Broken Box&lt;/dc:title&gt;&lt;upnp:class&gt;object.item.audioItem.musicTrack&lt;/upnp:class&gt;&lt;dc:creator&gt;Queens Of The Stone Age&lt;/dc:creator&gt;&lt;upnp:album&gt;Lullabies To Paralyze&lt;/upnp:album&gt;&lt;r:albumArtist&gt;Queens Of The Stone Age&lt;/r:albumArtist&gt;&lt;/item&gt;&lt;/DIDL-Lite&gt;" * /><r:NextTrackURI val= * "x-file-cifs://192.168.1.1/Storage4/Sonos%20Music/Queens%20Of%20The%20Stone%20Age/Lullabies%20To%20Paralyze/Queens%20Of%20The%20Stone%20Age%20-%20Lullabies%20To%20Paralyze%20-%2013%20-%20&apos;&apos;You%20Got%20A%20Killer%20Scene%20There,%20Man...&apos;&apos;.wma" * /><r:NextTrackMetaData val= * "&lt;DIDL-Lite xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot; xmlns:upnp=&quot;urn:schemas-upnp-org:metadata-1-0/upnp/&quot; xmlns:r=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot; xmlns=&quot;urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/&quot;&gt;&lt;item id=&quot;-1&quot; parentID=&quot;-1&quot; restricted=&quot;true&quot;&gt;&lt;res protocolInfo=&quot;x-file-cifs:*:audio/x-ms-wma:*&quot; duration=&quot;0:04:56&quot;&gt;x-file-cifs://192.168.1.1/Storage4/Sonos%20Music/Queens%20Of%20The%20Stone%20Age/Lullabies%20To%20Paralyze/Queens%20Of%20The%20Stone%20Age%20-%20Lullabies%20To%20Paralyze%20-%2013%20-%20&amp;apos;&amp;apos;You%20Got%20A%20Killer%20Scene%20There,%20Man...&amp;apos;&amp;apos;.wma&lt;/res&gt;&lt;dc:title&gt;&amp;apos;&amp;apos;You Got A Killer Scene There, Man...&amp;apos;&amp;apos;&lt;/dc:title&gt;&lt;upnp:class&gt;object.item.audioItem.musicTrack&lt;/upnp:class&gt;&lt;dc:creator&gt;Queens Of The Stone Age&lt;/dc:creator&gt;&lt;upnp:album&gt;Lullabies To Paralyze&lt;/upnp:album&gt;&lt;r:albumArtist&gt;Queens Of The Stone Age&lt;/r:albumArtist&gt;&lt;/item&gt;&lt;/DIDL-Lite&gt;" * /><r:EnqueuedTransportURI * val="x-rincon-playlist:RINCON_000E582126EE01400#A:ALBUMARTIST/Queens%20Of%20The%20Stone%20Age"/><r: * EnqueuedTransportURIMetaData val= * "&lt;DIDL-Lite xmlns:dc=&quot;http://purl.org/dc/elements/1.1/&quot; xmlns:upnp=&quot;urn:schemas-upnp-org:metadata-1-0/upnp/&quot; xmlns:r=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot; xmlns=&quot;urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/&quot;&gt;&lt;item id=&quot;A:ALBUMARTIST/Queens%20Of%20The%20Stone%20Age&quot; parentID=&quot;A:ALBUMARTIST&quot; restricted=&quot;true&quot;&gt;&lt;dc:title&gt;Queens Of The Stone Age&lt;/dc:title&gt;&lt;upnp:class&gt;object.container&lt;/upnp:class&gt;&lt;desc id=&quot;cdudn&quot; nameSpace=&quot;urn:schemas-rinconnetworks-com:metadata-1-0/&quot;&gt;RINCON_AssociatedZPUDN&lt;/desc&gt;&lt;/item&gt;&lt;/DIDL-Lite&gt;" * /> * <PlaybackStorageMedium val="NETWORK"/> * <AVTransportURI val="x-rincon-queue:RINCON_000E5812BC1801400#0"/> * <AVTransportURIMetaData val=""/> * <CurrentTransportActions val="Play, Stop, Pause, Seek, Next, Previous"/> * <TransportStatus val="OK"/> * <r:SleepTimerGeneration val="0"/> * <r:AlarmRunning val="0"/> * <r:SnoozeRunning val="0"/> * <r:RestartPending val="0"/> * <TransportPlaySpeed val="NOT_IMPLEMENTED"/> * <CurrentMediaDuration val="NOT_IMPLEMENTED"/> * <RecordStorageMedium val="NOT_IMPLEMENTED"/> * <PossiblePlaybackStorageMedia val="NONE, NETWORK"/> * <PossibleRecordStorageMedia val="NOT_IMPLEMENTED"/> * <RecordMediumWriteStatus val="NOT_IMPLEMENTED"/> * <CurrentRecordQualityMode val="NOT_IMPLEMENTED"/> * <PossibleRecordQualityModes val="NOT_IMPLEMENTED"/> * <NextAVTransportURI val="NOT_IMPLEMENTED"/> * <NextAVTransportURIMetaData val="NOT_IMPLEMENTED"/> * </InstanceID> * </Event> */ private final Map<String, @Nullable String> changes = new HashMap<>(); @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { /* * The events are all of the form <qName val="value"/> so we can get all * the info we need from here. */ if (localName == null) { // this means that localName isn't defined in EventType, which is expected for some elements LOGGER.info("{} is not defined in EventType. ", localName); } else { String val = attributes == null ? null : attributes.getValue("val"); if (val != null) { changes.put(localName, val); } } } public Map<String, @Nullable String> getChanges() { return changes; } } private static class MetaDataHandler extends DefaultHandler { private @Nullable CurrentElement currentElement; private String id = "-1"; private String parentId = "-1"; private StringBuilder resource = new StringBuilder(); private StringBuilder streamContent = new StringBuilder(); private StringBuilder albumArtUri = new StringBuilder(); private StringBuilder title = new StringBuilder(); private StringBuilder upnpClass = new StringBuilder(); private StringBuilder creator = new StringBuilder(); private StringBuilder album = new StringBuilder(); private StringBuilder albumArtist = new StringBuilder(); @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { String name = localName == null ? "" : localName; switch (name) { case "item": currentElement = CurrentElement.item; if (attributes != null) { id = attributes.getValue("id"); parentId = attributes.getValue("parentID"); } break; case "res": currentElement = CurrentElement.res; break; case "streamContent": currentElement = CurrentElement.streamContent; break; case "albumArtURI": currentElement = CurrentElement.albumArtURI; break; case "title": currentElement = CurrentElement.title; break; case "class": currentElement = CurrentElement.upnpClass; break; case "creator": currentElement = CurrentElement.creator; break; case "album": currentElement = CurrentElement.album; break; case "albumArtist": currentElement = CurrentElement.albumArtist; break; default: // unknown element currentElement = null; break; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { CurrentElement elt = currentElement; if (elt == null) { return; } switch (elt) { case item: break; case res: resource.append(ch, start, length); break; case streamContent: streamContent.append(ch, start, length); break; case albumArtURI: albumArtUri.append(ch, start, length); break; case title: title.append(ch, start, length); break; case upnpClass: upnpClass.append(ch, start, length); break; case creator: creator.append(ch, start, length); break; case album: album.append(ch, start, length); break; case albumArtist: albumArtist.append(ch, start, length); break; case desc: break; } } public SonosMetaData getMetaData() { return new SonosMetaData(id, parentId, resource.toString(), streamContent.toString(), albumArtUri.toString(), title.toString(), upnpClass.toString(), creator.toString(), album.toString(), albumArtist.toString()); } } private static class RenderingControlEventHandler extends DefaultHandler { private final Map<String, @Nullable String> changes = new HashMap<>(); private boolean getPresetName = false; private @Nullable String presetName; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if (qName == null) { return; } String channel; String val; switch (qName) { case "Volume": case "Mute": case "Loudness": channel = attributes == null ? null : attributes.getValue("channel"); val = attributes == null ? null : attributes.getValue("val"); if (channel != null && val != null) { changes.put(qName + channel, val); } break; case "Bass": case "Treble": case "OutputFixed": val = attributes == null ? null : attributes.getValue("val"); if (val != null) { changes.put(qName, val); } break; case "PresetNameList": getPresetName = true; break; default: break; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { if (getPresetName) { presetName = new String(ch, start, length); } } @Override public void endElement(@Nullable String uri, @Nullable String localName, @Nullable String qName) throws SAXException { if (getPresetName) { getPresetName = false; String preset = presetName; if (qName != null && preset != null) { changes.put(qName, preset); } } } public Map<String, @Nullable String> getChanges() { return changes; } } private static class MusicServiceHandler extends DefaultHandler { private final List<SonosMusicService> services = new ArrayList<>(); @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { // All services are of the form <services Id="value" Name="value">...</Service> if ("Service".equals(qName) && attributes != null && attributes.getValue("Id") != null && attributes.getValue("Name") != null) { services.add(new SonosMusicService(attributes.getValue("Id"), attributes.getValue("Name"))); } } public List<SonosMusicService> getServices() { return services; } } public static @Nullable String getRoomName(String descriptorXML) { RoomNameHandler roomNameHandler = new RoomNameHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(roomNameHandler); URL url = new URL(descriptorXML); reader.parse(new InputSource(url.openStream())); } catch (IOException | SAXException e) { LOGGER.error("Could not parse Sonos room name from string '{}'", descriptorXML); } return roomNameHandler.getRoomName(); } private static class RoomNameHandler extends DefaultHandler { private @Nullable String roomName; private boolean roomNameTag; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("roomName".equalsIgnoreCase(localName)) { roomNameTag = true; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { if (roomNameTag) { roomName = new String(ch, start, length); roomNameTag = false; } } public @Nullable String getRoomName() { return roomName; } } public static @Nullable String parseModelDescription(URL descriptorURL) { ModelNameHandler modelNameHandler = new ModelNameHandler(); try { XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(modelNameHandler); URL url = new URL(descriptorURL.toString()); reader.parse(new InputSource(url.openStream())); } catch (IOException | SAXException e) { LOGGER.error("Could not parse Sonos model name from string '{}'", descriptorURL.toString()); } return modelNameHandler.getModelName(); } private static class ModelNameHandler extends DefaultHandler { private @Nullable String modelName; private boolean modelNameTag; @Override public void startElement(@Nullable String uri, @Nullable String localName, @Nullable String qName, @Nullable Attributes attributes) throws SAXException { if ("modelName".equalsIgnoreCase(localName)) { modelNameTag = true; } } @Override public void characters(char @Nullable [] ch, int start, int length) throws SAXException { if (modelNameTag) { modelName = new String(ch, start, length); modelNameTag = false; } } public @Nullable String getModelName() { return modelName; } } /** * The model name provided by upnp is formated like in the example form "Sonos PLAY:1" or "Sonos PLAYBAR" * * @param sonosModelName Sonos model name provided via upnp device * @return the extracted players model name without column (:) character used for ThingType creation */ public static String extractModelName(String sonosModelName) { String ret = sonosModelName; Matcher matcher = Pattern.compile("\\s(.*)").matcher(ret); if (matcher.find()) { ret = matcher.group(1); } if (ret.contains(":")) { ret = ret.replace(":", ""); } return ret; } public static String compileMetadataString(SonosEntry entry) { /** * If the entry contains resource meta data we will override this with * that data. */ String id = entry.getId(); String parentId = entry.getParentId(); String title = entry.getTitle(); String upnpClass = entry.getUpnpClass(); /** * By default 'RINCON_AssociatedZPUDN' is used for most operations, * however when playing a favorite entry that is associated withh a * subscription like pandora we need to use the desc string asscoiated * with that item. */ String desc = entry.getDesc(); if (desc == null) { desc = "RINCON_AssociatedZPUDN"; } /** * If resource meta data exists, use it over the parent data */ SonosResourceMetaData resourceMetaData = entry.getResourceMetaData(); if (resourceMetaData != null) { id = resourceMetaData.getId(); parentId = resourceMetaData.getParentId(); title = resourceMetaData.getTitle(); desc = resourceMetaData.getDesc(); upnpClass = resourceMetaData.getUpnpClass(); } title = StringEscapeUtils.escapeXml(title); String metadata = METADATA_FORMAT.format(new Object[] { id, parentId, title, upnpClass, desc }); return metadata; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_19
crossvul-java_data_bad_1910_7
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.enigma2.internal; import java.io.IOException; import java.io.StringReader; import java.time.LocalDateTime; import java.util.Collection; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.lang.StringUtils; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jetty.util.UrlEncoded; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link Enigma2Client} class is responsible for communicating with the Enigma2 device. * * @see <a href= * "https://github.com/E2OpenPlugins/e2openplugin-OpenWebif/wiki/OpenWebif-API-documentation">OpenWebif-API-documentation</a> * * @author Guido Dolfen - Initial contribution */ @NonNullByDefault public class Enigma2Client { private final Logger logger = LoggerFactory.getLogger(Enigma2Client.class); static final String PATH_REMOTE_CONTROL = "/web/remotecontrol?command="; static final String PATH_POWER = "/web/powerstate"; static final String PATH_VOLUME = "/web/vol"; static final String PATH_SET_VOLUME = "/web/vol?set=set"; static final String PATH_TOGGLE_MUTE = "/web/vol?set=mute"; static final String PATH_TOGGLE_POWER = "/web/powerstate?newstate=0"; static final String PATH_MESSAGE = "/web/message?type="; static final String PATH_ALL_SERVICES = "/web/getallservices"; static final String PATH_ZAP = "/web/zap?sRef="; static final String PATH_CHANNEL = "/web/subservices"; static final String PATH_EPG = "/web/epgservicenow?sRef="; static final String PATH_ANSWER = "/web/messageanswer?getanswer=now"; static final int TYPE_QUESTION = 0; static final int TYPE_INFO = 1; static final int TYPE_WARNING = 2; static final int TYPE_ERROR = 3; private final Map<String, @Nullable String> channels = new ConcurrentHashMap<>(); private final String host; private boolean power; private String channel = ""; private String title = ""; private String description = ""; private String answer = ""; private int volume = 0; private boolean mute; private boolean online; private boolean initialized; private boolean asking; private LocalDateTime lastAnswerTime = LocalDateTime.of(2020, 1, 1, 0, 0); // Date in the past private final Enigma2HttpClient enigma2HttpClient; private final DocumentBuilderFactory factory; public Enigma2Client(String host, @Nullable String user, @Nullable String password, int requestTimeout) { this.enigma2HttpClient = new Enigma2HttpClient(requestTimeout); this.factory = DocumentBuilderFactory.newInstance(); if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(password)) { this.host = "http://" + user + ":" + password + "@" + host; } else { this.host = "http://" + host; } } public boolean refresh() { boolean wasOnline = online; refreshPower(); if (!wasOnline && online) { // Only refresh all services if the box changed from offline to online and power is on // because it is a performance intensive action. refreshAllServices(); } refreshChannel(); refreshEpg(); refreshVolume(); refreshAnswer(); return online; } public void refreshPower() { Optional<Document> document = transmitWithResult(PATH_POWER); if (document.isPresent()) { online = true; processPowerResult(document.get()); } else { online = false; power = false; } initialized = true; } public void refreshAllServices() { if (power || channels.isEmpty()) { transmitWithResult(PATH_ALL_SERVICES).ifPresent(this::processAllServicesResult); } } public void refreshChannel() { if (power) { transmitWithResult(PATH_CHANNEL).ifPresent(this::processChannelResult); } } public void refreshAnswer() { if (asking) { transmitWithResult(PATH_ANSWER).ifPresent(this::processAnswerResult); } } public void refreshVolume() { if (power) { transmitWithResult(PATH_VOLUME).ifPresent(this::processVolumeResult); } } public void refreshEpg() { if (power) { Optional.ofNullable(channels.get(channel)) .flatMap(name -> transmitWithResult(PATH_EPG + UrlEncoded.encodeString(name))) .ifPresent(this::processEpgResult); } } private Optional<Document> transmitWithResult(String path) { try { Optional<String> xml = transmit(path); if (xml.isPresent()) { DocumentBuilder builder = factory.newDocumentBuilder(); return Optional.ofNullable(builder.parse(new InputSource(new StringReader(xml.get())))); } return Optional.empty(); } catch (IOException | SAXException | ParserConfigurationException | IllegalArgumentException e) { if (online || !initialized) { logger.debug("Error on transmit {}{}.", host, path, e); } return Optional.empty(); } } private Optional<String> transmit(String path) { String url = host + path; try { logger.debug("Transmitting {}", url); String result = getEnigma2HttpClient().get(url); logger.debug("Transmitting result is {}", result); return Optional.ofNullable(result); } catch (IOException | IllegalArgumentException e) { if (online || !initialized) { logger.debug("Error on transmit {}.", url, e); } return Optional.empty(); } } public void setMute(boolean mute) { refreshVolume(); if (this.mute != mute) { transmitWithResult(PATH_TOGGLE_MUTE).ifPresent(this::processVolumeResult); } } public void setPower(boolean power) { refreshPower(); if (this.power != power) { transmitWithResult(PATH_TOGGLE_POWER).ifPresent(this::processPowerResult); } } public void setVolume(int volume) { transmitWithResult(PATH_SET_VOLUME + volume).ifPresent(this::processVolumeResult); } public void setChannel(String name) { if (channels.containsKey(name)) { String id = channels.get(name); transmitWithResult(PATH_ZAP + UrlEncoded.encodeString(id)).ifPresent(document -> channel = name); } else { logger.warn("Channel {} not found.", name); } } public void sendRcCommand(int key) { transmit(PATH_REMOTE_CONTROL + key); } public void sendError(int timeout, String text) { sendMessage(TYPE_ERROR, timeout, text); } public void sendWarning(int timeout, String text) { sendMessage(TYPE_WARNING, timeout, text); } public void sendInfo(int timeout, String text) { sendMessage(TYPE_INFO, timeout, text); } public void sendQuestion(int timeout, String text) { asking = true; sendMessage(TYPE_QUESTION, timeout, text); } private void sendMessage(int type, int timeout, String text) { transmit(PATH_MESSAGE + type + "&timeout=" + timeout + "&text=" + UrlEncoded.encodeString(text)); } private void processPowerResult(Document document) { power = !getBoolean(document, "e2instandby"); if (!power) { title = ""; description = ""; channel = ""; } } private void processChannelResult(Document document) { channel = getString(document, "e2servicename"); // Add channel-Reference-ID if not known if (!channels.containsKey(channel)) { channels.put(channel, getString(document, "e2servicereference")); } } private void processAnswerResult(Document document) { if (asking) { boolean state = getBoolean(document, "e2state"); if (state) { String[] text = getString(document, "e2statetext").split(" "); answer = text[text.length - 1].replace("!", ""); asking = false; lastAnswerTime = LocalDateTime.now(); } } } private void processVolumeResult(Document document) { volume = getInt(document, "e2current"); mute = getBoolean(document, "e2ismuted"); } private void processEpgResult(Document document) { title = getString(document, "e2eventtitle"); description = getString(document, "e2eventdescription"); } private void processAllServicesResult(Document document) { NodeList bouquetList = document.getElementsByTagName("e2bouquet"); channels.clear(); for (int i = 0; i < bouquetList.getLength(); i++) { Element bouquet = (Element) bouquetList.item(i); NodeList serviceList = bouquet.getElementsByTagName("e2service"); for (int j = 0; j < serviceList.getLength(); j++) { Element service = (Element) serviceList.item(j); String id = service.getElementsByTagName("e2servicereference").item(0).getTextContent(); String name = service.getElementsByTagName("e2servicename").item(0).getTextContent(); channels.put(name, id); } } } private String getString(Document document, String elementId) { return Optional.ofNullable(document.getElementsByTagName(elementId)).map(nodeList -> nodeList.item(0)) .map(Node::getTextContent).map(String::trim).orElse(""); } private boolean getBoolean(Document document, String elementId) { return Boolean.parseBoolean(getString(document, elementId)); } private int getInt(Document document, String elementId) { try { return Integer.parseInt(getString(document, elementId)); } catch (NumberFormatException e) { return 0; } } public int getVolume() { return volume; } public boolean isMute() { return mute; } public boolean isPower() { return power; } public LocalDateTime getLastAnswerTime() { return lastAnswerTime; } public String getChannel() { return channel; } public String getTitle() { return title; } public String getDescription() { return description; } public String getAnswer() { return answer; } public Collection<String> getChannels() { return channels.keySet(); } /** * Getter for Test-Injection * * @return HttpGet. */ Enigma2HttpClient getEnigma2HttpClient() { return enigma2HttpClient; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_7
crossvul-java_data_good_1910_9
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.fsinternetradio.internal.radio; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.CharacterData; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * This class hold the result of a request read from the radio. Upon a request the radio returns a XML document like * this: * * <pre> * <xmp> * <fsapiResponse> <status>FS_OK</status> <value><u8>1</u8></value> </fsapiResponse> * </xmp> * </pre> * * This class parses this XML data and provides functions for reading and casting typical fields. * * @author Rainer Ostendorf * @author Patrick Koenemann * */ public class FrontierSiliconRadioApiResult { /** * XML structure holding the parsed response */ final Document xmlDoc; private final Logger logger = LoggerFactory.getLogger(FrontierSiliconRadioApiResult.class); /** * Create result object from XML that was received from the radio. * * @param requestResultString * The XML string received from the radio. * @throws IOException in case the XML returned by the radio is invalid. */ public FrontierSiliconRadioApiResult(String requestResultString) throws IOException { Document xml = null; try { xml = getXmlDocFromString(requestResultString); } catch (Exception e) { logger.trace("converting to XML failed: '{}' with {}: {}", requestResultString, e.getClass().getName(), e.getMessage()); logger.debug("converting to XML failed with {}: {}", e.getClass().getName(), e.getMessage()); if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } xmlDoc = xml; } /** * Extract the field "status" from the result and return it * * @return result field as string. */ private String getStatus() { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element statusNode = (Element) fsApiResult.getElementsByTagName("status").item(0); final String status = getCharacterDataFromElement(statusNode); logger.trace("status is: {}", status); return status; } /** * checks if the responses status code was "FS_OK" * * @return true if status is "FS_OK", false else */ public boolean isStatusOk() { return ("FS_OK").equals(getStatus()); } /** * read the &lt;value&gt;&lt;u8&gt; field as boolean * * @return value.u8 field as bool */ public boolean getValueU8AsBoolean() { try { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element valueNode = (Element) fsApiResult.getElementsByTagName("value").item(0); final Element u8Node = (Element) valueNode.getElementsByTagName("u8").item(0); final String value = getCharacterDataFromElement(u8Node); logger.trace("value is: {}", value); return "1".equals(value); } catch (Exception e) { logger.error("getting Value.U8 failed with {}: {}", e.getClass().getName(), e.getMessage()); return false; } } /** * read the &lt;value&gt;&lt;u8&gt; field as int * * @return value.u8 field as int */ public int getValueU8AsInt() { try { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element valueNode = (Element) fsApiResult.getElementsByTagName("value").item(0); final Element u8Node = (Element) valueNode.getElementsByTagName("u8").item(0); final String value = getCharacterDataFromElement(u8Node); logger.trace("value is: {}", value); return Integer.parseInt(value); } catch (Exception e) { logger.error("getting Value.U8 failed with {}: {}", e.getClass().getName(), e.getMessage()); return 0; } } /** * read the &lt;value&gt;&lt;u32&gt; field as int * * @return value.u32 field as int */ public int getValueU32AsInt() { try { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element valueNode = (Element) fsApiResult.getElementsByTagName("value").item(0); final Element u32Node = (Element) valueNode.getElementsByTagName("u32").item(0); final String value = getCharacterDataFromElement(u32Node); logger.trace("value is: {}", value); return Integer.parseInt(value); } catch (Exception e) { logger.error("getting Value.U32 failed with {}: {}", e.getClass().getName(), e.getMessage()); return 0; } } /** * read the &lt;value&gt;&lt;c8_array&gt; field as String * * @return value.c8_array field as String */ public String getValueC8ArrayAsString() { try { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element valueNode = (Element) fsApiResult.getElementsByTagName("value").item(0); final Element c8Array = (Element) valueNode.getElementsByTagName("c8_array").item(0); final String value = getCharacterDataFromElement(c8Array); logger.trace("value is: {}", value); return value; } catch (Exception e) { logger.error("getting Value.c8array failed with {}: {}", e.getClass().getName(), e.getMessage()); return ""; } } /** * read the &lt;sessionId&gt; field as String * * @return value of sessionId field */ public String getSessionId() { final NodeList sessionIdTagList = xmlDoc.getElementsByTagName("sessionId"); final String givenSessId = getCharacterDataFromElement((Element) sessionIdTagList.item(0)); return givenSessId; } /** * converts the string we got from the radio to a parsable XML document * * @param xmlString * the XML string read from the radio * @return the parsed XML document * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ private Document getXmlDocFromString(String xmlString) throws ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setXIncludeAware(false); factory.setExpandEntityReferences(false); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document xmlDocument = builder.parse(new InputSource(new StringReader(xmlString))); return xmlDocument; } /** * convert the value of a given XML element to a string for further processing * * @param e * XML Element * @return the elements value converted to string */ private static String getCharacterDataFromElement(Element e) { final Node child = e.getFirstChild(); if (child instanceof CharacterData) { final CharacterData cd = (CharacterData) child; return cd.getData(); } return ""; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_9
crossvul-java_data_good_1910_5
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.denonmarantz.internal.handler; import static org.openhab.binding.denonmarantz.internal.DenonMarantzBindingConstants.*; import java.io.IOException; import java.io.StringReader; import java.net.HttpURLConnection; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.eclipse.jetty.client.HttpClient; import org.eclipse.jetty.client.api.ContentResponse; import org.eclipse.smarthome.config.core.Configuration; import org.eclipse.smarthome.core.thing.Channel; import org.eclipse.smarthome.core.thing.ChannelUID; import org.eclipse.smarthome.core.thing.Thing; import org.eclipse.smarthome.core.thing.ThingStatus; import org.eclipse.smarthome.core.thing.ThingStatusDetail; import org.eclipse.smarthome.core.thing.binding.BaseThingHandler; import org.eclipse.smarthome.core.thing.binding.builder.ChannelBuilder; import org.eclipse.smarthome.core.thing.type.ChannelTypeUID; import org.eclipse.smarthome.core.types.Command; import org.eclipse.smarthome.core.types.RefreshType; import org.eclipse.smarthome.core.types.State; import org.openhab.binding.denonmarantz.internal.DenonMarantzState; import org.openhab.binding.denonmarantz.internal.DenonMarantzStateChangedListener; import org.openhab.binding.denonmarantz.internal.UnsupportedCommandTypeException; import org.openhab.binding.denonmarantz.internal.config.DenonMarantzConfiguration; import org.openhab.binding.denonmarantz.internal.connector.DenonMarantzConnector; import org.openhab.binding.denonmarantz.internal.connector.DenonMarantzConnectorFactory; import org.openhab.binding.denonmarantz.internal.connector.http.DenonMarantzHttpConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * The {@link DenonMarantzHandler} is responsible for handling commands, which are * sent to one of the channels. * * @author Jan-Willem Veldhuis - Initial contribution */ public class DenonMarantzHandler extends BaseThingHandler implements DenonMarantzStateChangedListener { private final Logger logger = LoggerFactory.getLogger(DenonMarantzHandler.class); private static final int RETRY_TIME_SECONDS = 30; private HttpClient httpClient; private DenonMarantzConnector connector; private DenonMarantzConfiguration config; private DenonMarantzConnectorFactory connectorFactory = new DenonMarantzConnectorFactory(); private DenonMarantzState denonMarantzState; private ScheduledFuture<?> retryJob; public DenonMarantzHandler(Thing thing, HttpClient httpClient) { super(thing); this.httpClient = httpClient; } @Override public void handleCommand(ChannelUID channelUID, Command command) { if (connector == null) { return; } if (connector instanceof DenonMarantzHttpConnector && command instanceof RefreshType) { // Refreshing individual channels isn't supported by the Http connector. // The connector refreshes all channels together at the configured polling interval. return; } try { switch (channelUID.getId()) { case CHANNEL_POWER: connector.sendPowerCommand(command, 0); break; case CHANNEL_MAIN_ZONE_POWER: connector.sendPowerCommand(command, 1); break; case CHANNEL_MUTE: connector.sendMuteCommand(command, 1); break; case CHANNEL_MAIN_VOLUME: connector.sendVolumeCommand(command, 1); break; case CHANNEL_MAIN_VOLUME_DB: connector.sendVolumeDbCommand(command, 1); break; case CHANNEL_INPUT: connector.sendInputCommand(command, 1); break; case CHANNEL_SURROUND_PROGRAM: connector.sendSurroundProgramCommand(command); break; case CHANNEL_COMMAND: connector.sendCustomCommand(command); break; case CHANNEL_ZONE2_POWER: connector.sendPowerCommand(command, 2); break; case CHANNEL_ZONE2_MUTE: connector.sendMuteCommand(command, 2); break; case CHANNEL_ZONE2_VOLUME: connector.sendVolumeCommand(command, 2); break; case CHANNEL_ZONE2_VOLUME_DB: connector.sendVolumeDbCommand(command, 2); break; case CHANNEL_ZONE2_INPUT: connector.sendInputCommand(command, 2); break; case CHANNEL_ZONE3_POWER: connector.sendPowerCommand(command, 3); break; case CHANNEL_ZONE3_MUTE: connector.sendMuteCommand(command, 3); break; case CHANNEL_ZONE3_VOLUME: connector.sendVolumeCommand(command, 3); break; case CHANNEL_ZONE3_VOLUME_DB: connector.sendVolumeDbCommand(command, 3); break; case CHANNEL_ZONE3_INPUT: connector.sendInputCommand(command, 3); break; case CHANNEL_ZONE4_POWER: connector.sendPowerCommand(command, 4); break; case CHANNEL_ZONE4_MUTE: connector.sendMuteCommand(command, 4); break; case CHANNEL_ZONE4_VOLUME: connector.sendVolumeCommand(command, 4); break; case CHANNEL_ZONE4_VOLUME_DB: connector.sendVolumeDbCommand(command, 4); break; case CHANNEL_ZONE4_INPUT: connector.sendInputCommand(command, 4); break; default: throw new UnsupportedCommandTypeException(); } } catch (UnsupportedCommandTypeException e) { logger.debug("Unsupported command {} for channel {}", command, channelUID.getId()); } } public boolean checkConfiguration() { // prevent too low values for polling interval if (config.httpPollingInterval < 5) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "The polling interval should be at least 5 seconds!"); return false; } // Check zone count is within supported range if (config.getZoneCount() < 1 || config.getZoneCount() > 4) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "This binding supports 1 to 4 zones. Please update the zone count."); return false; } return true; } /** * Try to auto configure the connection type (Telnet or HTTP) * for Things not added through Paper UI. */ private void autoConfigure() { /* * The isTelnet parameter has no default. * When not set we will try to auto-detect the correct values * for isTelnet and zoneCount and update the Thing accordingly. */ if (config.isTelnet() == null) { logger.debug("Trying to auto-detect the connection."); ContentResponse response; boolean telnetEnable = true; int httpPort = 80; boolean httpApiUsable = false; // try to reach the HTTP API at port 80 (most models, except Denon ...H should respond. String host = config.getHost(); try { response = httpClient.newRequest("http://" + host + "/goform/Deviceinfo.xml") .timeout(3, TimeUnit.SECONDS).send(); if (response.getStatus() == HttpURLConnection.HTTP_OK) { logger.debug("We can access the HTTP API, disabling the Telnet mode by default."); telnetEnable = false; httpApiUsable = true; } } catch (InterruptedException | TimeoutException | ExecutionException e) { logger.debug("Error when trying to access AVR using HTTP on port 80, reverting to Telnet mode.", e); } if (telnetEnable) { // the above attempt failed. Let's try on port 8080, as for some models a subset of the HTTP API is // available try { response = httpClient.newRequest("http://" + host + ":8080/goform/Deviceinfo.xml") .timeout(3, TimeUnit.SECONDS).send(); if (response.getStatus() == HttpURLConnection.HTTP_OK) { logger.debug( "This model responds to HTTP port 8080, we use this port to retrieve the number of zones."); httpPort = 8080; httpApiUsable = true; } } catch (InterruptedException | TimeoutException | ExecutionException e) { logger.debug("Additionally tried to connect to port 8080, this also failed", e); } } // default zone count int zoneCount = 2; // try to determine the zone count by checking the Deviceinfo.xml file if (httpApiUsable) { int status = 0; response = null; try { response = httpClient.newRequest("http://" + host + ":" + httpPort + "/goform/Deviceinfo.xml") .timeout(3, TimeUnit.SECONDS).send(); status = response.getStatus(); } catch (InterruptedException | TimeoutException | ExecutionException e) { logger.debug("Failed in fetching the Deviceinfo.xml to determine zone count", e); } if (status == HttpURLConnection.HTTP_OK && response != null) { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { // see // https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html domFactory.setFeature("http://xml.org/sax/features/external-general-entities", false); domFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); domFactory.setXIncludeAware(false); domFactory.setExpandEntityReferences(false); DocumentBuilder builder; builder = domFactory.newDocumentBuilder(); Document dDoc = builder.parse(new InputSource(new StringReader(response.getContentAsString()))); XPath xPath = XPathFactory.newInstance().newXPath(); Node node = (Node) xPath.evaluate("/Device_Info/DeviceZones/text()", dDoc, XPathConstants.NODE); if (node != null) { String nodeValue = node.getNodeValue(); logger.trace("/Device_Info/DeviceZones/text() = {}", nodeValue); zoneCount = Integer.parseInt(nodeValue); logger.debug("Discovered number of zones: {}", zoneCount); } } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | NumberFormatException e) { logger.debug("Something went wrong with looking up the zone count in Deviceinfo.xml: {}", e.getMessage()); } } } config.setTelnet(telnetEnable); config.setZoneCount(zoneCount); Configuration configuration = editConfiguration(); configuration.put(PARAMETER_TELNET_ENABLED, telnetEnable); configuration.put(PARAMETER_ZONE_COUNT, zoneCount); updateConfiguration(configuration); } } @Override public void initialize() { cancelRetry(); config = getConfigAs(DenonMarantzConfiguration.class); // Configure Connection type (Telnet/HTTP) and number of zones // Note: this only happens for discovered Things autoConfigure(); if (!checkConfiguration()) { return; } denonMarantzState = new DenonMarantzState(this); configureZoneChannels(); updateStatus(ThingStatus.UNKNOWN); // create connection (either Telnet or HTTP) // ThingStatus ONLINE/OFFLINE is set when AVR status is known. createConnection(); } private void createConnection() { if (connector != null) { connector.dispose(); } connector = connectorFactory.getConnector(config, denonMarantzState, scheduler, httpClient); connector.connect(); } private void cancelRetry() { ScheduledFuture<?> localRetryJob = retryJob; if (localRetryJob != null && !localRetryJob.isDone()) { localRetryJob.cancel(false); } } private void configureZoneChannels() { logger.debug("Configuring zone channels"); Integer zoneCount = config.getZoneCount(); List<Channel> channels = new ArrayList<>(this.getThing().getChannels()); boolean channelsUpdated = false; // construct a set with the existing channel type UIDs, to quickly check Set<String> currentChannels = new HashSet<>(); channels.forEach(channel -> currentChannels.add(channel.getUID().getId())); Set<Entry<String, ChannelTypeUID>> channelsToRemove = new HashSet<>(); if (zoneCount > 1) { List<Entry<String, ChannelTypeUID>> channelsToAdd = new ArrayList<>(ZONE2_CHANNEL_TYPES.entrySet()); if (zoneCount > 2) { // add channels for zone 3 channelsToAdd.addAll(ZONE3_CHANNEL_TYPES.entrySet()); if (zoneCount > 3) { // add channels for zone 4 (more zones currently not supported) channelsToAdd.addAll(ZONE4_CHANNEL_TYPES.entrySet()); } else { channelsToRemove.addAll(ZONE4_CHANNEL_TYPES.entrySet()); } } else { channelsToRemove.addAll(ZONE3_CHANNEL_TYPES.entrySet()); channelsToRemove.addAll(ZONE4_CHANNEL_TYPES.entrySet()); } // filter out the already existing channels channelsToAdd.removeIf(c -> currentChannels.contains(c.getKey())); // add the channels that were not yet added if (!channelsToAdd.isEmpty()) { for (Entry<String, ChannelTypeUID> entry : channelsToAdd) { String itemType = CHANNEL_ITEM_TYPES.get(entry.getKey()); Channel channel = ChannelBuilder .create(new ChannelUID(this.getThing().getUID(), entry.getKey()), itemType) .withType(entry.getValue()).build(); channels.add(channel); } channelsUpdated = true; } else { logger.debug("No zone channels have been added"); } } else { channelsToRemove.addAll(ZONE2_CHANNEL_TYPES.entrySet()); channelsToRemove.addAll(ZONE3_CHANNEL_TYPES.entrySet()); channelsToRemove.addAll(ZONE4_CHANNEL_TYPES.entrySet()); } // filter out the non-existing channels channelsToRemove.removeIf(c -> !currentChannels.contains(c.getKey())); // remove the channels that were not yet added if (!channelsToRemove.isEmpty()) { for (Entry<String, ChannelTypeUID> entry : channelsToRemove) { if (channels.removeIf(c -> (entry.getKey()).equals(c.getUID().getId()))) { logger.trace("Removed channel {}", entry.getKey()); } else { logger.trace("Could NOT remove channel {}", entry.getKey()); } } channelsUpdated = true; } else { logger.debug("No zone channels have been removed"); } // update Thing if channels changed if (channelsUpdated) { updateThing(editThing().withChannels(channels).build()); } } @Override public void dispose() { if (connector != null) { connector.dispose(); connector = null; } cancelRetry(); super.dispose(); } @Override public void channelLinked(ChannelUID channelUID) { super.channelLinked(channelUID); String channelID = channelUID.getId(); if (isLinked(channelID)) { State state = denonMarantzState.getStateForChannelID(channelID); if (state != null) { updateState(channelID, state); } } } @Override public void stateChanged(String channelID, State state) { logger.debug("Received state {} for channelID {}", state, channelID); // Don't flood the log with thing 'updated: ONLINE' each time a single channel changed if (this.getThing().getStatus() != ThingStatus.ONLINE) { updateStatus(ThingStatus.ONLINE); } updateState(channelID, state); } @Override public void connectionError(String errorMessage) { if (this.getThing().getStatus() != ThingStatus.OFFLINE) { // Don't flood the log with thing 'updated: OFFLINE' when already offline updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, errorMessage); } connector.dispose(); retryJob = scheduler.schedule(this::createConnection, RETRY_TIME_SECONDS, TimeUnit.SECONDS); } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_1910_5
crossvul-java_data_good_3875_1
/* * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. * * This software is open source. * See the bottom of this file for the licence. */ package org.dom4j.io; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import javax.xml.parsers.SAXParserFactory; /** * <p> * <code>SAXHelper</code> contains some helper methods for working with SAX * and XMLReader objects. * </p> * * @author <a href="mailto:james.strachan@metastuff.com">James Strachan </a> * @version $Revision: 1.18 $ */ class SAXHelper { private static boolean loggedWarning = true; protected SAXHelper() { } public static boolean setParserProperty(XMLReader reader, String propertyName, Object value) { try { reader.setProperty(propertyName, value); return true; } catch (SAXNotSupportedException e) { // ignore } catch (SAXNotRecognizedException e) { // ignore } return false; } public static boolean setParserFeature(XMLReader reader, String featureName, boolean value) { try { reader.setFeature(featureName, value); return true; } catch (SAXNotSupportedException e) { // ignore } catch (SAXNotRecognizedException e) { // ignore } return false; } /** * Creats a default XMLReader via the org.xml.sax.driver system property or * JAXP if the system property is not set. * * This method internally calls {@link SAXParserFactory}{@code .newInstance().newSAXParser().getXMLReader()} or {@link XMLReaderFactory#createXMLReader()}. * Be sure to configure returned reader if the default configuration does not suit you. Consider setting the following properties: * * <pre> * reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); * reader.setFeature("http://xml.org/sax/features/external-general-entities", false); * reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false); * </pre> * * @param validating * DOCUMENT ME! * * @return DOCUMENT ME! * * @throws SAXException * DOCUMENT ME! */ public static XMLReader createXMLReader(boolean validating) throws SAXException { XMLReader reader = null; if (reader == null) { reader = createXMLReaderViaJAXP(validating, true); } if (reader == null) { try { reader = XMLReaderFactory.createXMLReader(); } catch (Exception e) { if (isVerboseErrorReporting()) { // log all exceptions as warnings and carry // on as we have a default SAX parser we can use System.out.println("Warning: Caught exception attempting " + "to use SAX to load a SAX XMLReader "); System.out.println("Warning: Exception was: " + e); System.out .println("Warning: I will print the stack trace " + "then carry on using the default " + "SAX parser"); e.printStackTrace(); } throw new SAXException(e); } } if (reader == null) { throw new SAXException("Couldn't create SAX reader"); } // configure namespace support SAXHelper.setParserFeature(reader, "http://xml.org/sax/features/namespaces", true); SAXHelper.setParserFeature(reader, "http://xml.org/sax/features/namespace-prefixes", false); // external entites SAXHelper.setParserFeature(reader, "http://xml.org/sax/properties/external-general-entities", false); SAXHelper.setParserFeature(reader, "http://xml.org/sax/properties/external-parameter-entities", false); // external DTD SAXHelper.setParserFeature(reader,"http://apache.org/xml/features/nonvalidating/load-external-dtd", false); // use Locator2 if possible SAXHelper.setParserFeature(reader,"http://xml.org/sax/features/use-locator2", true); return reader; } /** * This method attempts to use JAXP to locate the SAX2 XMLReader * implementation. This method uses reflection to avoid being dependent * directly on the JAXP classes. * * @param validating * DOCUMENT ME! * @param namespaceAware * DOCUMENT ME! * * @return DOCUMENT ME! */ protected static XMLReader createXMLReaderViaJAXP(boolean validating, boolean namespaceAware) { // try use JAXP to load the XMLReader... try { return JAXPHelper.createXMLReader(validating, namespaceAware); } catch (Throwable e) { if (!loggedWarning) { loggedWarning = true; if (isVerboseErrorReporting()) { // log all exceptions as warnings and carry // on as we have a default SAX parser we can use System.out.println("Warning: Caught exception attempting " + "to use JAXP to load a SAX XMLReader"); System.out.println("Warning: Exception was: " + e); e.printStackTrace(); } } } return null; } protected static boolean isVerboseErrorReporting() { try { String flag = System.getProperty("org.dom4j.verbose"); if ((flag != null) && flag.equalsIgnoreCase("true")) { return true; } } catch (Exception e) { // in case a security exception // happens in an applet or similar JVM } return true; } } /* * Redistribution and use of this software and associated documentation * ("Software"), with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain copyright statements and * notices. Redistributions must also contain a copy of this document. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name "DOM4J" must not be used to endorse or promote products derived * from this Software without prior written permission of MetaStuff, Ltd. For * written permission, please contact dom4j-info@metastuff.com. * * 4. Products derived from this Software may not be called "DOM4J" nor may * "DOM4J" appear in their names without prior written permission of MetaStuff, * Ltd. DOM4J is a registered trademark of MetaStuff, Ltd. * * 5. Due credit should be given to the DOM4J Project - http://www.dom4j.org * * THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL METASTUFF, LTD. OR ITS CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. */
./CrossVul/dataset_final_sorted/CWE-611/java/good_3875_1
crossvul-java_data_good_4033_4
/* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.jdbc; import org.postgresql.core.BaseConnection; import org.postgresql.util.GT; import org.postgresql.util.PSQLException; import org.postgresql.util.PSQLState; import org.postgresql.xml.DefaultPGXmlFactoryFactory; import org.postgresql.xml.PGXmlFactoryFactory; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.sql.SQLException; import java.sql.SQLXML; import javax.xml.parsers.DocumentBuilder; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stax.StAXResult; import javax.xml.transform.stax.StAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; public class PgSQLXML implements SQLXML { private final BaseConnection conn; private String data; // The actual data contained. private boolean initialized; // Has someone assigned the data for this object? private boolean active; // Is anyone in the process of loading data into us? private boolean freed; private ByteArrayOutputStream byteArrayOutputStream; private StringWriter stringWriter; private DOMResult domResult; public PgSQLXML(BaseConnection conn) { this(conn, null, false); } public PgSQLXML(BaseConnection conn, String data) { this(conn, data, true); } private PgSQLXML(BaseConnection conn, String data, boolean initialized) { this.conn = conn; this.data = data; this.initialized = initialized; this.active = false; this.freed = false; } private PGXmlFactoryFactory getXmlFactoryFactory() throws SQLException { if (conn != null) { return conn.getXmlFactoryFactory(); } return DefaultPGXmlFactoryFactory.INSTANCE; } @Override public synchronized void free() { freed = true; data = null; } @Override public synchronized InputStream getBinaryStream() throws SQLException { checkFreed(); ensureInitialized(); if (data == null) { return null; } try { return new ByteArrayInputStream(conn.getEncoding().encode(data)); } catch (IOException ioe) { // This should be a can't happen exception. We just // decoded this data, so it would be surprising that // we couldn't encode it. // For this reason don't make it translatable. throw new PSQLException("Failed to re-encode xml data.", PSQLState.DATA_ERROR, ioe); } } @Override public synchronized Reader getCharacterStream() throws SQLException { checkFreed(); ensureInitialized(); if (data == null) { return null; } return new StringReader(data); } // We must implement this unsafely because that's what the // interface requires. Because it says we're returning T // which is unknown, none of the return values can satisfy it // as Java isn't going to understand the if statements that // ensure they are the same. // @Override public synchronized <T extends Source> T getSource(Class<T> sourceClass) throws SQLException { checkFreed(); ensureInitialized(); if (data == null) { return null; } try { if (sourceClass == null || DOMSource.class.equals(sourceClass)) { DocumentBuilder builder = getXmlFactoryFactory().newDocumentBuilder(); InputSource input = new InputSource(new StringReader(data)); return (T) new DOMSource(builder.parse(input)); } else if (SAXSource.class.equals(sourceClass)) { XMLReader reader = getXmlFactoryFactory().createXMLReader(); InputSource is = new InputSource(new StringReader(data)); return (T) new SAXSource(reader, is); } else if (StreamSource.class.equals(sourceClass)) { return (T) new StreamSource(new StringReader(data)); } else if (StAXSource.class.equals(sourceClass)) { XMLInputFactory xif = getXmlFactoryFactory().newXMLInputFactory(); XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(data)); return (T) new StAXSource(xsr); } } catch (Exception e) { throw new PSQLException(GT.tr("Unable to decode xml data."), PSQLState.DATA_ERROR, e); } throw new PSQLException(GT.tr("Unknown XML Source class: {0}", sourceClass), PSQLState.INVALID_PARAMETER_TYPE); } @Override public synchronized String getString() throws SQLException { checkFreed(); ensureInitialized(); return data; } @Override public synchronized OutputStream setBinaryStream() throws SQLException { checkFreed(); initialize(); active = true; byteArrayOutputStream = new ByteArrayOutputStream(); return byteArrayOutputStream; } @Override public synchronized Writer setCharacterStream() throws SQLException { checkFreed(); initialize(); active = true; stringWriter = new StringWriter(); return stringWriter; } @Override public synchronized <T extends Result> T setResult(Class<T> resultClass) throws SQLException { checkFreed(); initialize(); if (resultClass == null || DOMResult.class.equals(resultClass)) { domResult = new DOMResult(); active = true; return (T) domResult; } else if (SAXResult.class.equals(resultClass)) { try { SAXTransformerFactory transformerFactory = getXmlFactoryFactory().newSAXTransformerFactory(); TransformerHandler transformerHandler = transformerFactory.newTransformerHandler(); stringWriter = new StringWriter(); transformerHandler.setResult(new StreamResult(stringWriter)); active = true; return (T) new SAXResult(transformerHandler); } catch (TransformerException te) { throw new PSQLException(GT.tr("Unable to create SAXResult for SQLXML."), PSQLState.UNEXPECTED_ERROR, te); } } else if (StreamResult.class.equals(resultClass)) { stringWriter = new StringWriter(); active = true; return (T) new StreamResult(stringWriter); } else if (StAXResult.class.equals(resultClass)) { stringWriter = new StringWriter(); try { XMLOutputFactory xof = getXmlFactoryFactory().newXMLOutputFactory(); XMLStreamWriter xsw = xof.createXMLStreamWriter(stringWriter); active = true; return (T) new StAXResult(xsw); } catch (XMLStreamException xse) { throw new PSQLException(GT.tr("Unable to create StAXResult for SQLXML"), PSQLState.UNEXPECTED_ERROR, xse); } } throw new PSQLException(GT.tr("Unknown XML Result class: {0}", resultClass), PSQLState.INVALID_PARAMETER_TYPE); } @Override public synchronized void setString(String value) throws SQLException { checkFreed(); initialize(); data = value; } private void checkFreed() throws SQLException { if (freed) { throw new PSQLException(GT.tr("This SQLXML object has already been freed."), PSQLState.OBJECT_NOT_IN_STATE); } } private void ensureInitialized() throws SQLException { if (!initialized) { throw new PSQLException( GT.tr( "This SQLXML object has not been initialized, so you cannot retrieve data from it."), PSQLState.OBJECT_NOT_IN_STATE); } // Is anyone loading data into us at the moment? if (!active) { return; } if (byteArrayOutputStream != null) { try { data = conn.getEncoding().decode(byteArrayOutputStream.toByteArray()); } catch (IOException ioe) { throw new PSQLException(GT.tr("Failed to convert binary xml data to encoding: {0}.", conn.getEncoding().name()), PSQLState.DATA_ERROR, ioe); } finally { byteArrayOutputStream = null; active = false; } } else if (stringWriter != null) { // This is also handling the work for Stream, SAX, and StAX Results // as they will use the same underlying stringwriter variable. // data = stringWriter.toString(); stringWriter = null; active = false; } else if (domResult != null) { // Copy the content from the result to a source // and use the identify transform to get it into a // friendlier result format. try { TransformerFactory factory = getXmlFactoryFactory().newTransformerFactory(); Transformer transformer = factory.newTransformer(); DOMSource domSource = new DOMSource(domResult.getNode()); StringWriter stringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(stringWriter); transformer.transform(domSource, streamResult); data = stringWriter.toString(); } catch (TransformerException te) { throw new PSQLException(GT.tr("Unable to convert DOMResult SQLXML data to a string."), PSQLState.DATA_ERROR, te); } finally { domResult = null; active = false; } } } private void initialize() throws SQLException { if (initialized) { throw new PSQLException( GT.tr( "This SQLXML object has already been initialized, so you cannot manipulate it further."), PSQLState.OBJECT_NOT_IN_STATE); } initialized = true; } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4033_4
crossvul-java_data_bad_1910_15
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.insteon.internal.device; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.eclipse.smarthome.core.library.types.DecimalType; import org.eclipse.smarthome.core.library.types.IncreaseDecreaseType; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.types.Command; import org.openhab.binding.insteon.internal.utils.Utils; import org.openhab.binding.insteon.internal.utils.Utils.ParsingException; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; /** * Class that loads the device feature templates from an xml stream * * @author Daniel Pfrommer - Initial contribution * @author Rob Nielsen - Port to openHAB 2 insteon binding */ @NonNullByDefault public class FeatureTemplateLoader { public static List<FeatureTemplate> readTemplates(InputStream input) throws IOException, ParsingException { List<FeatureTemplate> features = new ArrayList<>(); try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); // Parse it! Document doc = dBuilder.parse(input); doc.getDocumentElement().normalize(); Element root = doc.getDocumentElement(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) node; if (e.getTagName().equals("feature")) { features.add(parseFeature(e)); } } } } catch (SAXException e) { throw new ParsingException("Failed to parse XML!", e); } catch (ParserConfigurationException e) { throw new ParsingException("Got parser config exception! ", e); } return features; } private static FeatureTemplate parseFeature(Element e) throws ParsingException { String name = e.getAttribute("name"); boolean statusFeature = e.getAttribute("statusFeature").equals("true"); FeatureTemplate feature = new FeatureTemplate(name, statusFeature, e.getAttribute("timeout")); NodeList nodes = e.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element child = (Element) node; if (child.getTagName().equals("message-handler")) { parseMessageHandler(child, feature); } else if (child.getTagName().equals("command-handler")) { parseCommandHandler(child, feature); } else if (child.getTagName().equals("message-dispatcher")) { parseMessageDispatcher(child, feature); } else if (child.getTagName().equals("poll-handler")) { parsePollHandler(child, feature); } } } return feature; } private static HandlerEntry makeHandlerEntry(Element e) throws ParsingException { String handler = e.getTextContent(); if (handler == null) { throw new ParsingException("Could not find Handler for: " + e.getTextContent()); } NamedNodeMap attributes = e.getAttributes(); Map<String, @Nullable String> params = new HashMap<>(); for (int i = 0; i < attributes.getLength(); i++) { Node n = attributes.item(i); params.put(n.getNodeName(), n.getNodeValue()); } return new HandlerEntry(handler, params); } private static void parseMessageHandler(Element e, FeatureTemplate f) throws DOMException, ParsingException { HandlerEntry he = makeHandlerEntry(e); if (e.getAttribute("default").equals("true")) { f.setDefaultMessageHandler(he); } else { String attr = e.getAttribute("cmd"); int command = (attr == null) ? 0 : Utils.from0xHexString(attr); f.addMessageHandler(command, he); } } private static void parseCommandHandler(Element e, FeatureTemplate f) throws ParsingException { HandlerEntry he = makeHandlerEntry(e); if (e.getAttribute("default").equals("true")) { f.setDefaultCommandHandler(he); } else { Class<? extends Command> command = parseCommandClass(e.getAttribute("command")); f.addCommandHandler(command, he); } } private static void parseMessageDispatcher(Element e, FeatureTemplate f) throws DOMException, ParsingException { HandlerEntry he = makeHandlerEntry(e); f.setMessageDispatcher(he); } private static void parsePollHandler(Element e, FeatureTemplate f) throws ParsingException { HandlerEntry he = makeHandlerEntry(e); f.setPollHandler(he); } private static Class<? extends Command> parseCommandClass(String c) throws ParsingException { if (c.equals("OnOffType")) { return OnOffType.class; } else if (c.equals("PercentType")) { return PercentType.class; } else if (c.equals("DecimalType")) { return DecimalType.class; } else if (c.equals("IncreaseDecreaseType")) { return IncreaseDecreaseType.class; } else { throw new ParsingException("Unknown Command Type"); } } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_15
crossvul-java_data_good_4362_1
/** * (The MIT License) * * Copyright (c) 2008 - 2011: * * * {Aaron Patterson}[http://tenderlovemaking.com] * * {Mike Dalessio}[http://mike.daless.io] * * {Charles Nutter}[http://blog.headius.com] * * {Sergio Arbeo}[http://www.serabe.com] * * {Patrick Mahoney}[http://polycrystal.org] * * {Yoko Harada}[http://yokolet.blogspot.com] * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package nokogiri; import static nokogiri.internals.NokogiriHelpers.adjustSystemIdIfNecessary; import static nokogiri.internals.NokogiriHelpers.getNokogiriClass; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import javax.xml.XMLConstants; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import nokogiri.internals.IgnoreSchemaErrorsErrorHandler; import nokogiri.internals.SchemaErrorHandler; import nokogiri.internals.XmlDomParserContext; import org.jruby.Ruby; import org.jruby.RubyArray; import org.jruby.RubyClass; import org.jruby.RubyFixnum; import org.jruby.RubyObject; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; import org.jruby.exceptions.RaiseException; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.Visibility; import org.jruby.runtime.builtin.IRubyObject; import org.w3c.dom.Document; import org.w3c.dom.ls.LSInput; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * Class for Nokogiri::XML::Schema * * @author sergio * @author Yoko Harada <yokolet@gmail.com> */ @JRubyClass(name="Nokogiri::XML::Schema") public class XmlSchema extends RubyObject { private Validator validator; public XmlSchema(Ruby ruby, RubyClass klazz) { super(ruby, klazz); } /** * Create and return a copy of this object. * * @return a clone of this object */ @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } private Schema getSchema(Source source, String currentDir, String scriptFileName, SchemaErrorHandler error_handler) throws SAXException { SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); SchemaResourceResolver resourceResolver = new SchemaResourceResolver(currentDir, scriptFileName, null, error_handler); schemaFactory.setResourceResolver(resourceResolver); schemaFactory.setErrorHandler(error_handler); return schemaFactory.newSchema(source); } private void setValidator(Validator validator) { this.validator = validator; } static XmlSchema createSchemaInstance(ThreadContext context, RubyClass klazz, Source source, IRubyObject parseOptions) { Ruby runtime = context.getRuntime(); XmlSchema xmlSchema = (XmlSchema) NokogiriService.XML_SCHEMA_ALLOCATOR.allocate(runtime, klazz); if (parseOptions == null) { parseOptions = defaultParseOptions(context.getRuntime()); } xmlSchema.setInstanceVariable("@errors", runtime.newEmptyArray()); xmlSchema.setInstanceVariable("@parse_options", parseOptions); try { SchemaErrorHandler error_handler = new SchemaErrorHandler(context.getRuntime(), (RubyArray)xmlSchema.getInstanceVariable("@errors")); Schema schema = xmlSchema.getSchema(source, context.getRuntime().getCurrentDirectory(), context.getRuntime().getInstanceConfig().getScriptFileName(), error_handler); xmlSchema.setValidator(schema.newValidator()); return xmlSchema; } catch (SAXException ex) { throw context.getRuntime().newRuntimeError("Could not parse document: " + ex.getMessage()); } } protected static IRubyObject defaultParseOptions(Ruby runtime) { return ((RubyClass)runtime.getClassFromPath("Nokogiri::XML::ParseOptions")).getConstant("DEFAULT_SCHEMA"); } /* * call-seq: * from_document(doc) * * Create a new Schema from the Nokogiri::XML::Document +doc+ */ @JRubyMethod(meta=true, required=1, optional=1) public static IRubyObject from_document(ThreadContext context, IRubyObject klazz, IRubyObject[] args) { IRubyObject document = args[0]; IRubyObject parseOptions = null; if (args.length > 1) { parseOptions = args[1]; } XmlDocument doc = ((XmlDocument) ((XmlNode) document).document(context)); RubyArray errors = (RubyArray) doc.getInstanceVariable("@errors"); if (!errors.isEmpty()) { throw ((XmlSyntaxError) errors.first()).toThrowable(); } DOMSource source = new DOMSource(doc.getDocument()); IRubyObject uri = doc.url(context); if (!uri.isNil()) { source.setSystemId(uri.convertToString().asJavaString()); } return getSchema(context, (RubyClass)klazz, source, parseOptions); } @JRubyMethod(meta=true, required=1, optional=1) public static IRubyObject read_memory(ThreadContext context, IRubyObject klazz, IRubyObject[] args) { IRubyObject content = args[0]; IRubyObject parseOptions = null; if (args.length > 1) { parseOptions = args[1]; } String data = content.convertToString().asJavaString(); return getSchema(context, (RubyClass) klazz, new StreamSource(new StringReader(data)), parseOptions); } private static IRubyObject getSchema(ThreadContext context, RubyClass klazz, Source source, IRubyObject parseOptions) { String moduleName = klazz.getName(); if ("Nokogiri::XML::Schema".equals(moduleName)) { return XmlSchema.createSchemaInstance(context, klazz, source, parseOptions); } else if ("Nokogiri::XML::RelaxNG".equals(moduleName)) { return XmlRelaxng.createSchemaInstance(context, klazz, source, parseOptions); } return context.getRuntime().getNil(); } @JRubyMethod(visibility=Visibility.PRIVATE) public IRubyObject validate_document(ThreadContext context, IRubyObject document) { return validate_document_or_file(context, (XmlDocument)document); } @JRubyMethod(visibility=Visibility.PRIVATE) public IRubyObject validate_file(ThreadContext context, IRubyObject file) { Ruby runtime = context.runtime; XmlDomParserContext ctx = new XmlDomParserContext(runtime, RubyFixnum.newFixnum(runtime, 1L)); ctx.setInputSourceFile(context, file); XmlDocument xmlDocument = ctx.parse(context, getNokogiriClass(runtime, "Nokogiri::XML::Document"), context.nil); return validate_document_or_file(context, xmlDocument); } IRubyObject validate_document_or_file(ThreadContext context, XmlDocument xmlDocument) { RubyArray errors = (RubyArray) this.getInstanceVariable("@errors"); ErrorHandler errorHandler = new SchemaErrorHandler(context.runtime, errors); setErrorHandler(errorHandler); try { validate(xmlDocument.getDocument()); } catch (SAXException ex) { XmlSyntaxError xmlSyntaxError = XmlSyntaxError.createXMLSyntaxError(context.runtime); xmlSyntaxError.setException(ex); errors.append(xmlSyntaxError); } catch (IOException ex) { throw context.runtime.newIOError(ex.getMessage()); } return errors; } protected void setErrorHandler(ErrorHandler errorHandler) { validator.setErrorHandler(errorHandler); } protected void validate(Document document) throws SAXException, IOException { DOMSource docSource = new DOMSource(document); validator.validate(docSource); } private class SchemaResourceResolver implements LSResourceResolver { SchemaLSInput lsInput = new SchemaLSInput(); String currentDir; String scriptFileName; SchemaErrorHandler error_handler; //String defaultURI; SchemaResourceResolver(String currentDir, String scriptFileName, Object input, SchemaErrorHandler error_handler) { this.currentDir = currentDir; this.scriptFileName = scriptFileName; this.error_handler = error_handler; if (input == null) return; if (input instanceof String) { lsInput.setStringData((String)input); } else if (input instanceof Reader) { lsInput.setCharacterStream((Reader)input); } else if (input instanceof InputStream) { lsInput.setByteStream((InputStream)input); } } @Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { String adjusted = adjustSystemIdIfNecessary(currentDir, scriptFileName, baseURI, systemId); lsInput.setPublicId(publicId); lsInput.setSystemId(adjusted != null? adjusted : systemId); lsInput.setBaseURI(baseURI); return lsInput; } } private class SchemaLSInput implements LSInput { protected String fPublicId; protected String fSystemId; protected String fBaseSystemId; protected InputStream fByteStream; protected Reader fCharStream; protected String fData; protected String fEncoding; protected boolean fCertifiedText = false; @Override public String getBaseURI() { return fBaseSystemId; } @Override public InputStream getByteStream() { return fByteStream; } @Override public boolean getCertifiedText() { return fCertifiedText; } @Override public Reader getCharacterStream() { return fCharStream; } @Override public String getEncoding() { return fEncoding; } @Override public String getPublicId() { return fPublicId; } @Override public String getStringData() { return fData; } @Override public String getSystemId() { return fSystemId; } @Override public void setBaseURI(String baseURI) { fBaseSystemId = baseURI; } @Override public void setByteStream(InputStream byteStream) { fByteStream = byteStream; } @Override public void setCertifiedText(boolean certified) { fCertifiedText = certified; } @Override public void setCharacterStream(Reader charStream) { fCharStream = charStream; } @Override public void setEncoding(String encoding) { fEncoding = encoding; } @Override public void setPublicId(String pubId) { fPublicId = pubId; } @Override public void setStringData(String stringData) { fData = stringData; } @Override public void setSystemId(String sysId) { fSystemId = sysId; } } }
./CrossVul/dataset_final_sorted/CWE-611/java/good_4362_1
crossvul-java_data_bad_1910_9
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.fsinternetradio.internal.radio; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.CharacterData; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * This class hold the result of a request read from the radio. Upon a request the radio returns a XML document like * this: * * <pre> * <xmp> * <fsapiResponse> <status>FS_OK</status> <value><u8>1</u8></value> </fsapiResponse> * </xmp> * </pre> * * This class parses this XML data and provides functions for reading and casting typical fields. * * @author Rainer Ostendorf * @author Patrick Koenemann * */ public class FrontierSiliconRadioApiResult { /** * XML structure holding the parsed response */ final Document xmlDoc; private final Logger logger = LoggerFactory.getLogger(FrontierSiliconRadioApiResult.class); /** * Create result object from XML that was received from the radio. * * @param requestResultString * The XML string received from the radio. * @throws IOException in case the XML returned by the radio is invalid. */ public FrontierSiliconRadioApiResult(String requestResultString) throws IOException { Document xml = null; try { xml = getXmlDocFromString(requestResultString); } catch (Exception e) { logger.trace("converting to XML failed: '{}' with {}: {}", requestResultString, e.getClass().getName(), e.getMessage()); logger.debug("converting to XML failed with {}: {}", e.getClass().getName(), e.getMessage()); if (e instanceof IOException) { throw (IOException) e; } throw new IOException(e); } xmlDoc = xml; } /** * Extract the field "status" from the result and return it * * @return result field as string. */ private String getStatus() { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element statusNode = (Element) fsApiResult.getElementsByTagName("status").item(0); final String status = getCharacterDataFromElement(statusNode); logger.trace("status is: {}", status); return status; } /** * checks if the responses status code was "FS_OK" * * @return true if status is "FS_OK", false else */ public boolean isStatusOk() { return ("FS_OK").equals(getStatus()); } /** * read the &lt;value&gt;&lt;u8&gt; field as boolean * * @return value.u8 field as bool */ public boolean getValueU8AsBoolean() { try { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element valueNode = (Element) fsApiResult.getElementsByTagName("value").item(0); final Element u8Node = (Element) valueNode.getElementsByTagName("u8").item(0); final String value = getCharacterDataFromElement(u8Node); logger.trace("value is: {}", value); return "1".equals(value); } catch (Exception e) { logger.error("getting Value.U8 failed with {}: {}", e.getClass().getName(), e.getMessage()); return false; } } /** * read the &lt;value&gt;&lt;u8&gt; field as int * * @return value.u8 field as int */ public int getValueU8AsInt() { try { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element valueNode = (Element) fsApiResult.getElementsByTagName("value").item(0); final Element u8Node = (Element) valueNode.getElementsByTagName("u8").item(0); final String value = getCharacterDataFromElement(u8Node); logger.trace("value is: {}", value); return Integer.parseInt(value); } catch (Exception e) { logger.error("getting Value.U8 failed with {}: {}", e.getClass().getName(), e.getMessage()); return 0; } } /** * read the &lt;value&gt;&lt;u32&gt; field as int * * @return value.u32 field as int */ public int getValueU32AsInt() { try { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element valueNode = (Element) fsApiResult.getElementsByTagName("value").item(0); final Element u32Node = (Element) valueNode.getElementsByTagName("u32").item(0); final String value = getCharacterDataFromElement(u32Node); logger.trace("value is: {}", value); return Integer.parseInt(value); } catch (Exception e) { logger.error("getting Value.U32 failed with {}: {}", e.getClass().getName(), e.getMessage()); return 0; } } /** * read the &lt;value&gt;&lt;c8_array&gt; field as String * * @return value.c8_array field as String */ public String getValueC8ArrayAsString() { try { final Element fsApiResult = (Element) xmlDoc.getElementsByTagName("fsapiResponse").item(0); final Element valueNode = (Element) fsApiResult.getElementsByTagName("value").item(0); final Element c8Array = (Element) valueNode.getElementsByTagName("c8_array").item(0); final String value = getCharacterDataFromElement(c8Array); logger.trace("value is: {}", value); return value; } catch (Exception e) { logger.error("getting Value.c8array failed with {}: {}", e.getClass().getName(), e.getMessage()); return ""; } } /** * read the &lt;sessionId&gt; field as String * * @return value of sessionId field */ public String getSessionId() { final NodeList sessionIdTagList = xmlDoc.getElementsByTagName("sessionId"); final String givenSessId = getCharacterDataFromElement((Element) sessionIdTagList.item(0)); return givenSessId; } /** * converts the string we got from the radio to a parsable XML document * * @param xmlString * the XML string read from the radio * @return the parsed XML document * @throws ParserConfigurationException * @throws SAXException * @throws IOException */ private Document getXmlDocFromString(String xmlString) throws ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document xmlDocument = builder.parse(new InputSource(new StringReader(xmlString))); return xmlDocument; } /** * convert the value of a given XML element to a string for further processing * * @param e * XML Element * @return the elements value converted to string */ private static String getCharacterDataFromElement(Element e) { final Node child = e.getFirstChild(); if (child instanceof CharacterData) { final CharacterData cd = (CharacterData) child; return cd.getData(); } return ""; } }
./CrossVul/dataset_final_sorted/CWE-611/java/bad_1910_9
crossvul-java_data_bad_4762_1
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherSpi; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.interfaces.DHKey; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyEncoder; import org.bouncycastle.crypto.agreement.DHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.DHKeyPairGenerator; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHKeyGenerationParameters; import org.bouncycastle.crypto.params.DHKeyParameters; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.parsers.DHIESPublicKeyParser; import org.bouncycastle.jcajce.provider.asymmetric.util.DHUtil; import org.bouncycastle.jcajce.provider.asymmetric.util.IESUtil; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.IESKey; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; public class IESCipher extends CipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private final int ivLength; private IESEngine engine; private int state = -1; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private AlgorithmParameters engineParam = null; private IESParameterSpec engineSpec = null; private AsymmetricKeyParameter key; private SecureRandom random; private boolean dhaesMode = false; private AsymmetricKeyParameter otherKeyParameter = null; public IESCipher(IESEngine engine) { this.engine = engine; this.ivLength = 0; } public IESCipher(IESEngine engine, int ivLength) { this.engine = engine; this.ivLength = ivLength; } public int engineGetBlockSize() { if (engine.getCipher() != null) { return engine.getCipher().getBlockSize(); } else { return 0; } } public int engineGetKeySize(Key key) { if (key instanceof DHKey) { return ((DHKey)key).getParams().getP().bitLength(); } else { throw new IllegalArgumentException("not a DH key"); } } public byte[] engineGetIV() { if (engineSpec != null) { return engineSpec.getNonce(); } return null; } public AlgorithmParameters engineGetParameters() { if (engineParam == null && engineSpec != null) { try { engineParam = helper.createAlgorithmParameters("IES"); engineParam.init(engineSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } return engineParam; } public void engineSetMode(String mode) throws NoSuchAlgorithmException { String modeName = Strings.toUpperCase(mode); if (modeName.equals("NONE")) { dhaesMode = false; } else if (modeName.equals("DHAES")) { dhaesMode = true; } else { throw new IllegalArgumentException("can't support mode " + mode); } } public int engineGetOutputSize(int inputLen) { int len1, len2, len3; if (key == null) { throw new IllegalStateException("cipher not initialised"); } len1 = engine.getMac().getMacSize(); if (otherKeyParameter == null) { len2 = 1 + 2 * (((DHKeyParameters)key).getParameters().getP().bitLength() + 7) / 8; } else { len2 = 0; } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("IESCipher not initialised"); } } public void engineSetPadding(String padding) throws NoSuchPaddingException { String paddingName = Strings.toUpperCase(padding); // TDOD: make this meaningful... if (paddingName.equals("NOPADDING")) { } else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) { } else { throw new NoSuchPaddingException("padding not available with IESCipher"); } } // Initialisation methods public void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(IESParameterSpec.class); } catch (Exception e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString()); } } engineParam = params; engineInit(opmode, key, paramSpec, random); } public void engineInit( int opmode, Key key, AlgorithmParameterSpec engineSpec, SecureRandom random) throws InvalidAlgorithmParameterException, InvalidKeyException { // Use default parameters (including cipher key size) if none are specified if (engineSpec == null) { byte[] nonce = null; if (ivLength != 0 && opmode == Cipher.ENCRYPT_MODE) { nonce = new byte[ivLength]; random.nextBytes(nonce); } this.engineSpec = IESUtil.guessParameterSpec(engine.getCipher(), nonce); } else if (engineSpec instanceof IESParameterSpec) { this.engineSpec = (IESParameterSpec)engineSpec; } else { throw new InvalidAlgorithmParameterException("must be passed IES parameters"); } byte[] nonce = this.engineSpec.getNonce(); if (ivLength != 0 && (nonce == null || nonce.length != ivLength)) { throw new InvalidAlgorithmParameterException("NONCE in IES Parameters needs to be " + ivLength + " bytes long"); } // Parse the recipient's key if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) { if (key instanceof DHPublicKey) { this.key = DHUtil.generatePublicKeyParameter((PublicKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.key = DHUtil.generatePublicKeyParameter(ieKey.getPublic()); this.otherKeyParameter = DHUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's public DH key for encryption"); } } else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) { if (key instanceof DHPrivateKey) { this.key = DHUtil.generatePrivateKeyParameter((PrivateKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.otherKeyParameter = DHUtil.generatePublicKeyParameter(ieKey.getPublic()); this.key = DHUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's private DH key for decryption"); } } else { throw new InvalidKeyException("must be passed EC key"); } this.random = random; this.state = opmode; buffer.reset(); } public void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("cannot handle supplied parameter spec: " + e.getMessage()); } } // Update methods - buffer the input public byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { buffer.write(input, inputOffset, inputLen); return null; } public int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { buffer.write(input, inputOffset, inputLen); return 0; } // Finalisation methods public byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } byte[] in = buffer.toByteArray(); buffer.reset(); // Convert parameters for use in IESEngine CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize()); if (engineSpec.getNonce() != null) { params = new ParametersWithIV(params, engineSpec.getNonce()); } DHParameters dhParams = ((DHKeyParameters)key).getParameters(); byte[] V; if (otherKeyParameter != null) { try { if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { engine.init(true, otherKeyParameter, key, params); } else { engine.init(false, key, otherKeyParameter, params); } return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadPaddingException(e.getMessage()); } } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { // Generate the ephemeral key pair DHKeyPairGenerator gen = new DHKeyPairGenerator(); gen.init(new DHKeyGenerationParameters(random, dhParams)); EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() { public byte[] getEncoded(AsymmetricKeyParameter keyParameter) { byte[] Vloc = new byte[(((DHKeyParameters)keyParameter).getParameters().getP().bitLength() + 7) / 8]; byte[] Vtmp = BigIntegers.asUnsignedByteArray(((DHPublicKeyParameters)keyParameter).getY()); if (Vtmp.length > Vloc.length) { throw new IllegalArgumentException("Senders's public key longer than expected."); } else { System.arraycopy(Vtmp, 0, Vloc, Vloc.length - Vtmp.length, Vtmp.length); } return Vloc; } }); // Encrypt the buffer try { engine.init(key, params, kGen); return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadPaddingException(e.getMessage()); } } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { // Decrypt the buffer try { engine.init(key, params, new DHIESPublicKeyParser(((DHKeyParameters)key).getParameters())); return engine.processBlock(in, 0, in.length); } catch (InvalidCipherTextException e) { throw new BadPaddingException(e.getMessage()); } } else { throw new IllegalStateException("IESCipher not initialised"); } } public int engineDoFinal( byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] buf = engineDoFinal(input, inputOffset, inputLength); System.arraycopy(buf, 0, output, outputOffset, buf.length); return buf.length; } /** * Classes that inherit from us */ static public class IES extends IESCipher { public IES() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()))); } } static public class IESwithDESedeCBC extends IESCipher { public IESwithDESedeCBC() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()))), 8); } } static public class IESwithAESCBC extends IESCipher { public IESwithAESCBC() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()))), 16); } } }
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4762_1
crossvul-java_data_bad_4758_1
package org.bouncycastle.crypto.test; import java.math.BigInteger; import java.security.SecureRandom; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA3Digest; import org.bouncycastle.crypto.generators.DSAKeyPairGenerator; import org.bouncycastle.crypto.generators.DSAParametersGenerator; import org.bouncycastle.crypto.params.DSAKeyGenerationParameters; import org.bouncycastle.crypto.params.DSAParameterGenerationParameters; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.DSAValidationParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.DSADigestSigner; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; /** * Test based on FIPS 186-2, Appendix 5, an example of DSA, and FIPS 168-3 test vectors. */ public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.Data(k1), new FixedSecureRandom.Data(k2) }); byte[] keyData = Hex.decode("b5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); SecureRandom keyRandom = new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.Data(keyData), new FixedSecureRandom.Data(keyData) }); BigInteger pValue = new BigInteger("8df2a494492276aa3d25759bb06869cbeac0d83afb8d0cf7cbb8324f0d7882e5d0762fc5b7210eafc2e9adac32ab7aac49693dfbf83724c2ec0736ee31c80291", 16); BigInteger qValue = new BigInteger("c773218c737ec8ee993b4f2ded30f48edace915f", 16); public String getName() { return "DSA"; } public void performTest() { BigInteger r = new BigInteger("68076202252361894315274692543577577550894681403"); BigInteger s = new BigInteger("1089214853334067536215539335472893651470583479365"); DSAParametersGenerator pGen = new DSAParametersGenerator(); pGen.init(512, 80, random); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pValid = params.getValidationParameters(); if (pValid.getCounter() != 105) { fail("Counter wrong"); } if (!pValue.equals(params.getP()) || !qValue.equals(params.getQ())) { fail("p or q wrong"); } DSAKeyPairGenerator dsaKeyGen = new DSAKeyPairGenerator(); DSAKeyGenerationParameters genParam = new DSAKeyGenerationParameters(keyRandom, params); dsaKeyGen.init(genParam); AsymmetricCipherKeyPair pair = dsaKeyGen.generateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.getPrivate(), keyRandom); DSASigner dsa = new DSASigner(); dsa.init(true, param); byte[] message = BigIntegers.asUnsignedByteArray(new BigInteger("968236873715988614170569073515315707566766479517")); BigInteger[] sig = dsa.generateSignature(message); if (!r.equals(sig[0])) { fail("r component wrong.", r, sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong.", s, sig[1]); } dsa.init(false, pair.getPublic()); if (!dsa.verifySignature(message, sig[0], sig[1])) { fail("verification fails"); } dsa2Test1(); dsa2Test2(); dsa2Test3(); dsa2Test4(); testDSAsha3(224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); } private void testDSAsha3(int size, BigInteger s) { DSAParameters dsaParams = new DSAParameters( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeyParameters priKey = new DSAPrivateKeyParameters(x, dsaParams); SecureRandom k = new TestRandomBigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); DSADigestSigner dsa = new DSADigestSigner(new DSASigner(), new SHA3Digest(size)); dsa.init(true, new ParametersWithRandom(priKey, k)); dsa.update(M, 0, M.length); byte[] encSig = dsa.generateSignature(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature DSAPublicKeyParameters pubKey = new DSAPublicKeyParameters(y, dsaParams); dsa.init(false, pubKey); dsa.update(M, 0, M.length); if (!dsa.verifySignature(encSig)) { fail("signature fails"); } } private void dsa2Test1() { byte[] seed = Hex.decode("ED8BEE8D1CB89229D2903CBF0E51EE7377F48698"); DSAParametersGenerator pGen = new DSAParametersGenerator(); pGen.init(new DSAParameterGenerationParameters(1024, 160, 80, new DSATestSecureRandom(seed))); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pv = params.getValidationParameters(); if (pv.getCounter() != 5) { fail("counter incorrect"); } if (!Arrays.areEqual(seed, pv.getSeed())) { fail("seed incorrect"); } if (!params.getQ().equals(new BigInteger("E950511EAB424B9A19A2AEB4E159B7844C589C4F", 16))) { fail("Q incorrect"); } if (!params.getP().equals(new BigInteger( "E0A67598CD1B763B" + "C98C8ABB333E5DDA0CD3AA0E5E1FB5BA8A7B4EABC10BA338" + "FAE06DD4B90FDA70D7CF0CB0C638BE3341BEC0AF8A7330A3" + "307DED2299A0EE606DF035177A239C34A912C202AA5F83B9" + "C4A7CF0235B5316BFC6EFB9A248411258B30B839AF172440" + "F32563056CB67A861158DDD90E6A894C72A5BBEF9E286C6B", 16))) { fail("P incorrect"); } if (!params.getG().equals(new BigInteger( "D29D5121B0423C27" + "69AB21843E5A3240FF19CACC792264E3BB6BE4F78EDD1B15" + "C4DFF7F1D905431F0AB16790E1F773B5CE01C804E509066A" + "9919F5195F4ABC58189FD9FF987389CB5BEDF21B4DAB4F8B" + "76A055FFE2770988FE2EC2DE11AD92219F0B351869AC24DA" + "3D7BA87011A701CE8EE7BFE49486ED4527B7186CA4610A75", 16))) { fail("G incorrect"); } DSAKeyPairGenerator kpGen = new DSAKeyPairGenerator(); kpGen.init(new DSAKeyGenerationParameters(new TestRandomBigInteger("D0EC4E50BB290A42E9E355C73D8809345DE2E139", 16), params)); AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)kp.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)kp.getPrivate(); if (!pub.getY().equals(new BigInteger( "25282217F5730501" + "DD8DBA3EDFCF349AAFFEC20921128D70FAC44110332201BB" + "A3F10986140CBB97C726938060473C8EC97B4731DB004293" + "B5E730363609DF9780F8D883D8C4D41DED6A2F1E1BBBDC97" + "9E1B9D6D3C940301F4E978D65B19041FCF1E8B518F5C0576" + "C770FE5A7A485D8329EE2914A2DE1B5DA4A6128CEAB70F79", 16))) { fail("Y value incorrect"); } if (!priv.getX().equals( new BigInteger("D0EC4E50BB290A42E9E355C73D8809345DE2E139", 16))) { fail("X value incorrect"); } DSASigner signer = new DSASigner(); signer.init(true, new ParametersWithRandom(kp.getPrivate(), new TestRandomBigInteger("349C55648DCF992F3F33E8026CFAC87C1D2BA075", 16))); byte[] msg = Hex.decode("A9993E364706816ABA3E25717850C26C9CD0D89D"); BigInteger[] sig = signer.generateSignature(msg); if (!sig[0].equals(new BigInteger("636155AC9A4633B4665D179F9E4117DF68601F34", 16))) { fail("R value incorrect"); } if (!sig[1].equals(new BigInteger("6C540B02D9D4852F89DF8CFC99963204F4347704", 16))) { fail("S value incorrect"); } signer.init(false, kp.getPublic()); if (!signer.verifySignature(msg, sig[0], sig[1])) { fail("signature not verified"); } } private void dsa2Test2() { byte[] seed = Hex.decode("5AFCC1EFFC079A9CCA6ECA86D6E3CC3B18642D9BE1CC6207C84002A9"); DSAParametersGenerator pGen = new DSAParametersGenerator(new SHA224Digest()); pGen.init(new DSAParameterGenerationParameters(2048, 224, 80, new DSATestSecureRandom(seed))); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pv = params.getValidationParameters(); if (pv.getCounter() != 21) { fail("counter incorrect"); } if (!Arrays.areEqual(seed, pv.getSeed())) { fail("seed incorrect"); } if (!params.getQ().equals(new BigInteger("90EAF4D1AF0708B1B612FF35E0A2997EB9E9D263C9CE659528945C0D", 16))) { fail("Q incorrect"); } if (!params.getP().equals(new BigInteger( "C196BA05AC29E1F9C3C72D56DFFC6154" + "A033F1477AC88EC37F09BE6C5BB95F51C296DD20D1A28A06" + "7CCC4D4316A4BD1DCA55ED1066D438C35AEBAABF57E7DAE4" + "28782A95ECA1C143DB701FD48533A3C18F0FE23557EA7AE6" + "19ECACC7E0B51652A8776D02A425567DED36EABD90CA33A1" + "E8D988F0BBB92D02D1D20290113BB562CE1FC856EEB7CDD9" + "2D33EEA6F410859B179E7E789A8F75F645FAE2E136D252BF" + "FAFF89528945C1ABE705A38DBC2D364AADE99BE0D0AAD82E" + "5320121496DC65B3930E38047294FF877831A16D5228418D" + "E8AB275D7D75651CEFED65F78AFC3EA7FE4D79B35F62A040" + "2A1117599ADAC7B269A59F353CF450E6982D3B1702D9CA83", 16))) { fail("P incorrect"); } if (!params.getG().equals(new BigInteger( "A59A749A11242C58C894E9E5A91804E8"+ "FA0AC64B56288F8D47D51B1EDC4D65444FECA0111D78F35F"+ "C9FDD4CB1F1B79A3BA9CBEE83A3F811012503C8117F98E50"+ "48B089E387AF6949BF8784EBD9EF45876F2E6A5A495BE64B"+ "6E770409494B7FEE1DBB1E4B2BC2A53D4F893D418B715959"+ "2E4FFFDF6969E91D770DAEBD0B5CB14C00AD68EC7DC1E574"+ "5EA55C706C4A1C5C88964E34D09DEB753AD418C1AD0F4FDF"+ "D049A955E5D78491C0B7A2F1575A008CCD727AB376DB6E69"+ "5515B05BD412F5B8C2F4C77EE10DA48ABD53F5DD498927EE"+ "7B692BBBCDA2FB23A516C5B4533D73980B2A3B60E384ED20"+ "0AE21B40D273651AD6060C13D97FD69AA13C5611A51B9085", 16))) { fail("G incorrect"); } DSAKeyPairGenerator kpGen = new DSAKeyPairGenerator(); kpGen.init(new DSAKeyGenerationParameters(new TestRandomData(Hex.decode("00D0F09ED3E2568F6CADF9224117DA2AEC5A4300E009DE1366023E17")), params)); AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)kp.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)kp.getPrivate(); if (!pub.getY().equals(new BigInteger( "70035C9A3B225B258F16741F3941FBF0" + "6F3D056CD7BD864604CBB5EE9DD85304EE8E8E4ABD5E9032" + "11DDF25CE149075510ACE166970AFDC7DF552B7244F342FA" + "02F7A621405B754909D757F97290E1FE5036E904CF593446" + "0C046D95659821E1597ED9F2B1F0E20863A6BBD0CE74DACB" + "A5D8C68A90B29C2157CDEDB82EC12B81EE3068F9BF5F7F34" + "6ECA41ED174CCCD7D154FA4F42F80FFE1BF46AE9D8125DEB" + "5B4BA08A72BDD86596DBEDDC9550FDD650C58F5AE5133509" + "A702F79A31ECB490F7A3C5581631F7C5BE4FF7F9E9F27FA3" + "90E47347AD1183509FED6FCF198BA9A71AB3335B4F38BE8D" + "15496A00B6DC2263E20A5F6B662320A3A1EC033AA61E3B68", 16))) { fail("Y value incorrect"); } if (!priv.getX().equals( new BigInteger("00D0F09ED3E2568F6CADF9224117DA2AEC5A4300E009DE1366023E17", 16))) { fail("X value incorrect"); } DSASigner signer = new DSASigner(); signer.init(true, new ParametersWithRandom(kp.getPrivate(), new TestRandomData(Hex.decode("735959CC4463B8B440E407EECA8A473BF6A6D1FE657546F67D401F05")))); byte[] msg = Hex.decode("23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"); BigInteger[] sig = signer.generateSignature(msg); if (!sig[0].equals(new BigInteger("4400138D05F9639CAF54A583CAAF25D2B76D0C3EAD752CE17DBC85FE", 16))) { fail("R value incorrect"); } if (!sig[1].equals(new BigInteger("874D4F12CB13B61732D398445698CFA9D92381D938AA57EE2C9327B3", 16))) { fail("S value incorrect"); } signer.init(false, kp.getPublic()); if (!signer.verifySignature(msg, sig[0], sig[1])) { fail("signature not verified"); } } private void dsa2Test3() { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); DSAParametersGenerator pGen = new DSAParametersGenerator(new SHA256Digest()); pGen.init(new DSAParameterGenerationParameters(2048, 256, 80, new DSATestSecureRandom(seed))); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pv = params.getValidationParameters(); if (pv.getCounter() != 12) { fail("counter incorrect"); } if (!Arrays.areEqual(seed, pv.getSeed())) { fail("seed incorrect"); } if (!params.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!params.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!params.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } DSAKeyPairGenerator kpGen = new DSAKeyPairGenerator(); kpGen.init(new DSAKeyGenerationParameters(new TestRandomData(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), params)); AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)kp.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)kp.getPrivate(); if (!pub.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!priv.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } DSASigner signer = new DSASigner(); signer.init(true, new ParametersWithRandom(kp.getPrivate(), new TestRandomData(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")))); byte[] msg = Hex.decode("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"); BigInteger[] sig = signer.generateSignature(msg); if (!sig[0].equals(new BigInteger("315C875DCD4850E948B8AC42824E9483A32D5BA5ABE0681B9B9448D444F2BE3C", 16))) { fail("R value incorrect"); } if (!sig[1].equals(new BigInteger("89718D12E54A8D9ED066E4A55F7ED5A2229CD23B9A3CEE78F83ED6AA61F6BCB9", 16))) { fail("S value incorrect"); } signer.init(false, kp.getPublic()); if (!signer.verifySignature(msg, sig[0], sig[1])) { fail("signature not verified"); } } private void dsa2Test4() { byte[] seed = Hex.decode("193AFCA7C1E77B3C1ECC618C81322E47B8B8B997C9C83515C59CC446C2D9BD47"); DSAParametersGenerator pGen = new DSAParametersGenerator(new SHA256Digest()); pGen.init(new DSAParameterGenerationParameters(3072, 256, 80, new DSATestSecureRandom(seed))); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pv = params.getValidationParameters(); if (pv.getCounter() != 20) { fail("counter incorrect"); } if (!Arrays.areEqual(seed, pv.getSeed())) { fail("seed incorrect"); } if (!params.getQ().equals(new BigInteger("CFA0478A54717B08CE64805B76E5B14249A77A4838469DF7F7DC987EFCCFB11D", 16))) { fail("Q incorrect"); } if (!params.getP().equals(new BigInteger( "90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD610" + "37E56258A7795A1C7AD46076982CE6BB956936C6AB4DCFE0" + "5E6784586940CA544B9B2140E1EB523F009D20A7E7880E4E" + "5BFA690F1B9004A27811CD9904AF70420EEFD6EA11EF7DA1" + "29F58835FF56B89FAA637BC9AC2EFAAB903402229F491D8D" + "3485261CD068699B6BA58A1DDBBEF6DB51E8FE34E8A78E54" + "2D7BA351C21EA8D8F1D29F5D5D15939487E27F4416B0CA63" + "2C59EFD1B1EB66511A5A0FBF615B766C5862D0BD8A3FE7A0" + "E0DA0FB2FE1FCB19E8F9996A8EA0FCCDE538175238FC8B0E" + "E6F29AF7F642773EBE8CD5402415A01451A840476B2FCEB0" + "E388D30D4B376C37FE401C2A2C2F941DAD179C540C1C8CE0" + "30D460C4D983BE9AB0B20F69144C1AE13F9383EA1C08504F" + "B0BF321503EFE43488310DD8DC77EC5B8349B8BFE97C2C56" + "0EA878DE87C11E3D597F1FEA742D73EEC7F37BE43949EF1A" + "0D15C3F3E3FC0A8335617055AC91328EC22B50FC15B941D3" + "D1624CD88BC25F3E941FDDC6200689581BFEC416B4B2CB73", 16))) { fail("P incorrect"); } if (!params.getG().equals(new BigInteger( "5E5CBA992E0A680D885EB903AEA78E4A45A469103D448EDE" + "3B7ACCC54D521E37F84A4BDD5B06B0970CC2D2BBB715F7B8" + "2846F9A0C393914C792E6A923E2117AB805276A975AADB52" + "61D91673EA9AAFFEECBFA6183DFCB5D3B7332AA19275AFA1" + "F8EC0B60FB6F66CC23AE4870791D5982AAD1AA9485FD8F4A" + "60126FEB2CF05DB8A7F0F09B3397F3937F2E90B9E5B9C9B6" + "EFEF642BC48351C46FB171B9BFA9EF17A961CE96C7E7A7CC" + "3D3D03DFAD1078BA21DA425198F07D2481622BCE45969D9C" + "4D6063D72AB7A0F08B2F49A7CC6AF335E08C4720E31476B6" + "7299E231F8BD90B39AC3AE3BE0C6B6CACEF8289A2E2873D5" + "8E51E029CAFBD55E6841489AB66B5B4B9BA6E2F784660896" + "AFF387D92844CCB8B69475496DE19DA2E58259B090489AC8" + "E62363CDF82CFD8EF2A427ABCD65750B506F56DDE3B98856" + "7A88126B914D7828E2B63A6D7ED0747EC59E0E0A23CE7D8A" + "74C1D2C2A7AFB6A29799620F00E11C33787F7DED3B30E1A2" + "2D09F1FBDA1ABBBFBF25CAE05A13F812E34563F99410E73B", 16))) { fail("G incorrect"); } DSAKeyPairGenerator kpGen = new DSAKeyPairGenerator(); kpGen.init(new DSAKeyGenerationParameters(new TestRandomData(Hex.decode("3ABC1587297CE7B9EA1AD6651CF2BC4D7F92ED25CABC8553F567D1B40EBB8764")), params)); AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)kp.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)kp.getPrivate(); if (!pub.getY().equals(new BigInteger( "8B891C8692D3DE875879390F2698B26FBECCA6B075535DCE" + "6B0C862577F9FA0DEF6074E7A7624121224A595896ABD4CD" + "A56B2CEFB942E025D2A4282FFAA98A48CDB47E1A6FCB5CFB" + "393EF35AF9DF913102BB303C2B5C36C3F8FC04ED7B8B69FE" + "FE0CF3E1FC05CFA713B3435B2656E913BA8874AEA9F93600" + "6AEB448BCD005D18EC3562A33D04CF25C8D3D69844343442" + "FA3DB7DE618C5E2DA064573E61E6D5581BFB694A23AC87FD" + "5B52D62E954E1376DB8DDB524FFC0D469DF978792EE44173" + "8E5DB05A7DC43E94C11A2E7A4FBE383071FA36D2A7EC8A93" + "88FE1C4F79888A99D3B6105697C2556B79BB4D7E781CEBB3" + "D4866AD825A5E830846072289FDBC941FA679CA82F5F78B7" + "461B2404DB883D215F4E0676CF5493950AC5591697BFEA8D" + "1EE6EC016B89BA51CAFB5F9C84C989FA117375E94578F28B" + "E0B34CE0545DA46266FD77F62D8F2CEE92AB77012AFEBC11" + "008985A821CD2D978C7E6FE7499D1AAF8DE632C21BB48CA5" + "CBF9F31098FD3FD3854C49A65D9201744AACE540354974F9", 16))) { fail("Y value incorrect"); } if (!priv.getX().equals( new BigInteger("3ABC1587297CE7B9EA1AD6651CF2BC4D7F92ED25CABC8553F567D1B40EBB8764", 16))) { fail("X value incorrect"); } DSASigner signer = new DSASigner(); signer.init(true, new ParametersWithRandom(kp.getPrivate(), new TestRandomData(Hex.decode("A6902C1E6E3943C5628061588A8B007BCCEA91DBF12915483F04B24AB0678BEE")))); byte[] msg = Hex.decode("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"); BigInteger[] sig = signer.generateSignature(msg); if (!sig[0].equals(new BigInteger("5F184E645A38BE8FB4A6871B6503A9D12924C7ABE04B71410066C2ECA6E3BE3E", 16))) { fail("R value incorrect"); } if (!sig[1].equals(new BigInteger("91EB0C7BA3D4B9B60B825C3D9F2CADA8A2C9D7723267B033CBCDCF8803DB9C18", 16))) { fail("S value incorrect"); } signer.init(false, kp.getPublic()); if (!signer.verifySignature(msg, sig[0], sig[1])) { fail("signature not verified"); } } public static void main( String[] args) { runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4758_1
crossvul-java_data_bad_4758_0
package org.bouncycastle.crypto.signers; import java.math.BigInteger; import java.security.SecureRandom; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DSA; import org.bouncycastle.crypto.params.DSAKeyParameters; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; /** * The Digital Signature Algorithm - as described in "Handbook of Applied * Cryptography", pages 452 - 453. */ public class DSASigner implements DSA { private final DSAKCalculator kCalculator; private DSAKeyParameters key; private SecureRandom random; /** * Default configuration, random K values. */ public DSASigner() { this.kCalculator = new RandomDSAKCalculator(); } /** * Configuration with an alternate, possibly deterministic calculator of K. * * @param kCalculator a K value calculator. */ public DSASigner(DSAKCalculator kCalculator) { this.kCalculator = kCalculator; } public void init( boolean forSigning, CipherParameters param) { SecureRandom providedRandom = null; if (forSigning) { if (param instanceof ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; this.key = (DSAPrivateKeyParameters)rParam.getParameters(); providedRandom = rParam.getRandom(); } else { this.key = (DSAPrivateKeyParameters)param; } } else { this.key = (DSAPublicKeyParameters)param; } this.random = initSecureRandom(forSigning && !kCalculator.isDeterministic(), providedRandom); } /** * generate a signature for the given message using the key we were * initialised with. For conventional DSA the message should be a SHA-1 * hash of the message of interest. * * @param message the message that will be verified later. */ public BigInteger[] generateSignature( byte[] message) { DSAParameters params = key.getParameters(); BigInteger q = params.getQ(); BigInteger m = calculateE(q, message); BigInteger x = ((DSAPrivateKeyParameters)key).getX(); if (kCalculator.isDeterministic()) { kCalculator.init(q, x, message); } else { kCalculator.init(q, random); } BigInteger k = kCalculator.nextK(); BigInteger r = params.getG().modPow(k, params.getP()).mod(q); k = k.modInverse(q).multiply(m.add(x.multiply(r))); BigInteger s = k.mod(q); return new BigInteger[]{ r, s }; } /** * return true if the value r and s represent a DSA signature for * the passed in message for standard DSA the message should be a * SHA-1 hash of the real message to be verified. */ public boolean verifySignature( byte[] message, BigInteger r, BigInteger s) { DSAParameters params = key.getParameters(); BigInteger q = params.getQ(); BigInteger m = calculateE(q, message); BigInteger zero = BigInteger.valueOf(0); if (zero.compareTo(r) >= 0 || q.compareTo(r) <= 0) { return false; } if (zero.compareTo(s) >= 0 || q.compareTo(s) <= 0) { return false; } BigInteger w = s.modInverse(q); BigInteger u1 = m.multiply(w).mod(q); BigInteger u2 = r.multiply(w).mod(q); BigInteger p = params.getP(); u1 = params.getG().modPow(u1, p); u2 = ((DSAPublicKeyParameters)key).getY().modPow(u2, p); BigInteger v = u1.multiply(u2).mod(p).mod(q); return v.equals(r); } private BigInteger calculateE(BigInteger n, byte[] message) { if (n.bitLength() >= message.length * 8) { return new BigInteger(1, message); } else { byte[] trunc = new byte[n.bitLength() / 8]; System.arraycopy(message, 0, trunc, 0, trunc.length); return new BigInteger(1, trunc); } } protected SecureRandom initSecureRandom(boolean needed, SecureRandom provided) { return !needed ? null : (provided != null) ? provided : new SecureRandom(); } }
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4758_0
crossvul-java_data_bad_4762_5
package org.bouncycastle.jce.provider.test; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import org.bouncycastle.crypto.agreement.DHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.DESEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.jcajce.provider.asymmetric.dh.IESCipher; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; /** * Test for DHIES - Diffie-Hellman Integrated Encryption Scheme */ public class DHIESTest extends SimpleTest { // Oakley group 2 - RFC 5996 BigInteger p1024 = new BigInteger( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381" + "FFFFFFFFFFFFFFFF",16); BigInteger g1024 = new BigInteger("2",16); DHParameterSpec param = new DHParameterSpec(p1024, g1024); DHIESTest() { } public String getName() { return "DHIES"; } public void performTest() throws Exception { byte[] derivation = Hex.decode("202122232425262728292a2b2c2d2e2f"); byte[] encoding = Hex.decode("303132333435363738393a3b3c3d3e3f"); IESCipher c1 = new org.bouncycastle.jcajce.provider.asymmetric.dh.IESCipher.IES(); IESCipher c2 = new org.bouncycastle.jcajce.provider.asymmetric.dh.IESCipher.IES(); IESParameterSpec params = new IESParameterSpec(derivation,encoding,128); // Testing DHIES with default prime in streaming mode KeyPairGenerator g = KeyPairGenerator.getInstance("DH", "BC"); KeyPairGenerator g512 = KeyPairGenerator.getInstance("DH", "BC"); g.initialize(param); doTest("DHIES with default", g, "DHIES", params); // Testing DHIES with 512-bit prime in streaming mode g512.initialize(512, new SecureRandom()); doTest("DHIES with 512-bit", g512, "DHIES", params); // Testing ECIES with 1024-bit prime in streaming mode g.initialize(param, new SecureRandom()); doTest("DHIES with 1024-bit", g, "DHIES", params); c1 = new IESCipher(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new DESEngine()))); c2 = new IESCipher(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new DESEngine()))); params = new IESParameterSpec(derivation, encoding, 128, 192, Hex.decode("0001020304050607")); // Testing DHIES with default prime using DESEDE g = KeyPairGenerator.getInstance("DH", "BC"); doTest("DHIESwithDES default", g, "DHIESwithDESEDE-CBC", params); // Testing DHIES with 512-bit prime using DESEDE doTest("DHIESwithDES 512-bit", g512, "DHIESwithDESEDE-CBC", params); // Testing DHIES with 1024-bit prime using DESEDE g.initialize(param, new SecureRandom()); doTest("DHIESwithDES 1024-bit", g, "DHIESwithDESEDE-CBC", params); g = KeyPairGenerator.getInstance("DH", "BC"); g.initialize(param); c1 = new IESCipher.IESwithAESCBC(); c2 = new IESCipher.IESwithAESCBC(); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("00010203040506070001020304050607")); // Testing DHIES with default prime using AES doTest("DHIESwithAES default", g, "DHIESwithAES-CBC", params); // Testing DHIES with 512-bit prime using AES doTest("DHIESwithAES 512-bit", g512, "DHIESwithAES-CBC", params); // Testing DHIES with 1024-bit prime using AES g.initialize(param, new SecureRandom()); doTest("DHIESwithAES 1024-bit", g, "DHIESwithAES-CBC", params); KeyPair keyPair = g.generateKeyPair(); DHPublicKey pub = (DHPublicKey)keyPair.getPublic(); DHPrivateKey priv = (DHPrivateKey)keyPair.getPrivate(); Cipher c = Cipher.getInstance("DHIESwithAES-CBC", "BC"); try { c.init(Cipher.ENCRYPT_MODE, pub, new IESParameterSpec(derivation, encoding, 128, 128, null)); fail("no exception"); } catch (InvalidAlgorithmParameterException e) { isTrue("message ", "NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } try { c.init(Cipher.DECRYPT_MODE, priv); fail("no exception"); } catch (IllegalArgumentException e) { isTrue("message ", "cannot handle supplied parameter spec: NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } try { c.init(Cipher.DECRYPT_MODE, priv, new IESParameterSpec(derivation, encoding, 128, 128, null)); fail("no exception"); } catch (InvalidAlgorithmParameterException e) { isTrue("message ", "NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } } public void doTest( String testname, KeyPairGenerator g, String cipher, IESParameterSpec p) throws Exception { byte[] message = Hex.decode("0102030405060708090a0b0c0d0e0f10111213141516"); byte[] out1, out2; Cipher c1 = Cipher.getInstance(cipher, "BC"); Cipher c2 = Cipher.getInstance(cipher, "BC"); // Generate static key pair KeyPair keyPair = g.generateKeyPair(); DHPublicKey pub = (DHPublicKey)keyPair.getPublic(); DHPrivateKey priv = (DHPrivateKey)keyPair.getPrivate(); // Testing with default parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, pub, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, priv, c1.getParameters()); isTrue("nonce mismatch", Arrays.areEqual(c1.getIV(), c2.getIV())); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) { fail(testname + " test failed with default parameters, DHAES mode false."); } // Testing with given parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, pub, p, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, priv, p); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with non-null parameters, DHAES mode false."); // Testing with null parameters and DHAES mode on c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); c1.init(Cipher.ENCRYPT_MODE, pub, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, priv, c1.getParameters(), new SecureRandom()); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with null parameters, DHAES mode true."); // Testing with given parameters and DHAES mode on c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); c1.init(Cipher.ENCRYPT_MODE, pub, p, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, priv, p, new SecureRandom()); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with non-null parameters, DHAES mode true."); } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DHIESTest()); } }
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4762_5
crossvul-java_data_bad_4762_2
package org.bouncycastle.jcajce.provider.asymmetric.ec; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherSpi; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyEncoder; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECKeyGenerationParameters; import org.bouncycastle.crypto.params.ECKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.parsers.ECIESPublicKeyParser; import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; import org.bouncycastle.jcajce.provider.asymmetric.util.IESUtil; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.ECKey; import org.bouncycastle.jce.interfaces.IESKey; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.Strings; public class IESCipher extends CipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private int ivLength; private IESEngine engine; private int state = -1; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private AlgorithmParameters engineParam = null; private IESParameterSpec engineSpec = null; private AsymmetricKeyParameter key; private SecureRandom random; private boolean dhaesMode = false; private AsymmetricKeyParameter otherKeyParameter = null; public IESCipher(IESEngine engine) { this.engine = engine; this.ivLength = 0; } public IESCipher(IESEngine engine, int ivLength) { this.engine = engine; this.ivLength = ivLength; } public int engineGetBlockSize() { if (engine.getCipher() != null) { return engine.getCipher().getBlockSize(); } else { return 0; } } public int engineGetKeySize(Key key) { if (key instanceof ECKey) { return ((ECKey)key).getParameters().getCurve().getFieldSize(); } else { throw new IllegalArgumentException("not an EC key"); } } public byte[] engineGetIV() { if (engineSpec != null) { return engineSpec.getNonce(); } return null; } public AlgorithmParameters engineGetParameters() { if (engineParam == null && engineSpec != null) { try { engineParam = helper.createAlgorithmParameters("IES"); engineParam.init(engineSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } return engineParam; } public void engineSetMode(String mode) throws NoSuchAlgorithmException { String modeName = Strings.toUpperCase(mode); if (modeName.equals("NONE")) { dhaesMode = false; } else if (modeName.equals("DHAES")) { dhaesMode = true; } else { throw new IllegalArgumentException("can't support mode " + mode); } } public int engineGetOutputSize(int inputLen) { int len1, len2, len3; if (key == null) { throw new IllegalStateException("cipher not initialised"); } len1 = engine.getMac().getMacSize(); if (otherKeyParameter == null) { len2 = 2 * (((ECKeyParameters)key).getParameters().getCurve().getFieldSize() + 7) / 8; } else { len2 = 0; } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + 1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("cipher not initialised"); } } public void engineSetPadding(String padding) throws NoSuchPaddingException { String paddingName = Strings.toUpperCase(padding); // TDOD: make this meaningful... if (paddingName.equals("NOPADDING")) { } else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) { } else { throw new NoSuchPaddingException("padding not available with IESCipher"); } } // Initialisation methods public void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(IESParameterSpec.class); } catch (Exception e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString()); } } engineParam = params; engineInit(opmode, key, paramSpec, random); } public void engineInit( int opmode, Key key, AlgorithmParameterSpec engineSpec, SecureRandom random) throws InvalidAlgorithmParameterException, InvalidKeyException { otherKeyParameter = null; // Use default parameters (including cipher key size) if none are specified if (engineSpec == null) { byte[] nonce = null; if (ivLength != 0 && opmode == Cipher.ENCRYPT_MODE) { nonce = new byte[ivLength]; random.nextBytes(nonce); } this.engineSpec = IESUtil.guessParameterSpec(engine.getCipher(), nonce); } else if (engineSpec instanceof IESParameterSpec) { this.engineSpec = (IESParameterSpec)engineSpec; } else { throw new InvalidAlgorithmParameterException("must be passed IES parameters"); } byte[] nonce = this.engineSpec.getNonce(); if (ivLength != 0 && (nonce == null || nonce.length != ivLength)) { throw new InvalidAlgorithmParameterException("NONCE in IES Parameters needs to be " + ivLength + " bytes long"); } // Parse the recipient's key if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) { if (key instanceof PublicKey) { this.key = ECUtils.generatePublicKeyParameter((PublicKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.key = ECUtils.generatePublicKeyParameter(ieKey.getPublic()); this.otherKeyParameter = ECUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's public EC key for encryption"); } } else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) { if (key instanceof PrivateKey) { this.key = ECUtil.generatePrivateKeyParameter((PrivateKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.otherKeyParameter = ECUtils.generatePublicKeyParameter(ieKey.getPublic()); this.key = ECUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's private EC key for decryption"); } } else { throw new InvalidKeyException("must be passed EC key"); } this.random = random; this.state = opmode; buffer.reset(); } public void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("cannot handle supplied parameter spec: " + e.getMessage()); } } // Update methods - buffer the input public byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { buffer.write(input, inputOffset, inputLen); return null; } public int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { buffer.write(input, inputOffset, inputLen); return 0; } // Finalisation methods public byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } final byte[] in = buffer.toByteArray(); buffer.reset(); // Convert parameters for use in IESEngine CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize()); if (engineSpec.getNonce() != null) { params = new ParametersWithIV(params, engineSpec.getNonce()); } final ECDomainParameters ecParams = ((ECKeyParameters)key).getParameters(); final byte[] V; if (otherKeyParameter != null) { try { if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { engine.init(true, otherKeyParameter, key, params); } else { engine.init(false, key, otherKeyParameter, params); } return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadPaddingException(e.getMessage()); } } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { // Generate the ephemeral key pair ECKeyPairGenerator gen = new ECKeyPairGenerator(); gen.init(new ECKeyGenerationParameters(ecParams, random)); final boolean usePointCompression = engineSpec.getPointCompression(); EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() { public byte[] getEncoded(AsymmetricKeyParameter keyParameter) { return ((ECPublicKeyParameters)keyParameter).getQ().getEncoded(usePointCompression); } }); // Encrypt the buffer try { engine.init(key, params, kGen); return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadPaddingException(e.getMessage()); } } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { // Decrypt the buffer try { engine.init(key, params, new ECIESPublicKeyParser(ecParams)); return engine.processBlock(in, 0, in.length); } catch (InvalidCipherTextException e) { throw new BadPaddingException(e.getMessage()); } } else { throw new IllegalStateException("cipher not initialised"); } } public int engineDoFinal( byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] buf = engineDoFinal(input, inputOffset, inputLength); System.arraycopy(buf, 0, output, outputOffset, buf.length); return buf.length; } /** * Classes that inherit from us */ static public class ECIES extends IESCipher { public ECIES() { super(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()))); } } static public class ECIESwithCipher extends IESCipher { public ECIESwithCipher(BlockCipher cipher, int ivLength) { super(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(cipher)), ivLength); } } static public class ECIESwithDESedeCBC extends ECIESwithCipher { public ECIESwithDESedeCBC() { super(new CBCBlockCipher(new DESedeEngine()), 8); } } static public class ECIESwithAESCBC extends ECIESwithCipher { public ECIESwithAESCBC() { super(new CBCBlockCipher(new AESFastEngine()), 16); } } }
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4762_2
crossvul-java_data_good_4762_5
package org.bouncycastle.jce.provider.test; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.security.Security; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import org.bouncycastle.crypto.agreement.DHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.DESEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.jcajce.provider.asymmetric.dh.IESCipher; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; /** * Test for DHIES - Diffie-Hellman Integrated Encryption Scheme */ public class DHIESTest extends SimpleTest { // Oakley group 2 - RFC 5996 BigInteger p1024 = new BigInteger( "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" + "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" + "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" + "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" + "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381" + "FFFFFFFFFFFFFFFF",16); BigInteger g1024 = new BigInteger("2",16); DHParameterSpec param = new DHParameterSpec(p1024, g1024); DHIESTest() { } public String getName() { return "DHIES"; } public void performTest() throws Exception { byte[] derivation = Hex.decode("202122232425262728292a2b2c2d2e2f"); byte[] encoding = Hex.decode("303132333435363738393a3b3c3d3e3f"); IESCipher c1 = new org.bouncycastle.jcajce.provider.asymmetric.dh.IESCipher.IES(); IESCipher c2 = new org.bouncycastle.jcajce.provider.asymmetric.dh.IESCipher.IES(); IESParameterSpec params = new IESParameterSpec(derivation,encoding,128); // Testing DHIES with default prime in streaming mode KeyPairGenerator g = KeyPairGenerator.getInstance("DH", "BC"); KeyPairGenerator g512 = KeyPairGenerator.getInstance("DH", "BC"); g.initialize(param); doTest("DHIES with default", g, "DHIES", params); // Testing DHIES with 512-bit prime in streaming mode g512.initialize(512, new SecureRandom()); doTest("DHIES with 512-bit", g512, "DHIES", params); // Testing ECIES with 1024-bit prime in streaming mode g.initialize(param, new SecureRandom()); doTest("DHIES with 1024-bit", g, "DHIES", params); c1 = new IESCipher(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new DESEngine()))); c2 = new IESCipher(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new DESEngine()))); params = new IESParameterSpec(derivation, encoding, 128, 192, Hex.decode("0001020304050607")); // Testing DHIES with default prime using DESEDE g = KeyPairGenerator.getInstance("DH", "BC"); doTest("DHIESwithDES default", g, "DHIESwithDESEDE-CBC", params); // Testing DHIES with 512-bit prime using DESEDE doTest("DHIESwithDES 512-bit", g512, "DHIESwithDESEDE-CBC", params); // Testing DHIES with 1024-bit prime using DESEDE g.initialize(param, new SecureRandom()); doTest("DHIESwithDES 1024-bit", g, "DHIESwithDESEDE-CBC", params); g = KeyPairGenerator.getInstance("DH", "BC"); g.initialize(param); c1 = new IESCipher.IESwithAESCBC(); c2 = new IESCipher.IESwithAESCBC(); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("00010203040506070001020304050607")); // Testing DHIES with default prime using AES doTest("DHIESwithAES default", g, "DHIESwithAES-CBC", params); // Testing DHIES with 512-bit prime using AES doTest("DHIESwithAES 512-bit", g512, "DHIESwithAES-CBC", params); // Testing DHIES with 1024-bit prime using AES g.initialize(param, new SecureRandom()); doTest("DHIESwithAES 1024-bit", g, "DHIESwithAES-CBC", params); KeyPair keyPair = g.generateKeyPair(); DHPublicKey pub = (DHPublicKey)keyPair.getPublic(); DHPrivateKey priv = (DHPrivateKey)keyPair.getPrivate(); Cipher c = Cipher.getInstance("DHIESwithAES-CBC", "BC"); try { c.init(Cipher.ENCRYPT_MODE, pub, new IESParameterSpec(derivation, encoding, 128, 128, null)); fail("no exception"); } catch (InvalidAlgorithmParameterException e) { isTrue("message ", "NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } try { c.init(Cipher.DECRYPT_MODE, priv); fail("no exception"); } catch (IllegalArgumentException e) { isTrue("message ", "cannot handle supplied parameter spec: NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } try { c.init(Cipher.DECRYPT_MODE, priv, new IESParameterSpec(derivation, encoding, 128, 128, null)); fail("no exception"); } catch (InvalidAlgorithmParameterException e) { isTrue("message ", "NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } } public void doTest( String testname, KeyPairGenerator g, String cipher, IESParameterSpec p) throws Exception { byte[] message = Hex.decode("0102030405060708090a0b0c0d0e0f10111213141516"); byte[] out1, out2; Cipher c1 = Cipher.getInstance(cipher, "BC"); Cipher c2 = Cipher.getInstance(cipher, "BC"); // Generate static key pair KeyPair keyPair = g.generateKeyPair(); DHPublicKey pub = (DHPublicKey)keyPair.getPublic(); DHPrivateKey priv = (DHPrivateKey)keyPair.getPrivate(); // Testing with default parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, pub, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, priv, c1.getParameters()); isTrue("nonce mismatch", Arrays.areEqual(c1.getIV(), c2.getIV())); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) { fail(testname + " test failed with default parameters, DHAES mode false."); } // Testing with given parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, pub, p, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, priv, p); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with non-null parameters, DHAES mode false."); // Testing with null parameters and DHAES mode on c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); c1.init(Cipher.ENCRYPT_MODE, pub, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, priv, c1.getParameters(), new SecureRandom()); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with null parameters, DHAES mode true."); // Testing with given parameters and DHAES mode on c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); c1.init(Cipher.ENCRYPT_MODE, pub, p, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, priv, p, new SecureRandom()); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with non-null parameters, DHAES mode true."); // // corrupted data test // byte[] tmp = new byte[out1.length]; for (int i = 0; i != out1.length; i++) { System.arraycopy(out1, 0, tmp, 0, tmp.length); tmp[i] = (byte)~tmp[i]; try { c2.doFinal(tmp, 0, tmp.length); fail("decrypted corrupted data"); } catch (BadPaddingException e) { isTrue("wrong message: " + e.getMessage(), "unable to process block".equals(e.getMessage())); } } } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DHIESTest()); } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4762_5
crossvul-java_data_good_4762_2
package org.bouncycastle.jcajce.provider.asymmetric.ec; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherSpi; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyEncoder; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECKeyGenerationParameters; import org.bouncycastle.crypto.params.ECKeyParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.parsers.ECIESPublicKeyParser; import org.bouncycastle.jcajce.provider.asymmetric.util.ECUtil; import org.bouncycastle.jcajce.provider.asymmetric.util.IESUtil; import org.bouncycastle.jcajce.provider.util.BadBlockException; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.ECKey; import org.bouncycastle.jce.interfaces.IESKey; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.Strings; public class IESCipher extends CipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private int ivLength; private IESEngine engine; private int state = -1; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private AlgorithmParameters engineParam = null; private IESParameterSpec engineSpec = null; private AsymmetricKeyParameter key; private SecureRandom random; private boolean dhaesMode = false; private AsymmetricKeyParameter otherKeyParameter = null; public IESCipher(IESEngine engine) { this.engine = engine; this.ivLength = 0; } public IESCipher(IESEngine engine, int ivLength) { this.engine = engine; this.ivLength = ivLength; } public int engineGetBlockSize() { if (engine.getCipher() != null) { return engine.getCipher().getBlockSize(); } else { return 0; } } public int engineGetKeySize(Key key) { if (key instanceof ECKey) { return ((ECKey)key).getParameters().getCurve().getFieldSize(); } else { throw new IllegalArgumentException("not an EC key"); } } public byte[] engineGetIV() { if (engineSpec != null) { return engineSpec.getNonce(); } return null; } public AlgorithmParameters engineGetParameters() { if (engineParam == null && engineSpec != null) { try { engineParam = helper.createAlgorithmParameters("IES"); engineParam.init(engineSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } return engineParam; } public void engineSetMode(String mode) throws NoSuchAlgorithmException { String modeName = Strings.toUpperCase(mode); if (modeName.equals("NONE")) { dhaesMode = false; } else if (modeName.equals("DHAES")) { dhaesMode = true; } else { throw new IllegalArgumentException("can't support mode " + mode); } } public int engineGetOutputSize(int inputLen) { int len1, len2, len3; if (key == null) { throw new IllegalStateException("cipher not initialised"); } len1 = engine.getMac().getMacSize(); if (otherKeyParameter == null) { len2 = 2 * (((ECKeyParameters)key).getParameters().getCurve().getFieldSize() + 7) / 8; } else { len2 = 0; } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + 1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("cipher not initialised"); } } public void engineSetPadding(String padding) throws NoSuchPaddingException { String paddingName = Strings.toUpperCase(padding); // TDOD: make this meaningful... if (paddingName.equals("NOPADDING")) { } else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) { } else { throw new NoSuchPaddingException("padding not available with IESCipher"); } } // Initialisation methods public void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(IESParameterSpec.class); } catch (Exception e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString()); } } engineParam = params; engineInit(opmode, key, paramSpec, random); } public void engineInit( int opmode, Key key, AlgorithmParameterSpec engineSpec, SecureRandom random) throws InvalidAlgorithmParameterException, InvalidKeyException { otherKeyParameter = null; // Use default parameters (including cipher key size) if none are specified if (engineSpec == null) { byte[] nonce = null; if (ivLength != 0 && opmode == Cipher.ENCRYPT_MODE) { nonce = new byte[ivLength]; random.nextBytes(nonce); } this.engineSpec = IESUtil.guessParameterSpec(engine.getCipher(), nonce); } else if (engineSpec instanceof IESParameterSpec) { this.engineSpec = (IESParameterSpec)engineSpec; } else { throw new InvalidAlgorithmParameterException("must be passed IES parameters"); } byte[] nonce = this.engineSpec.getNonce(); if (ivLength != 0 && (nonce == null || nonce.length != ivLength)) { throw new InvalidAlgorithmParameterException("NONCE in IES Parameters needs to be " + ivLength + " bytes long"); } // Parse the recipient's key if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) { if (key instanceof PublicKey) { this.key = ECUtils.generatePublicKeyParameter((PublicKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.key = ECUtils.generatePublicKeyParameter(ieKey.getPublic()); this.otherKeyParameter = ECUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's public EC key for encryption"); } } else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) { if (key instanceof PrivateKey) { this.key = ECUtil.generatePrivateKeyParameter((PrivateKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.otherKeyParameter = ECUtils.generatePublicKeyParameter(ieKey.getPublic()); this.key = ECUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's private EC key for decryption"); } } else { throw new InvalidKeyException("must be passed EC key"); } this.random = random; this.state = opmode; buffer.reset(); } public void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("cannot handle supplied parameter spec: " + e.getMessage()); } } // Update methods - buffer the input public byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { buffer.write(input, inputOffset, inputLen); return null; } public int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { buffer.write(input, inputOffset, inputLen); return 0; } // Finalisation methods public byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } final byte[] in = buffer.toByteArray(); buffer.reset(); // Convert parameters for use in IESEngine CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize()); if (engineSpec.getNonce() != null) { params = new ParametersWithIV(params, engineSpec.getNonce()); } final ECDomainParameters ecParams = ((ECKeyParameters)key).getParameters(); final byte[] V; if (otherKeyParameter != null) { try { if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { engine.init(true, otherKeyParameter, key, params); } else { engine.init(false, key, otherKeyParameter, params); } return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadBlockException("unable to process block", e); } } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { // Generate the ephemeral key pair ECKeyPairGenerator gen = new ECKeyPairGenerator(); gen.init(new ECKeyGenerationParameters(ecParams, random)); final boolean usePointCompression = engineSpec.getPointCompression(); EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() { public byte[] getEncoded(AsymmetricKeyParameter keyParameter) { return ((ECPublicKeyParameters)keyParameter).getQ().getEncoded(usePointCompression); } }); // Encrypt the buffer try { engine.init(key, params, kGen); return engine.processBlock(in, 0, in.length); } catch (final Exception e) { throw new BadBlockException("unable to process block", e); } } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { // Decrypt the buffer try { engine.init(key, params, new ECIESPublicKeyParser(ecParams)); return engine.processBlock(in, 0, in.length); } catch (InvalidCipherTextException e) { throw new BadBlockException("unable to process block", e); } } else { throw new IllegalStateException("cipher not initialised"); } } public int engineDoFinal( byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] buf = engineDoFinal(input, inputOffset, inputLength); System.arraycopy(buf, 0, output, outputOffset, buf.length); return buf.length; } /** * Classes that inherit from us */ static public class ECIES extends IESCipher { public ECIES() { super(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()))); } } static public class ECIESwithCipher extends IESCipher { public ECIESwithCipher(BlockCipher cipher, int ivLength) { super(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(cipher)), ivLength); } } static public class ECIESwithDESedeCBC extends ECIESwithCipher { public ECIESwithDESedeCBC() { super(new CBCBlockCipher(new DESedeEngine()), 8); } } static public class ECIESwithAESCBC extends ECIESwithCipher { public ECIESwithAESCBC() { super(new CBCBlockCipher(new AESFastEngine()), 16); } } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4762_2
crossvul-java_data_good_4762_0
package org.bouncycastle.crypto.engines; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.crypto.BasicAgreement; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DerivationFunction; import org.bouncycastle.crypto.EphemeralKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyParser; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.IESParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.KDFParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Pack; /** * Support class for constructing integrated encryption ciphers * for doing basic message exchanges on top of key agreement ciphers. * Follows the description given in IEEE Std 1363a. */ public class IESEngine { BasicAgreement agree; DerivationFunction kdf; Mac mac; BufferedBlockCipher cipher; byte[] macBuf; boolean forEncryption; CipherParameters privParam, pubParam; IESParameters param; byte[] V; private EphemeralKeyPairGenerator keyPairGenerator; private KeyParser keyParser; private byte[] IV; /** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message */ public IESEngine( BasicAgreement agree, DerivationFunction kdf, Mac mac) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.getMacSize()]; this.cipher = null; } /** * Set up for use in conjunction with a block cipher to handle the * message.It is <b>strongly</b> recommended that the cipher is not in ECB mode. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param cipher the cipher to used for encrypting the message */ public IESEngine( BasicAgreement agree, DerivationFunction kdf, Mac mac, BufferedBlockCipher cipher) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.getMacSize()]; this.cipher = cipher; } /** * Initialise the encryptor. * * @param forEncryption whether or not this is encryption/decryption. * @param privParam our private key parameters * @param pubParam the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. */ public void init( boolean forEncryption, CipherParameters privParam, CipherParameters pubParam, CipherParameters params) { this.forEncryption = forEncryption; this.privParam = privParam; this.pubParam = pubParam; this.V = new byte[0]; extractParams(params); } /** * Initialise the decryptor. * * @param publicKey the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param ephemeralKeyPairGenerator the ephemeral key pair generator to use. */ public void init(AsymmetricKeyParameter publicKey, CipherParameters params, EphemeralKeyPairGenerator ephemeralKeyPairGenerator) { this.forEncryption = true; this.pubParam = publicKey; this.keyPairGenerator = ephemeralKeyPairGenerator; extractParams(params); } /** * Initialise the encryptor. * * @param privateKey the recipient's private key. * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param publicKeyParser the parser for reading the ephemeral public key. */ public void init(AsymmetricKeyParameter privateKey, CipherParameters params, KeyParser publicKeyParser) { this.forEncryption = false; this.privParam = privateKey; this.keyParser = publicKeyParser; extractParams(params); } private void extractParams(CipherParameters params) { if (params instanceof ParametersWithIV) { this.IV = ((ParametersWithIV)params).getIV(); this.param = (IESParameters)((ParametersWithIV)params).getParameters(); } else { this.IV = null; this.param = (IESParameters)params; } } public BufferedBlockCipher getCipher() { return cipher; } public Mac getMac() { return mac; } private byte[] encryptBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { byte[] C = null, K = null, K1 = null, K2 = null; int len; if (cipher == null) { // Streaming mode. K1 = new byte[inLen]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); if (V.length != 0) { System.arraycopy(K, 0, K2, 0, K2.length); System.arraycopy(K, K2.length, K1, 0, K1.length); } else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, inLen, K2, 0, K2.length); } C = new byte[inLen]; for (int i = 0; i != inLen; i++) { C[i] = (byte)(in[inOff + i] ^ K1[i]); } len = inLen; } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If iv provided use it to initialise the cipher if (IV != null) { cipher.init(true, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(true, new KeyParameter(K1)); } C = new byte[cipher.getOutputSize(inLen)]; len = cipher.processBytes(in, inOff, inLen, C, 0); len += cipher.doFinal(C, len); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); byte[] L2 = null; if (V.length != 0) { L2 = getLengthTag(P2); } // Apply the MAC. byte[] T = new byte[mac.getMacSize()]; mac.init(new KeyParameter(K2)); mac.update(C, 0, C.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0) { mac.update(L2, 0, L2.length); } mac.doFinal(T, 0); // Output the triple (V,C,T). byte[] Output = new byte[V.length + len + T.length]; System.arraycopy(V, 0, Output, 0, V.length); System.arraycopy(C, 0, Output, V.length, len); System.arraycopy(T, 0, Output, V.length + len, T.length); return Output; } private byte[] decryptBlock( byte[] in_enc, int inOff, int inLen) throws InvalidCipherTextException { byte[] M, K, K1, K2; int len = 0; // Ensure that the length of the input is greater than the MAC in bytes if (inLen < V.length + mac.getMacSize()) { throw new InvalidCipherTextException("Length of input must be greater than the MAC and V combined"); } // note order is important: set up keys, do simple encryptions, check mac, do final encryption. if (cipher == null) { // Streaming mode. K1 = new byte[inLen - V.length - mac.getMacSize()]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); if (V.length != 0) { System.arraycopy(K, 0, K2, 0, K2.length); System.arraycopy(K, K2.length, K1, 0, K1.length); } else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); } // process the message M = new byte[K1.length]; for (int i = 0; i != K1.length; i++) { M[i] = (byte)(in_enc[inOff + V.length + i] ^ K1[i]); } } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If IV provide use it to initialize the cipher if (IV != null) { cipher.init(false, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(false, new KeyParameter(K1)); } M = new byte[cipher.getOutputSize(inLen - V.length - mac.getMacSize())]; // do initial processing len = cipher.processBytes(in_enc, inOff + V.length, inLen - V.length - mac.getMacSize(), M, 0); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); byte[] L2 = null; if (V.length != 0) { L2 = getLengthTag(P2); } // Verify the MAC. int end = inOff + inLen; byte[] T1 = Arrays.copyOfRange(in_enc, end - mac.getMacSize(), end); byte[] T2 = new byte[T1.length]; mac.init(new KeyParameter(K2)); mac.update(in_enc, inOff + V.length, inLen - V.length - T2.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0) { mac.update(L2, 0, L2.length); } mac.doFinal(T2, 0); if (!Arrays.constantTimeAreEqual(T1, T2)) { throw new InvalidCipherTextException("invalid MAC"); } if (cipher == null) { return M; } else { len += cipher.doFinal(M, len); return Arrays.copyOfRange(M, 0, len); } } public byte[] processBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { if (forEncryption) { if (keyPairGenerator != null) { EphemeralKeyPair ephKeyPair = keyPairGenerator.generate(); this.privParam = ephKeyPair.getKeyPair().getPrivate(); this.V = ephKeyPair.getEncodedPublicKey(); } } else { if (keyParser != null) { ByteArrayInputStream bIn = new ByteArrayInputStream(in, inOff, inLen); try { this.pubParam = keyParser.readKey(bIn); } catch (IOException e) { throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.getMessage(), e); } int encLength = (inLen - bIn.available()); this.V = Arrays.copyOfRange(in, inOff, inOff + encLength); } } // Compute the common value and convert to byte array. agree.init(privParam); BigInteger z = agree.calculateAgreement(pubParam); byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z); // Create input to KDF. if (V.length != 0) { byte[] VZ = Arrays.concatenate(V, Z); Arrays.fill(Z, (byte)0); Z = VZ; } try { // Initialise the KDF. KDFParameters kdfParam = new KDFParameters(Z, param.getDerivationV()); kdf.init(kdfParam); return forEncryption ? encryptBlock(in, inOff, inLen) : decryptBlock(in, inOff, inLen); } finally { Arrays.fill(Z, (byte)0); } } // as described in Shroup's paper and P1363a protected byte[] getLengthTag(byte[] p2) { byte[] L2 = new byte[8]; if (p2 != null) { Pack.longToBigEndian(p2.length * 8L, L2, 0); } return L2; } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4762_0
crossvul-java_data_good_4762_6
package org.bouncycastle.jce.provider.test; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.security.Security; import java.security.spec.ECGenParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.SealedObject; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.DESEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher; import org.bouncycastle.jce.interfaces.ECPrivateKey; import org.bouncycastle.jce.interfaces.ECPublicKey; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; /** * Test for ECIES - Elliptic Curve Integrated Encryption Scheme */ public class ECIESTest extends SimpleTest { ECIESTest() { } public String getName() { return "ECIES"; } public void performTest() throws Exception { byte[] derivation = Hex.decode("202122232425262728292a2b2c2d2e2f"); byte[] encoding = Hex.decode("303132333435363738393a3b3c3d3e3f"); IESCipher c1 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIES(); IESCipher c2 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIES(); IESParameterSpec params = new IESParameterSpec(derivation,encoding,128); // Testing ECIES with default curve in streaming mode KeyPairGenerator g = KeyPairGenerator.getInstance("EC", "BC"); doTest("ECIES with default", g, "ECIES", params); // Testing ECIES with 192-bit curve in streaming mode g.initialize(192, new SecureRandom()); doTest("ECIES with 192-bit", g, "ECIES", params); // Testing ECIES with 256-bit curve in streaming mode g.initialize(256, new SecureRandom()); doTest("ECIES with 256-bit", g, "ECIES", params); c1 = new IESCipher(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new DESEngine()))); c2 = new IESCipher(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new DESEngine()))); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("0001020304050607")); // Testing ECIES with default curve using DES g = KeyPairGenerator.getInstance("EC", "BC"); // Testing ECIES with 256-bit curve using DES-CBC g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithDESEDE-CBC", params); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("0001020304050607")); g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithDESEDE-CBC", params); try { params = new IESParameterSpec(derivation, encoding, 128, 128, new byte[10]); g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithDESEDE-CBC", params); fail("DESEDE no exception!"); } catch (InvalidAlgorithmParameterException e) { if (!e.getMessage().equals("NONCE in IES Parameters needs to be 8 bytes long")) { fail("DESEDE wrong message!"); } } c1 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIESwithAESCBC(); c2 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIESwithAESCBC(); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("000102030405060708090a0b0c0d0e0f")); // Testing ECIES with 256-bit curve using AES-CBC g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithAES-CBC", params); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("000102030405060708090a0b0c0d0e0f")); g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithAES-CBC", params); try { params = new IESParameterSpec(derivation, encoding, 128, 128, new byte[10]); g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithAES-CBC", params); fail("AES no exception!"); } catch (InvalidAlgorithmParameterException e) { if (!e.getMessage().equals("NONCE in IES Parameters needs to be 16 bytes long")) { fail("AES wrong message!"); } } KeyPair keyPair = g.generateKeyPair(); ECPublicKey pub = (ECPublicKey)keyPair.getPublic(); ECPrivateKey priv = (ECPrivateKey)keyPair.getPrivate(); Cipher c = Cipher.getInstance("ECIESwithAES-CBC", "BC"); try { c.init(Cipher.ENCRYPT_MODE, pub, new IESParameterSpec(derivation, encoding, 128, 128, null)); fail("no exception"); } catch (InvalidAlgorithmParameterException e) { isTrue("message ", "NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } try { c.init(Cipher.DECRYPT_MODE, priv); fail("no exception"); } catch (IllegalArgumentException e) { isTrue("message ", "cannot handle supplied parameter spec: NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } try { c.init(Cipher.DECRYPT_MODE, priv, new IESParameterSpec(derivation, encoding, 128, 128, null)); fail("no exception"); } catch (InvalidAlgorithmParameterException e) { isTrue("message ", "NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } sealedObjectTest(); } private void sealedObjectTest() throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECIES"); kpg.initialize(new ECGenParameterSpec("secp256r1")); KeyPair keyPair = kpg.generateKeyPair(); Cipher cipher = Cipher.getInstance("ECIES"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); String toEncrypt = "Hello"; // Check that cipher works ok cipher.doFinal(toEncrypt.getBytes()); // Using a SealedObject to encrypt the same string fails with a NullPointerException SealedObject sealedObject = new SealedObject(toEncrypt, cipher); cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); String result = (String)sealedObject.getObject(cipher); isTrue("result wrong", result.equals(toEncrypt)); result = (String)sealedObject.getObject(keyPair.getPrivate()); isTrue("result wrong", result.equals(toEncrypt)); } public void doTest( String testname, KeyPairGenerator g, String cipher, IESParameterSpec p) throws Exception { byte[] message = Hex.decode("0102030405060708090a0b0c0d0e0f10111213141516"); byte[] out1, out2; // Generate static key pair KeyPair KeyPair = g.generateKeyPair(); ECPublicKey Pub = (ECPublicKey) KeyPair.getPublic(); ECPrivateKey Priv = (ECPrivateKey) KeyPair.getPrivate(); Cipher c1 = Cipher.getInstance(cipher); Cipher c2 = Cipher.getInstance(cipher); // Testing with null parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, Priv, c1.getParameters()); isTrue("nonce mismatch", Arrays.areEqual(c1.getIV(), c2.getIV())); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with null parameters, DHAES mode false."); // Testing with given parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, Priv, p); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with non-null parameters, DHAES mode false."); // // corrupted data test // int offset = out1.length - (message.length + 8); byte[] tmp = new byte[out1.length]; for (int i = offset; i != out1.length; i++) { System.arraycopy(out1, 0, tmp, 0, tmp.length); tmp[i] = (byte)~tmp[i]; try { c2.doFinal(tmp, 0, tmp.length); fail("decrypted corrupted data"); } catch (BadPaddingException e) { isTrue("wrong message: " + e.getMessage(), "unable to process block".equals(e.getMessage())); } } // TODO: DHAES mode is not currently implemented, perhaps it shouldn't be... // c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); // c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); // // // Testing with null parameters and DHAES mode on // c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom()); // c2.init(Cipher.DECRYPT_MODE, Priv, new SecureRandom()); // // out1 = c1.doFinal(message, 0, message.length); // out2 = c2.doFinal(out1, 0, out1.length); // if (!areEqual(out2, message)) // fail(testname + " test failed with null parameters, DHAES mode true."); // // c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); // c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); // // // Testing with given parameters and DHAES mode on // c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom()); // c2.init(Cipher.DECRYPT_MODE, Priv, p, new SecureRandom()); // // out1 = c1.doFinal(message, 0, message.length); // out2 = c2.doFinal(out1, 0, out1.length); // if (!areEqual(out2, message)) // fail(testname + " test failed with non-null parameters, DHAES mode true."); } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new ECIESTest()); } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4762_6
crossvul-java_data_good_4762_3
package org.bouncycastle.jcajce.provider.asymmetric.rsa; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.InvalidParameterException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidParameterSpecException; import java.security.spec.MGF1ParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.OAEPParameterSpec; import javax.crypto.spec.PSource; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.crypto.AsymmetricBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.encodings.ISO9796d1Encoding; import org.bouncycastle.crypto.encodings.OAEPEncoding; import org.bouncycastle.crypto.encodings.PKCS1Encoding; import org.bouncycastle.crypto.engines.RSABlindedEngine; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.jcajce.provider.asymmetric.util.BaseCipherSpi; import org.bouncycastle.jcajce.provider.util.BadBlockException; import org.bouncycastle.jcajce.provider.util.DigestFactory; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.util.Strings; public class CipherSpi extends BaseCipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private AsymmetricBlockCipher cipher; private AlgorithmParameterSpec paramSpec; private AlgorithmParameters engineParams; private boolean publicKeyOnly = false; private boolean privateKeyOnly = false; private ByteArrayOutputStream bOut = new ByteArrayOutputStream(); public CipherSpi( AsymmetricBlockCipher engine) { cipher = engine; } public CipherSpi( OAEPParameterSpec pSpec) { try { initFromSpec(pSpec); } catch (NoSuchPaddingException e) { throw new IllegalArgumentException(e.getMessage()); } } public CipherSpi( boolean publicKeyOnly, boolean privateKeyOnly, AsymmetricBlockCipher engine) { this.publicKeyOnly = publicKeyOnly; this.privateKeyOnly = privateKeyOnly; cipher = engine; } private void initFromSpec( OAEPParameterSpec pSpec) throws NoSuchPaddingException { MGF1ParameterSpec mgfParams = (MGF1ParameterSpec)pSpec.getMGFParameters(); Digest digest = DigestFactory.getDigest(mgfParams.getDigestAlgorithm()); if (digest == null) { throw new NoSuchPaddingException("no match on OAEP constructor for digest algorithm: "+ mgfParams.getDigestAlgorithm()); } cipher = new OAEPEncoding(new RSABlindedEngine(), digest, ((PSource.PSpecified)pSpec.getPSource()).getValue()); paramSpec = pSpec; } protected int engineGetBlockSize() { try { return cipher.getInputBlockSize(); } catch (NullPointerException e) { throw new IllegalStateException("RSA Cipher not initialised"); } } protected int engineGetKeySize( Key key) { if (key instanceof RSAPrivateKey) { RSAPrivateKey k = (RSAPrivateKey)key; return k.getModulus().bitLength(); } else if (key instanceof RSAPublicKey) { RSAPublicKey k = (RSAPublicKey)key; return k.getModulus().bitLength(); } throw new IllegalArgumentException("not an RSA key!"); } protected int engineGetOutputSize( int inputLen) { try { return cipher.getOutputBlockSize(); } catch (NullPointerException e) { throw new IllegalStateException("RSA Cipher not initialised"); } } protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (paramSpec != null) { try { engineParams = helper.createAlgorithmParameters("OAEP"); engineParams.init(paramSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } } return engineParams; } protected void engineSetMode( String mode) throws NoSuchAlgorithmException { String md = Strings.toUpperCase(mode); if (md.equals("NONE") || md.equals("ECB")) { return; } if (md.equals("1")) { privateKeyOnly = true; publicKeyOnly = false; return; } else if (md.equals("2")) { privateKeyOnly = false; publicKeyOnly = true; return; } throw new NoSuchAlgorithmException("can't support mode " + mode); } protected void engineSetPadding( String padding) throws NoSuchPaddingException { String pad = Strings.toUpperCase(padding); if (pad.equals("NOPADDING")) { cipher = new RSABlindedEngine(); } else if (pad.equals("PKCS1PADDING")) { cipher = new PKCS1Encoding(new RSABlindedEngine()); } else if (pad.equals("ISO9796-1PADDING")) { cipher = new ISO9796d1Encoding(new RSABlindedEngine()); } else if (pad.equals("OAEPWITHMD5ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("MD5", "MGF1", new MGF1ParameterSpec("MD5"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPPADDING")) { initFromSpec(OAEPParameterSpec.DEFAULT); } else if (pad.equals("OAEPWITHSHA1ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-1ANDMGF1PADDING")) { initFromSpec(OAEPParameterSpec.DEFAULT); } else if (pad.equals("OAEPWITHSHA224ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-224ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA-224", "MGF1", new MGF1ParameterSpec("SHA-224"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA256ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-256ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA384ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-384ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA512ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-512ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA3-224ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA3-224", "MGF1", new MGF1ParameterSpec("SHA3-224"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA3-256ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA3-256", "MGF1", new MGF1ParameterSpec("SHA3-256"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA3-384ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA3-384", "MGF1", new MGF1ParameterSpec("SHA3-384"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA3-512ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA3-512", "MGF1", new MGF1ParameterSpec("SHA3-512"), PSource.PSpecified.DEFAULT)); } else { throw new NoSuchPaddingException(padding + " unavailable with RSA."); } } protected void engineInit( int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { CipherParameters param; if (params == null || params instanceof OAEPParameterSpec) { if (key instanceof RSAPublicKey) { if (privateKeyOnly && opmode == Cipher.ENCRYPT_MODE) { throw new InvalidKeyException( "mode 1 requires RSAPrivateKey"); } param = RSAUtil.generatePublicKeyParameter((RSAPublicKey)key); } else if (key instanceof RSAPrivateKey) { if (publicKeyOnly && opmode == Cipher.ENCRYPT_MODE) { throw new InvalidKeyException( "mode 2 requires RSAPublicKey"); } param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)key); } else { throw new InvalidKeyException("unknown key type passed to RSA"); } if (params != null) { OAEPParameterSpec spec = (OAEPParameterSpec)params; paramSpec = params; if (!spec.getMGFAlgorithm().equalsIgnoreCase("MGF1") && !spec.getMGFAlgorithm().equals(PKCSObjectIdentifiers.id_mgf1.getId())) { throw new InvalidAlgorithmParameterException("unknown mask generation function specified"); } if (!(spec.getMGFParameters() instanceof MGF1ParameterSpec)) { throw new InvalidAlgorithmParameterException("unkown MGF parameters"); } Digest digest = DigestFactory.getDigest(spec.getDigestAlgorithm()); if (digest == null) { throw new InvalidAlgorithmParameterException("no match on digest algorithm: "+ spec.getDigestAlgorithm()); } MGF1ParameterSpec mgfParams = (MGF1ParameterSpec)spec.getMGFParameters(); Digest mgfDigest = DigestFactory.getDigest(mgfParams.getDigestAlgorithm()); if (mgfDigest == null) { throw new InvalidAlgorithmParameterException("no match on MGF digest algorithm: "+ mgfParams.getDigestAlgorithm()); } cipher = new OAEPEncoding(new RSABlindedEngine(), digest, mgfDigest, ((PSource.PSpecified)spec.getPSource()).getValue()); } } else { throw new InvalidAlgorithmParameterException("unknown parameter type: " + params.getClass().getName()); } if (!(cipher instanceof RSABlindedEngine)) { if (random != null) { param = new ParametersWithRandom(param, random); } else { param = new ParametersWithRandom(param, new SecureRandom()); } } bOut.reset(); switch (opmode) { case Cipher.ENCRYPT_MODE: case Cipher.WRAP_MODE: cipher.init(true, param); break; case Cipher.DECRYPT_MODE: case Cipher.UNWRAP_MODE: cipher.init(false, param); break; default: throw new InvalidParameterException("unknown opmode " + opmode + " passed to RSA"); } } protected void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(OAEPParameterSpec.class); } catch (InvalidParameterSpecException e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString(), e); } } engineParams = params; engineInit(opmode, key, paramSpec, random); } protected void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { // this shouldn't happen throw new InvalidKeyException("Eeeek! " + e.toString(), e); } } protected byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { bOut.write(input, inputOffset, inputLen); if (cipher instanceof RSABlindedEngine) { if (bOut.size() > cipher.getInputBlockSize() + 1) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } else { if (bOut.size() > cipher.getInputBlockSize()) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } return null; } protected int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { bOut.write(input, inputOffset, inputLen); if (cipher instanceof RSABlindedEngine) { if (bOut.size() > cipher.getInputBlockSize() + 1) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } else { if (bOut.size() > cipher.getInputBlockSize()) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } return 0; } protected byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (input != null) { bOut.write(input, inputOffset, inputLen); } if (cipher instanceof RSABlindedEngine) { if (bOut.size() > cipher.getInputBlockSize() + 1) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } else { if (bOut.size() > cipher.getInputBlockSize()) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } return getOutput(); } protected int engineDoFinal( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws IllegalBlockSizeException, BadPaddingException { if (input != null) { bOut.write(input, inputOffset, inputLen); } if (cipher instanceof RSABlindedEngine) { if (bOut.size() > cipher.getInputBlockSize() + 1) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } else { if (bOut.size() > cipher.getInputBlockSize()) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } byte[] out = getOutput(); for (int i = 0; i != out.length; i++) { output[outputOffset + i] = out[i]; } return out.length; } private byte[] getOutput() throws BadPaddingException { try { byte[] bytes = bOut.toByteArray(); return cipher.processBlock(bytes, 0, bytes.length); } catch (InvalidCipherTextException e) { throw new BadBlockException("unable to decrypt block", e); } finally { bOut.reset(); } } /** * classes that inherit from us. */ static public class NoPadding extends CipherSpi { public NoPadding() { super(new RSABlindedEngine()); } } static public class PKCS1v1_5Padding extends CipherSpi { public PKCS1v1_5Padding() { super(new PKCS1Encoding(new RSABlindedEngine())); } } static public class PKCS1v1_5Padding_PrivateOnly extends CipherSpi { public PKCS1v1_5Padding_PrivateOnly() { super(false, true, new PKCS1Encoding(new RSABlindedEngine())); } } static public class PKCS1v1_5Padding_PublicOnly extends CipherSpi { public PKCS1v1_5Padding_PublicOnly() { super(true, false, new PKCS1Encoding(new RSABlindedEngine())); } } static public class OAEPPadding extends CipherSpi { public OAEPPadding() { super(OAEPParameterSpec.DEFAULT); } } static public class ISO9796d1Padding extends CipherSpi { public ISO9796d1Padding() { super(new ISO9796d1Encoding(new RSABlindedEngine())); } } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4762_3
crossvul-java_data_good_4758_2
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAParameterSpec; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 }); // DSA modified signatures, courtesy of the Google security team static final DSAPrivateKeySpec PRIVATE_KEY = new DSAPrivateKeySpec( // x new BigInteger( "15382583218386677486843706921635237927801862255437148328980464126979"), // p new BigInteger( "181118486631420055711787706248812146965913392568235070235446058914" + "1170708161715231951918020125044061516370042605439640379530343556" + "4101919053459832890139496933938670005799610981765220283775567361" + "4836626483403394052203488713085936276470766894079318754834062443" + "1033792580942743268186462355159813630244169054658542719322425431" + "4088256212718983105131138772434658820375111735710449331518776858" + "7867938758654181244292694091187568128410190746310049564097068770" + "8161261634790060655580211122402292101772553741704724263582994973" + "9109274666495826205002104010355456981211025738812433088757102520" + "562459649777989718122219159982614304359"), // q new BigInteger( "19689526866605154788513693571065914024068069442724893395618704484701"), // g new BigInteger( "2859278237642201956931085611015389087970918161297522023542900348" + "0877180630984239764282523693409675060100542360520959501692726128" + "3149190229583566074777557293475747419473934711587072321756053067" + "2532404847508798651915566434553729839971841903983916294692452760" + "2490198571084091890169933809199002313226100830607842692992570749" + "0504363602970812128803790973955960534785317485341020833424202774" + "0275688698461842637641566056165699733710043802697192696426360843" + "1736206792141319514001488556117408586108219135730880594044593648" + "9237302749293603778933701187571075920849848690861126195402696457" + "4111219599568903257472567764789616958430")); static final DSAPublicKeySpec PUBLIC_KEY = new DSAPublicKeySpec( new BigInteger( "3846308446317351758462473207111709291533523711306097971550086650" + "2577333637930103311673872185522385807498738696446063139653693222" + "3528823234976869516765207838304932337200968476150071617737755913" + "3181601169463467065599372409821150709457431511200322947508290005" + "1780020974429072640276810306302799924668893998032630777409440831" + "4314588994475223696460940116068336991199969153649625334724122468" + "7497038281983541563359385775312520539189474547346202842754393945" + "8755803223951078082197762886933401284142487322057236814878262166" + "5072306622943221607031324846468109901964841479558565694763440972" + "5447389416166053148132419345627682740529"), PRIVATE_KEY.getP(), PRIVATE_KEY.getQ(), PRIVATE_KEY.getG()); // The following test vectors check for signature malleability and bugs. That means the test // vectors are derived from a valid signature by modifying the ASN encoding. A correct // implementation of DSA should only accept correct DER encoding and properly handle the others. // Allowing alternative BER encodings is in many cases benign. An example where this kind of // signature malleability was a problem: https://en.bitcoin.it/wiki/Transaction_Malleability static final String[] MODIFIED_SIGNATURES = { "303e02811c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f0282001c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021d001e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd02811d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd0282001d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021e0000ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "30813d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "3082003d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9ef4" + "1dd424a4e1c8f16967cf3365813fe87862360000", "3040021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca8021d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3040100", "303e021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca802811d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3" }; private void testModified() throws Exception { KeyFactory kFact = KeyFactory.getInstance("DSA", "BC"); PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); Signature sig = Signature.getInstance("DSA", "BC"); for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) { sig.initVerify(pubKey); sig.update(Strings.toByteArray("Hello")); boolean failed; try { failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); } catch (SignatureException e) { failed = true; } isTrue("sig verified when shouldn't", failed); } } private void testCompat() throws Exception { if (Security.getProvider("SUN") == null) { return; } Signature s = Signature.getInstance("DSA", "SUN"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); // // sign SUN - verify with BC // s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("SUN -> BC verification failed"); } // // sign BC - verify with SUN // s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("DSA", "SUN"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("BC -> SUN verification failed"); } // // key encoding test - BC decoding Sun keys // KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded()); DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded()); DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); // // key decoding test - SUN decoding BC keys // f = KeyFactory.getInstance("DSA", "SUN"); x509s = new X509EncodedKeySpec(k1.getEncoded()); vKey = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded()); sKey = f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); } private void testNullParameters() throws Exception { KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded()); DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s); DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s); isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null); isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode()); isTrue("not equal", key1.equals(key2)); isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded())); } private void testValidate() throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); KeyFactory f = KeyFactory.getInstance("DSA", "BC"); try { f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ())); fail("no exception"); } catch (Exception e) { isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage())); } } private void testNONEwithDSA() throws Exception { byte[] dummySha1 = Hex.decode("01020304050607080910111213141516"); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC"); kpGen.initialize(512); KeyPair kp = kpGen.generateKeyPair(); Signature sig = Signature.getInstance("NONEwithDSA", "BC"); sig.initSign(kp.getPrivate()); sig.update(dummySha1); byte[] sigBytes = sig.sign(); sig.initVerify(kp.getPublic()); sig.update(dummySha1); sig.verify(sigBytes); // reset test sig.update(dummySha1); if (!sig.verify(sigBytes)) { fail("NONEwithDSA failed to reset"); } // lightweight test DSAPublicKey key = (DSAPublicKey)kp.getPublic(); DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG()); DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params); DSASigner signer = new DSASigner(); ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes)); signer.init(false, keyParams); if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue())) { fail("NONEwithDSA not really NONE!"); } } private void checkPublic(DSAPublicKey k1, PublicKey vKey) { if (!k1.getY().equals(((DSAPublicKey)vKey).getY())) { fail("public number not decoded properly"); } if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG())) { fail("public generator not decoded properly"); } if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP())) { fail("public p value not decoded properly"); } if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ())) { fail("public q value not decoded properly"); } } private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey) { if (!k2.getX().equals(((DSAPrivateKey)sKey).getX())) { fail("private number not decoded properly"); } if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG())) { fail("private generator not decoded properly"); } if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP())) { fail("private p value not decoded properly"); } if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ())) { fail("private q value not decoded properly"); } } private Object serializeDeserialize(Object o) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutputStream oOut = new ObjectOutputStream(bOut); oOut.writeObject(o); oOut.close(); ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); return oIn.readObject(); } /** * X9.62 - 1998,<br> * J.3.2, Page 155, ECDSA over the field Fp<br> * an example with 239 bit prime */ private void testECDSA239bitPrime() throws Exception { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); sgr.initSign(sKey, k); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testNONEwithECDSA239bitPrime() throws Exception { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("NONEwithECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); byte[] message = "abc".getBytes(); byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d"); checkMessage(sgr, sKey, vKey, message, sig); message = "abcdefghijklmnopqrstuvwxyz".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c"); checkMessage(sgr, sKey, vKey, message, sig); message = "a very very long message gauranteed to cause an overflow".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a"); checkMessage(sgr, sKey, vKey, message, sig); } private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { X9ECParameters p = NISTNamedCurves.getByName("P-256"); KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC"); ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); ECCurve curve = p.getCurve(); ECParameterSpec spec = new ECParameterSpec( curve, p.getG(), // G p.getN()); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q spec); doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey); doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey); } private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeySpec priKey = new DSAPrivateKeySpec( x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); DSAPublicKeySpec pubKey = new DSAPublicKeySpec( y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC"); doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey); doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey); } private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))), new FixedSecureRandom.Data(Hex.decode("01020304")) }); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig) throws InvalidKeyException, SignatureException { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); if (!Arrays.areEqual(sigBytes, sig)) { fail(new String(message) + " signature incorrect"); } sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail(new String(message) + " verification failed"); } } /** * X9.62 - 1998,<br> * J.2.1, Page 100, ECDSA over the field F2m<br> * an example with 191 bit binary field */ private void testECDSA239bitBinary() throws Exception { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid) throws Exception { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance(algorithm, "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr = Signature.getInstance(oid.getId(), "BC"); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC RIPEMD160 verification failed"); } } private void testGeneration() throws Exception { Signature s = Signature.getInstance("DSA", "BC"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // test exception // try { g.initialize(513, new SecureRandom()); fail("illegal parameter 513 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(510, new SecureRandom()); fail("illegal parameter 510 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(1025, new SecureRandom()); fail("illegal parameter 1025 check failed."); } catch (IllegalArgumentException e) { // expected } g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } // // key decoding test - serialisation test // DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey); checkPublic(k1, vKey); checkEquals(k1, vKey); DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey); checkPrivateKey(k2, sKey); checkEquals(k2, sKey); if (!(k2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } // // ECDSA Fp generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // PublicKey eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // Named curve parameter g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // // ECDSA F2m generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); if (!(eck2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } } private void checkEquals(Object o1, Object o2) { if (!o1.equals(o2)) { fail("comparison test failed"); } if (o1.hashCode() != o2.hashCode()) { fail("hashCode test failed"); } } private void testParameters() throws Exception { AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(512, random); AlgorithmParameters params = a.generateParameters(); byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } private void testDSA2Parameters() throws Exception { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(2048, new DSATestSecureRandom(seed)); AlgorithmParameters params = a.generateParameters(); DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!dsaP.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!dsaP.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); KeyPair p = g.generateKeyPair(); DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); if (!vKey.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!sKey.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } public void performTest() throws Exception { testCompat(); testNONEwithDSA(); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); testECDSA239bitPrime(); testNONEwithECDSA239bitPrime(); testECDSA239bitBinary(); testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160); testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1); testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16)); testGeneration(); testParameters(); testDSA2Parameters(); testNullParameters(); testValidate(); testModified(); } protected BigInteger[] derDecode( byte[] encoding) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(encoding); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence s = (ASN1Sequence)aIn.readObject(); BigInteger[] sig = new BigInteger[2]; sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } public String getName() { return "DSA/ECDSA"; } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4758_2
crossvul-java_data_bad_4762_0
package org.bouncycastle.crypto.engines; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.crypto.BasicAgreement; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DerivationFunction; import org.bouncycastle.crypto.EphemeralKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyParser; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.IESParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.KDFParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Pack; /** * Support class for constructing integrated encryption ciphers * for doing basic message exchanges on top of key agreement ciphers. * Follows the description given in IEEE Std 1363a. */ public class IESEngine { BasicAgreement agree; DerivationFunction kdf; Mac mac; BufferedBlockCipher cipher; byte[] macBuf; boolean forEncryption; CipherParameters privParam, pubParam; IESParameters param; byte[] V; private EphemeralKeyPairGenerator keyPairGenerator; private KeyParser keyParser; private byte[] IV; /** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message */ public IESEngine( BasicAgreement agree, DerivationFunction kdf, Mac mac) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.getMacSize()]; this.cipher = null; } /** * set up for use in conjunction with a block cipher to handle the * message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param cipher the cipher to used for encrypting the message */ public IESEngine( BasicAgreement agree, DerivationFunction kdf, Mac mac, BufferedBlockCipher cipher) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.getMacSize()]; this.cipher = cipher; } /** * Initialise the encryptor. * * @param forEncryption whether or not this is encryption/decryption. * @param privParam our private key parameters * @param pubParam the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. */ public void init( boolean forEncryption, CipherParameters privParam, CipherParameters pubParam, CipherParameters params) { this.forEncryption = forEncryption; this.privParam = privParam; this.pubParam = pubParam; this.V = new byte[0]; extractParams(params); } /** * Initialise the decryptor. * * @param publicKey the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param ephemeralKeyPairGenerator the ephemeral key pair generator to use. */ public void init(AsymmetricKeyParameter publicKey, CipherParameters params, EphemeralKeyPairGenerator ephemeralKeyPairGenerator) { this.forEncryption = true; this.pubParam = publicKey; this.keyPairGenerator = ephemeralKeyPairGenerator; extractParams(params); } /** * Initialise the encryptor. * * @param privateKey the recipient's private key. * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param publicKeyParser the parser for reading the ephemeral public key. */ public void init(AsymmetricKeyParameter privateKey, CipherParameters params, KeyParser publicKeyParser) { this.forEncryption = false; this.privParam = privateKey; this.keyParser = publicKeyParser; extractParams(params); } private void extractParams(CipherParameters params) { if (params instanceof ParametersWithIV) { this.IV = ((ParametersWithIV)params).getIV(); this.param = (IESParameters)((ParametersWithIV)params).getParameters(); } else { this.IV = null; this.param = (IESParameters)params; } } public BufferedBlockCipher getCipher() { return cipher; } public Mac getMac() { return mac; } private byte[] encryptBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { byte[] C = null, K = null, K1 = null, K2 = null; int len; if (cipher == null) { // Streaming mode. K1 = new byte[inLen]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); if (V.length != 0) { System.arraycopy(K, 0, K2, 0, K2.length); System.arraycopy(K, K2.length, K1, 0, K1.length); } else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, inLen, K2, 0, K2.length); } C = new byte[inLen]; for (int i = 0; i != inLen; i++) { C[i] = (byte)(in[inOff + i] ^ K1[i]); } len = inLen; } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If iv provided use it to initialise the cipher if (IV != null) { cipher.init(true, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(true, new KeyParameter(K1)); } C = new byte[cipher.getOutputSize(inLen)]; len = cipher.processBytes(in, inOff, inLen, C, 0); len += cipher.doFinal(C, len); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); byte[] L2 = null; if (V.length != 0) { L2 = getLengthTag(P2); } // Apply the MAC. byte[] T = new byte[mac.getMacSize()]; mac.init(new KeyParameter(K2)); mac.update(C, 0, C.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0) { mac.update(L2, 0, L2.length); } mac.doFinal(T, 0); // Output the triple (V,C,T). byte[] Output = new byte[V.length + len + T.length]; System.arraycopy(V, 0, Output, 0, V.length); System.arraycopy(C, 0, Output, V.length, len); System.arraycopy(T, 0, Output, V.length + len, T.length); return Output; } private byte[] decryptBlock( byte[] in_enc, int inOff, int inLen) throws InvalidCipherTextException { byte[] M = null, K = null, K1 = null, K2 = null; int len; // Ensure that the length of the input is greater than the MAC in bytes if (inLen < V.length + mac.getMacSize()) { throw new InvalidCipherTextException("Length of input must be greater than the MAC and V combined"); } if (cipher == null) { // Streaming mode. K1 = new byte[inLen - V.length - mac.getMacSize()]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); if (V.length != 0) { System.arraycopy(K, 0, K2, 0, K2.length); System.arraycopy(K, K2.length, K1, 0, K1.length); } else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); } M = new byte[K1.length]; for (int i = 0; i != K1.length; i++) { M[i] = (byte)(in_enc[inOff + V.length + i] ^ K1[i]); } len = K1.length; } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If IV provide use it to initialize the cipher if (IV != null) { cipher.init(false, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(false, new KeyParameter(K1)); } M = new byte[cipher.getOutputSize(inLen - V.length - mac.getMacSize())]; len = cipher.processBytes(in_enc, inOff + V.length, inLen - V.length - mac.getMacSize(), M, 0); len += cipher.doFinal(M, len); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); byte[] L2 = null; if (V.length != 0) { L2 = getLengthTag(P2); } // Verify the MAC. int end = inOff + inLen; byte[] T1 = Arrays.copyOfRange(in_enc, end - mac.getMacSize(), end); byte[] T2 = new byte[T1.length]; mac.init(new KeyParameter(K2)); mac.update(in_enc, inOff + V.length, inLen - V.length - T2.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0) { mac.update(L2, 0, L2.length); } mac.doFinal(T2, 0); if (!Arrays.constantTimeAreEqual(T1, T2)) { throw new InvalidCipherTextException("Invalid MAC."); } // Output the message. return Arrays.copyOfRange(M, 0, len); } public byte[] processBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { if (forEncryption) { if (keyPairGenerator != null) { EphemeralKeyPair ephKeyPair = keyPairGenerator.generate(); this.privParam = ephKeyPair.getKeyPair().getPrivate(); this.V = ephKeyPair.getEncodedPublicKey(); } } else { if (keyParser != null) { ByteArrayInputStream bIn = new ByteArrayInputStream(in, inOff, inLen); try { this.pubParam = keyParser.readKey(bIn); } catch (IOException e) { throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.getMessage(), e); } int encLength = (inLen - bIn.available()); this.V = Arrays.copyOfRange(in, inOff, inOff + encLength); } } // Compute the common value and convert to byte array. agree.init(privParam); BigInteger z = agree.calculateAgreement(pubParam); byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z); // Create input to KDF. if (V.length != 0) { byte[] VZ = Arrays.concatenate(V, Z); Arrays.fill(Z, (byte)0); Z = VZ; } try { // Initialise the KDF. KDFParameters kdfParam = new KDFParameters(Z, param.getDerivationV()); kdf.init(kdfParam); return forEncryption ? encryptBlock(in, inOff, inLen) : decryptBlock(in, inOff, inLen); } finally { Arrays.fill(Z, (byte)0); } } // as described in Shroup's paper and P1363a protected byte[] getLengthTag(byte[] p2) { byte[] L2 = new byte[8]; if (p2 != null) { Pack.longToBigEndian(p2.length * 8L, L2, 0); } return L2; } }
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4762_0
crossvul-java_data_good_4758_1
package org.bouncycastle.crypto.test; import java.math.BigInteger; import java.security.SecureRandom; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.digests.SHA224Digest; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.digests.SHA3Digest; import org.bouncycastle.crypto.generators.DSAKeyPairGenerator; import org.bouncycastle.crypto.generators.DSAParametersGenerator; import org.bouncycastle.crypto.params.DSAKeyGenerationParameters; import org.bouncycastle.crypto.params.DSAParameterGenerationParameters; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.DSAValidationParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.signers.DSADigestSigner; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; /** * Test based on FIPS 186-2, Appendix 5, an example of DSA, and FIPS 168-3 test vectors. */ public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.Data(k1), new FixedSecureRandom.Data(k2) }); byte[] keyData = Hex.decode("b5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); SecureRandom keyRandom = new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.Data(keyData), new FixedSecureRandom.Data(keyData), new FixedSecureRandom.Data(Hex.decode("01020304"))}); BigInteger pValue = new BigInteger("8df2a494492276aa3d25759bb06869cbeac0d83afb8d0cf7cbb8324f0d7882e5d0762fc5b7210eafc2e9adac32ab7aac49693dfbf83724c2ec0736ee31c80291", 16); BigInteger qValue = new BigInteger("c773218c737ec8ee993b4f2ded30f48edace915f", 16); public String getName() { return "DSA"; } public void performTest() { BigInteger r = new BigInteger("68076202252361894315274692543577577550894681403"); BigInteger s = new BigInteger("1089214853334067536215539335472893651470583479365"); DSAParametersGenerator pGen = new DSAParametersGenerator(); pGen.init(512, 80, random); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pValid = params.getValidationParameters(); if (pValid.getCounter() != 105) { fail("Counter wrong"); } if (!pValue.equals(params.getP()) || !qValue.equals(params.getQ())) { fail("p or q wrong"); } DSAKeyPairGenerator dsaKeyGen = new DSAKeyPairGenerator(); DSAKeyGenerationParameters genParam = new DSAKeyGenerationParameters(keyRandom, params); dsaKeyGen.init(genParam); AsymmetricCipherKeyPair pair = dsaKeyGen.generateKeyPair(); ParametersWithRandom param = new ParametersWithRandom(pair.getPrivate(), keyRandom); DSASigner dsa = new DSASigner(); dsa.init(true, param); byte[] message = BigIntegers.asUnsignedByteArray(new BigInteger("968236873715988614170569073515315707566766479517")); BigInteger[] sig = dsa.generateSignature(message); if (!r.equals(sig[0])) { fail("r component wrong.", r, sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong.", s, sig[1]); } dsa.init(false, pair.getPublic()); if (!dsa.verifySignature(message, sig[0], sig[1])) { fail("verification fails"); } dsa2Test1(); dsa2Test2(); dsa2Test3(); dsa2Test4(); testDSAsha3(224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); } private void testDSAsha3(int size, BigInteger s) { DSAParameters dsaParams = new DSAParameters( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeyParameters priKey = new DSAPrivateKeyParameters(x, dsaParams); SecureRandom k = new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))), new FixedSecureRandom.Data(Hex.decode("01020304")) }); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); DSADigestSigner dsa = new DSADigestSigner(new DSASigner(), new SHA3Digest(size)); dsa.init(true, new ParametersWithRandom(priKey, k)); dsa.update(M, 0, M.length); byte[] encSig = dsa.generateSignature(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature DSAPublicKeyParameters pubKey = new DSAPublicKeyParameters(y, dsaParams); dsa.init(false, pubKey); dsa.update(M, 0, M.length); if (!dsa.verifySignature(encSig)) { fail("signature fails"); } } private void dsa2Test1() { byte[] seed = Hex.decode("ED8BEE8D1CB89229D2903CBF0E51EE7377F48698"); DSAParametersGenerator pGen = new DSAParametersGenerator(); pGen.init(new DSAParameterGenerationParameters(1024, 160, 80, new DSATestSecureRandom(seed))); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pv = params.getValidationParameters(); if (pv.getCounter() != 5) { fail("counter incorrect"); } if (!Arrays.areEqual(seed, pv.getSeed())) { fail("seed incorrect"); } if (!params.getQ().equals(new BigInteger("E950511EAB424B9A19A2AEB4E159B7844C589C4F", 16))) { fail("Q incorrect"); } if (!params.getP().equals(new BigInteger( "E0A67598CD1B763B" + "C98C8ABB333E5DDA0CD3AA0E5E1FB5BA8A7B4EABC10BA338" + "FAE06DD4B90FDA70D7CF0CB0C638BE3341BEC0AF8A7330A3" + "307DED2299A0EE606DF035177A239C34A912C202AA5F83B9" + "C4A7CF0235B5316BFC6EFB9A248411258B30B839AF172440" + "F32563056CB67A861158DDD90E6A894C72A5BBEF9E286C6B", 16))) { fail("P incorrect"); } if (!params.getG().equals(new BigInteger( "D29D5121B0423C27" + "69AB21843E5A3240FF19CACC792264E3BB6BE4F78EDD1B15" + "C4DFF7F1D905431F0AB16790E1F773B5CE01C804E509066A" + "9919F5195F4ABC58189FD9FF987389CB5BEDF21B4DAB4F8B" + "76A055FFE2770988FE2EC2DE11AD92219F0B351869AC24DA" + "3D7BA87011A701CE8EE7BFE49486ED4527B7186CA4610A75", 16))) { fail("G incorrect"); } DSAKeyPairGenerator kpGen = new DSAKeyPairGenerator(); kpGen.init(new DSAKeyGenerationParameters(new TestRandomBigInteger("D0EC4E50BB290A42E9E355C73D8809345DE2E139", 16), params)); AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)kp.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)kp.getPrivate(); if (!pub.getY().equals(new BigInteger( "25282217F5730501" + "DD8DBA3EDFCF349AAFFEC20921128D70FAC44110332201BB" + "A3F10986140CBB97C726938060473C8EC97B4731DB004293" + "B5E730363609DF9780F8D883D8C4D41DED6A2F1E1BBBDC97" + "9E1B9D6D3C940301F4E978D65B19041FCF1E8B518F5C0576" + "C770FE5A7A485D8329EE2914A2DE1B5DA4A6128CEAB70F79", 16))) { fail("Y value incorrect"); } if (!priv.getX().equals( new BigInteger("D0EC4E50BB290A42E9E355C73D8809345DE2E139", 16))) { fail("X value incorrect"); } DSASigner signer = new DSASigner(); signer.init(true, new ParametersWithRandom(kp.getPrivate(), new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger("349C55648DCF992F3F33E8026CFAC87C1D2BA075"), new FixedSecureRandom.Data(Hex.decode("01020304")) }))); byte[] msg = Hex.decode("A9993E364706816ABA3E25717850C26C9CD0D89D"); BigInteger[] sig = signer.generateSignature(msg); if (!sig[0].equals(new BigInteger("636155AC9A4633B4665D179F9E4117DF68601F34", 16))) { fail("R value incorrect"); } if (!sig[1].equals(new BigInteger("6C540B02D9D4852F89DF8CFC99963204F4347704", 16))) { fail("S value incorrect"); } signer.init(false, kp.getPublic()); if (!signer.verifySignature(msg, sig[0], sig[1])) { fail("signature not verified"); } } private void dsa2Test2() { byte[] seed = Hex.decode("5AFCC1EFFC079A9CCA6ECA86D6E3CC3B18642D9BE1CC6207C84002A9"); DSAParametersGenerator pGen = new DSAParametersGenerator(new SHA224Digest()); pGen.init(new DSAParameterGenerationParameters(2048, 224, 80, new DSATestSecureRandom(seed))); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pv = params.getValidationParameters(); if (pv.getCounter() != 21) { fail("counter incorrect"); } if (!Arrays.areEqual(seed, pv.getSeed())) { fail("seed incorrect"); } if (!params.getQ().equals(new BigInteger("90EAF4D1AF0708B1B612FF35E0A2997EB9E9D263C9CE659528945C0D", 16))) { fail("Q incorrect"); } if (!params.getP().equals(new BigInteger( "C196BA05AC29E1F9C3C72D56DFFC6154" + "A033F1477AC88EC37F09BE6C5BB95F51C296DD20D1A28A06" + "7CCC4D4316A4BD1DCA55ED1066D438C35AEBAABF57E7DAE4" + "28782A95ECA1C143DB701FD48533A3C18F0FE23557EA7AE6" + "19ECACC7E0B51652A8776D02A425567DED36EABD90CA33A1" + "E8D988F0BBB92D02D1D20290113BB562CE1FC856EEB7CDD9" + "2D33EEA6F410859B179E7E789A8F75F645FAE2E136D252BF" + "FAFF89528945C1ABE705A38DBC2D364AADE99BE0D0AAD82E" + "5320121496DC65B3930E38047294FF877831A16D5228418D" + "E8AB275D7D75651CEFED65F78AFC3EA7FE4D79B35F62A040" + "2A1117599ADAC7B269A59F353CF450E6982D3B1702D9CA83", 16))) { fail("P incorrect"); } if (!params.getG().equals(new BigInteger( "A59A749A11242C58C894E9E5A91804E8"+ "FA0AC64B56288F8D47D51B1EDC4D65444FECA0111D78F35F"+ "C9FDD4CB1F1B79A3BA9CBEE83A3F811012503C8117F98E50"+ "48B089E387AF6949BF8784EBD9EF45876F2E6A5A495BE64B"+ "6E770409494B7FEE1DBB1E4B2BC2A53D4F893D418B715959"+ "2E4FFFDF6969E91D770DAEBD0B5CB14C00AD68EC7DC1E574"+ "5EA55C706C4A1C5C88964E34D09DEB753AD418C1AD0F4FDF"+ "D049A955E5D78491C0B7A2F1575A008CCD727AB376DB6E69"+ "5515B05BD412F5B8C2F4C77EE10DA48ABD53F5DD498927EE"+ "7B692BBBCDA2FB23A516C5B4533D73980B2A3B60E384ED20"+ "0AE21B40D273651AD6060C13D97FD69AA13C5611A51B9085", 16))) { fail("G incorrect"); } DSAKeyPairGenerator kpGen = new DSAKeyPairGenerator(); kpGen.init(new DSAKeyGenerationParameters(new TestRandomData(Hex.decode("00D0F09ED3E2568F6CADF9224117DA2AEC5A4300E009DE1366023E17")), params)); AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)kp.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)kp.getPrivate(); if (!pub.getY().equals(new BigInteger( "70035C9A3B225B258F16741F3941FBF0" + "6F3D056CD7BD864604CBB5EE9DD85304EE8E8E4ABD5E9032" + "11DDF25CE149075510ACE166970AFDC7DF552B7244F342FA" + "02F7A621405B754909D757F97290E1FE5036E904CF593446" + "0C046D95659821E1597ED9F2B1F0E20863A6BBD0CE74DACB" + "A5D8C68A90B29C2157CDEDB82EC12B81EE3068F9BF5F7F34" + "6ECA41ED174CCCD7D154FA4F42F80FFE1BF46AE9D8125DEB" + "5B4BA08A72BDD86596DBEDDC9550FDD650C58F5AE5133509" + "A702F79A31ECB490F7A3C5581631F7C5BE4FF7F9E9F27FA3" + "90E47347AD1183509FED6FCF198BA9A71AB3335B4F38BE8D" + "15496A00B6DC2263E20A5F6B662320A3A1EC033AA61E3B68", 16))) { fail("Y value incorrect"); } if (!priv.getX().equals( new BigInteger("00D0F09ED3E2568F6CADF9224117DA2AEC5A4300E009DE1366023E17", 16))) { fail("X value incorrect"); } DSASigner signer = new DSASigner(); signer.init(true, new ParametersWithRandom(kp.getPrivate(), new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger(Hex.decode("735959CC4463B8B440E407EECA8A473BF6A6D1FE657546F67D401F05")), new FixedSecureRandom.Data(Hex.decode("01020304")) }))); byte[] msg = Hex.decode("23097D223405D8228642A477BDA255B32AADBCE4BDA0B3F7E36C9DA7"); BigInteger[] sig = signer.generateSignature(msg); if (!sig[0].equals(new BigInteger("4400138D05F9639CAF54A583CAAF25D2B76D0C3EAD752CE17DBC85FE", 16))) { fail("R value incorrect"); } if (!sig[1].equals(new BigInteger("874D4F12CB13B61732D398445698CFA9D92381D938AA57EE2C9327B3", 16))) { fail("S value incorrect"); } signer.init(false, kp.getPublic()); if (!signer.verifySignature(msg, sig[0], sig[1])) { fail("signature not verified"); } } private void dsa2Test3() { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); DSAParametersGenerator pGen = new DSAParametersGenerator(new SHA256Digest()); pGen.init(new DSAParameterGenerationParameters(2048, 256, 80, new DSATestSecureRandom(seed))); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pv = params.getValidationParameters(); if (pv.getCounter() != 12) { fail("counter incorrect"); } if (!Arrays.areEqual(seed, pv.getSeed())) { fail("seed incorrect"); } if (!params.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!params.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!params.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } DSAKeyPairGenerator kpGen = new DSAKeyPairGenerator(); kpGen.init(new DSAKeyGenerationParameters(new TestRandomData(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), params)); AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)kp.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)kp.getPrivate(); if (!pub.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!priv.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } DSASigner signer = new DSASigner(); signer.init(true, new ParametersWithRandom(kp.getPrivate(), new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C")), new FixedSecureRandom.Data(Hex.decode("01020304")) }))); byte[] msg = Hex.decode("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"); BigInteger[] sig = signer.generateSignature(msg); if (!sig[0].equals(new BigInteger("315C875DCD4850E948B8AC42824E9483A32D5BA5ABE0681B9B9448D444F2BE3C", 16))) { fail("R value incorrect"); } if (!sig[1].equals(new BigInteger("89718D12E54A8D9ED066E4A55F7ED5A2229CD23B9A3CEE78F83ED6AA61F6BCB9", 16))) { fail("S value incorrect"); } signer.init(false, kp.getPublic()); if (!signer.verifySignature(msg, sig[0], sig[1])) { fail("signature not verified"); } } private void dsa2Test4() { byte[] seed = Hex.decode("193AFCA7C1E77B3C1ECC618C81322E47B8B8B997C9C83515C59CC446C2D9BD47"); DSAParametersGenerator pGen = new DSAParametersGenerator(new SHA256Digest()); pGen.init(new DSAParameterGenerationParameters(3072, 256, 80, new DSATestSecureRandom(seed))); DSAParameters params = pGen.generateParameters(); DSAValidationParameters pv = params.getValidationParameters(); if (pv.getCounter() != 20) { fail("counter incorrect"); } if (!Arrays.areEqual(seed, pv.getSeed())) { fail("seed incorrect"); } if (!params.getQ().equals(new BigInteger("CFA0478A54717B08CE64805B76E5B14249A77A4838469DF7F7DC987EFCCFB11D", 16))) { fail("Q incorrect"); } if (!params.getP().equals(new BigInteger( "90066455B5CFC38F9CAA4A48B4281F292C260FEEF01FD610" + "37E56258A7795A1C7AD46076982CE6BB956936C6AB4DCFE0" + "5E6784586940CA544B9B2140E1EB523F009D20A7E7880E4E" + "5BFA690F1B9004A27811CD9904AF70420EEFD6EA11EF7DA1" + "29F58835FF56B89FAA637BC9AC2EFAAB903402229F491D8D" + "3485261CD068699B6BA58A1DDBBEF6DB51E8FE34E8A78E54" + "2D7BA351C21EA8D8F1D29F5D5D15939487E27F4416B0CA63" + "2C59EFD1B1EB66511A5A0FBF615B766C5862D0BD8A3FE7A0" + "E0DA0FB2FE1FCB19E8F9996A8EA0FCCDE538175238FC8B0E" + "E6F29AF7F642773EBE8CD5402415A01451A840476B2FCEB0" + "E388D30D4B376C37FE401C2A2C2F941DAD179C540C1C8CE0" + "30D460C4D983BE9AB0B20F69144C1AE13F9383EA1C08504F" + "B0BF321503EFE43488310DD8DC77EC5B8349B8BFE97C2C56" + "0EA878DE87C11E3D597F1FEA742D73EEC7F37BE43949EF1A" + "0D15C3F3E3FC0A8335617055AC91328EC22B50FC15B941D3" + "D1624CD88BC25F3E941FDDC6200689581BFEC416B4B2CB73", 16))) { fail("P incorrect"); } if (!params.getG().equals(new BigInteger( "5E5CBA992E0A680D885EB903AEA78E4A45A469103D448EDE" + "3B7ACCC54D521E37F84A4BDD5B06B0970CC2D2BBB715F7B8" + "2846F9A0C393914C792E6A923E2117AB805276A975AADB52" + "61D91673EA9AAFFEECBFA6183DFCB5D3B7332AA19275AFA1" + "F8EC0B60FB6F66CC23AE4870791D5982AAD1AA9485FD8F4A" + "60126FEB2CF05DB8A7F0F09B3397F3937F2E90B9E5B9C9B6" + "EFEF642BC48351C46FB171B9BFA9EF17A961CE96C7E7A7CC" + "3D3D03DFAD1078BA21DA425198F07D2481622BCE45969D9C" + "4D6063D72AB7A0F08B2F49A7CC6AF335E08C4720E31476B6" + "7299E231F8BD90B39AC3AE3BE0C6B6CACEF8289A2E2873D5" + "8E51E029CAFBD55E6841489AB66B5B4B9BA6E2F784660896" + "AFF387D92844CCB8B69475496DE19DA2E58259B090489AC8" + "E62363CDF82CFD8EF2A427ABCD65750B506F56DDE3B98856" + "7A88126B914D7828E2B63A6D7ED0747EC59E0E0A23CE7D8A" + "74C1D2C2A7AFB6A29799620F00E11C33787F7DED3B30E1A2" + "2D09F1FBDA1ABBBFBF25CAE05A13F812E34563F99410E73B", 16))) { fail("G incorrect"); } DSAKeyPairGenerator kpGen = new DSAKeyPairGenerator(); kpGen.init(new DSAKeyGenerationParameters(new TestRandomData(Hex.decode("3ABC1587297CE7B9EA1AD6651CF2BC4D7F92ED25CABC8553F567D1B40EBB8764")), params)); AsymmetricCipherKeyPair kp = kpGen.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)kp.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)kp.getPrivate(); if (!pub.getY().equals(new BigInteger( "8B891C8692D3DE875879390F2698B26FBECCA6B075535DCE" + "6B0C862577F9FA0DEF6074E7A7624121224A595896ABD4CD" + "A56B2CEFB942E025D2A4282FFAA98A48CDB47E1A6FCB5CFB" + "393EF35AF9DF913102BB303C2B5C36C3F8FC04ED7B8B69FE" + "FE0CF3E1FC05CFA713B3435B2656E913BA8874AEA9F93600" + "6AEB448BCD005D18EC3562A33D04CF25C8D3D69844343442" + "FA3DB7DE618C5E2DA064573E61E6D5581BFB694A23AC87FD" + "5B52D62E954E1376DB8DDB524FFC0D469DF978792EE44173" + "8E5DB05A7DC43E94C11A2E7A4FBE383071FA36D2A7EC8A93" + "88FE1C4F79888A99D3B6105697C2556B79BB4D7E781CEBB3" + "D4866AD825A5E830846072289FDBC941FA679CA82F5F78B7" + "461B2404DB883D215F4E0676CF5493950AC5591697BFEA8D" + "1EE6EC016B89BA51CAFB5F9C84C989FA117375E94578F28B" + "E0B34CE0545DA46266FD77F62D8F2CEE92AB77012AFEBC11" + "008985A821CD2D978C7E6FE7499D1AAF8DE632C21BB48CA5" + "CBF9F31098FD3FD3854C49A65D9201744AACE540354974F9", 16))) { fail("Y value incorrect"); } if (!priv.getX().equals( new BigInteger("3ABC1587297CE7B9EA1AD6651CF2BC4D7F92ED25CABC8553F567D1B40EBB8764", 16))) { fail("X value incorrect"); } DSASigner signer = new DSASigner(); signer.init(true, new ParametersWithRandom(kp.getPrivate(), new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger("A6902C1E6E3943C5628061588A8B007BCCEA91DBF12915483F04B24AB0678BEE"), new FixedSecureRandom.Data(Hex.decode("01020304")) }))); byte[] msg = Hex.decode("BA7816BF8F01CFEA414140DE5DAE2223B00361A396177A9CB410FF61F20015AD"); BigInteger[] sig = signer.generateSignature(msg); if (!sig[0].equals(new BigInteger("5F184E645A38BE8FB4A6871B6503A9D12924C7ABE04B71410066C2ECA6E3BE3E", 16))) { fail("R value incorrect"); } if (!sig[1].equals(new BigInteger("91EB0C7BA3D4B9B60B825C3D9F2CADA8A2C9D7723267B033CBCDCF8803DB9C18", 16))) { fail("S value incorrect"); } signer.init(false, kp.getPublic()); if (!signer.verifySignature(msg, sig[0], sig[1])) { fail("signature not verified"); } } public static void main( String[] args) { runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4758_1
crossvul-java_data_good_4758_0
package org.bouncycastle.crypto.signers; import java.math.BigInteger; import java.security.SecureRandom; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DSA; import org.bouncycastle.crypto.params.DSAKeyParameters; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; /** * The Digital Signature Algorithm - as described in "Handbook of Applied * Cryptography", pages 452 - 453. */ public class DSASigner implements DSA { private final DSAKCalculator kCalculator; private DSAKeyParameters key; private SecureRandom random; /** * Default configuration, random K values. */ public DSASigner() { this.kCalculator = new RandomDSAKCalculator(); } /** * Configuration with an alternate, possibly deterministic calculator of K. * * @param kCalculator a K value calculator. */ public DSASigner(DSAKCalculator kCalculator) { this.kCalculator = kCalculator; } public void init( boolean forSigning, CipherParameters param) { SecureRandom providedRandom = null; if (forSigning) { if (param instanceof ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; this.key = (DSAPrivateKeyParameters)rParam.getParameters(); providedRandom = rParam.getRandom(); } else { this.key = (DSAPrivateKeyParameters)param; } } else { this.key = (DSAPublicKeyParameters)param; } this.random = initSecureRandom(forSigning && !kCalculator.isDeterministic(), providedRandom); } /** * generate a signature for the given message using the key we were * initialised with. For conventional DSA the message should be a SHA-1 * hash of the message of interest. * * @param message the message that will be verified later. */ public BigInteger[] generateSignature( byte[] message) { DSAParameters params = key.getParameters(); BigInteger q = params.getQ(); BigInteger m = calculateE(q, message); BigInteger x = ((DSAPrivateKeyParameters)key).getX(); if (kCalculator.isDeterministic()) { kCalculator.init(q, x, message); } else { kCalculator.init(q, random); } BigInteger k = kCalculator.nextK(); // the randomizer is to conceal timing information related to k and x. BigInteger r = params.getG().modPow(k.add(getRandomizer(q, random)), params.getP()).mod(q); k = k.modInverse(q).multiply(m.add(x.multiply(r))); BigInteger s = k.mod(q); return new BigInteger[]{ r, s }; } /** * return true if the value r and s represent a DSA signature for * the passed in message for standard DSA the message should be a * SHA-1 hash of the real message to be verified. */ public boolean verifySignature( byte[] message, BigInteger r, BigInteger s) { DSAParameters params = key.getParameters(); BigInteger q = params.getQ(); BigInteger m = calculateE(q, message); BigInteger zero = BigInteger.valueOf(0); if (zero.compareTo(r) >= 0 || q.compareTo(r) <= 0) { return false; } if (zero.compareTo(s) >= 0 || q.compareTo(s) <= 0) { return false; } BigInteger w = s.modInverse(q); BigInteger u1 = m.multiply(w).mod(q); BigInteger u2 = r.multiply(w).mod(q); BigInteger p = params.getP(); u1 = params.getG().modPow(u1, p); u2 = ((DSAPublicKeyParameters)key).getY().modPow(u2, p); BigInteger v = u1.multiply(u2).mod(p).mod(q); return v.equals(r); } private BigInteger calculateE(BigInteger n, byte[] message) { if (n.bitLength() >= message.length * 8) { return new BigInteger(1, message); } else { byte[] trunc = new byte[n.bitLength() / 8]; System.arraycopy(message, 0, trunc, 0, trunc.length); return new BigInteger(1, trunc); } } protected SecureRandom initSecureRandom(boolean needed, SecureRandom provided) { return !needed ? null : (provided != null) ? provided : new SecureRandom(); } private BigInteger getRandomizer(BigInteger q, SecureRandom provided) { // Calculate a random multiple of q to add to k. Note that g^q = 1 (mod p), so adding multiple of q to k does not change r. int randomBits = 7; return new BigInteger(randomBits, provided != null ? provided : new SecureRandom()).add(BigInteger.valueOf(128)).multiply(q); } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4758_0
crossvul-java_data_bad_4758_2
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAParameterSpec; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 }); // DSA modified signatures, courtesy of the Google security team static final DSAPrivateKeySpec PRIVATE_KEY = new DSAPrivateKeySpec( // x new BigInteger( "15382583218386677486843706921635237927801862255437148328980464126979"), // p new BigInteger( "181118486631420055711787706248812146965913392568235070235446058914" + "1170708161715231951918020125044061516370042605439640379530343556" + "4101919053459832890139496933938670005799610981765220283775567361" + "4836626483403394052203488713085936276470766894079318754834062443" + "1033792580942743268186462355159813630244169054658542719322425431" + "4088256212718983105131138772434658820375111735710449331518776858" + "7867938758654181244292694091187568128410190746310049564097068770" + "8161261634790060655580211122402292101772553741704724263582994973" + "9109274666495826205002104010355456981211025738812433088757102520" + "562459649777989718122219159982614304359"), // q new BigInteger( "19689526866605154788513693571065914024068069442724893395618704484701"), // g new BigInteger( "2859278237642201956931085611015389087970918161297522023542900348" + "0877180630984239764282523693409675060100542360520959501692726128" + "3149190229583566074777557293475747419473934711587072321756053067" + "2532404847508798651915566434553729839971841903983916294692452760" + "2490198571084091890169933809199002313226100830607842692992570749" + "0504363602970812128803790973955960534785317485341020833424202774" + "0275688698461842637641566056165699733710043802697192696426360843" + "1736206792141319514001488556117408586108219135730880594044593648" + "9237302749293603778933701187571075920849848690861126195402696457" + "4111219599568903257472567764789616958430")); static final DSAPublicKeySpec PUBLIC_KEY = new DSAPublicKeySpec( new BigInteger( "3846308446317351758462473207111709291533523711306097971550086650" + "2577333637930103311673872185522385807498738696446063139653693222" + "3528823234976869516765207838304932337200968476150071617737755913" + "3181601169463467065599372409821150709457431511200322947508290005" + "1780020974429072640276810306302799924668893998032630777409440831" + "4314588994475223696460940116068336991199969153649625334724122468" + "7497038281983541563359385775312520539189474547346202842754393945" + "8755803223951078082197762886933401284142487322057236814878262166" + "5072306622943221607031324846468109901964841479558565694763440972" + "5447389416166053148132419345627682740529"), PRIVATE_KEY.getP(), PRIVATE_KEY.getQ(), PRIVATE_KEY.getG()); // The following test vectors check for signature malleability and bugs. That means the test // vectors are derived from a valid signature by modifying the ASN encoding. A correct // implementation of DSA should only accept correct DER encoding and properly handle the others. // Allowing alternative BER encodings is in many cases benign. An example where this kind of // signature malleability was a problem: https://en.bitcoin.it/wiki/Transaction_Malleability static final String[] MODIFIED_SIGNATURES = { "303e02811c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f0282001c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021d001e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd02811d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd0282001d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021e0000ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "30813d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "3082003d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9ef4" + "1dd424a4e1c8f16967cf3365813fe87862360000", "3040021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca8021d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3040100", "303e021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca802811d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3" }; private void testModified() throws Exception { KeyFactory kFact = KeyFactory.getInstance("DSA", "BC"); PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); Signature sig = Signature.getInstance("DSA", "BC"); for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) { sig.initVerify(pubKey); sig.update(Strings.toByteArray("Hello")); boolean failed; try { failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); } catch (SignatureException e) { failed = true; } isTrue("sig verified when shouldn't", failed); } } private void testCompat() throws Exception { if (Security.getProvider("SUN") == null) { return; } Signature s = Signature.getInstance("DSA", "SUN"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); // // sign SUN - verify with BC // s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("SUN -> BC verification failed"); } // // sign BC - verify with SUN // s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("DSA", "SUN"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("BC -> SUN verification failed"); } // // key encoding test - BC decoding Sun keys // KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded()); DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded()); DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); // // key decoding test - SUN decoding BC keys // f = KeyFactory.getInstance("DSA", "SUN"); x509s = new X509EncodedKeySpec(k1.getEncoded()); vKey = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded()); sKey = f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); } private void testNullParameters() throws Exception { KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded()); DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s); DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s); isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null); isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode()); isTrue("not equal", key1.equals(key2)); isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded())); } private void testValidate() throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); KeyFactory f = KeyFactory.getInstance("DSA", "BC"); try { f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ())); fail("no exception"); } catch (Exception e) { isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage())); } } private void testNONEwithDSA() throws Exception { byte[] dummySha1 = Hex.decode("01020304050607080910111213141516"); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC"); kpGen.initialize(512); KeyPair kp = kpGen.generateKeyPair(); Signature sig = Signature.getInstance("NONEwithDSA", "BC"); sig.initSign(kp.getPrivate()); sig.update(dummySha1); byte[] sigBytes = sig.sign(); sig.initVerify(kp.getPublic()); sig.update(dummySha1); sig.verify(sigBytes); // reset test sig.update(dummySha1); if (!sig.verify(sigBytes)) { fail("NONEwithDSA failed to reset"); } // lightweight test DSAPublicKey key = (DSAPublicKey)kp.getPublic(); DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG()); DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params); DSASigner signer = new DSASigner(); ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes)); signer.init(false, keyParams); if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue())) { fail("NONEwithDSA not really NONE!"); } } private void checkPublic(DSAPublicKey k1, PublicKey vKey) { if (!k1.getY().equals(((DSAPublicKey)vKey).getY())) { fail("public number not decoded properly"); } if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG())) { fail("public generator not decoded properly"); } if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP())) { fail("public p value not decoded properly"); } if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ())) { fail("public q value not decoded properly"); } } private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey) { if (!k2.getX().equals(((DSAPrivateKey)sKey).getX())) { fail("private number not decoded properly"); } if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG())) { fail("private generator not decoded properly"); } if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP())) { fail("private p value not decoded properly"); } if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ())) { fail("private q value not decoded properly"); } } private Object serializeDeserialize(Object o) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutputStream oOut = new ObjectOutputStream(bOut); oOut.writeObject(o); oOut.close(); ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); return oIn.readObject(); } /** * X9.62 - 1998,<br> * J.3.2, Page 155, ECDSA over the field Fp<br> * an example with 239 bit prime */ private void testECDSA239bitPrime() throws Exception { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); sgr.initSign(sKey, k); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testNONEwithECDSA239bitPrime() throws Exception { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("NONEwithECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); byte[] message = "abc".getBytes(); byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d"); checkMessage(sgr, sKey, vKey, message, sig); message = "abcdefghijklmnopqrstuvwxyz".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c"); checkMessage(sgr, sKey, vKey, message, sig); message = "a very very long message gauranteed to cause an overflow".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a"); checkMessage(sgr, sKey, vKey, message, sig); } private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { X9ECParameters p = NISTNamedCurves.getByName("P-256"); KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC"); ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); ECCurve curve = p.getCurve(); ECParameterSpec spec = new ECParameterSpec( curve, p.getG(), // G p.getN()); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q spec); doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey); doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey); } private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeySpec priKey = new DSAPrivateKeySpec( x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); DSAPublicKeySpec pubKey = new DSAPublicKeySpec( y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC"); doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey); doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey); } private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig) throws InvalidKeyException, SignatureException { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); if (!Arrays.areEqual(sigBytes, sig)) { fail(new String(message) + " signature incorrect"); } sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail(new String(message) + " verification failed"); } } /** * X9.62 - 1998,<br> * J.2.1, Page 100, ECDSA over the field F2m<br> * an example with 191 bit binary field */ private void testECDSA239bitBinary() throws Exception { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid) throws Exception { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance(algorithm, "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr = Signature.getInstance(oid.getId(), "BC"); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC RIPEMD160 verification failed"); } } private void testGeneration() throws Exception { Signature s = Signature.getInstance("DSA", "BC"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // test exception // try { g.initialize(513, new SecureRandom()); fail("illegal parameter 513 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(510, new SecureRandom()); fail("illegal parameter 510 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(1025, new SecureRandom()); fail("illegal parameter 1025 check failed."); } catch (IllegalArgumentException e) { // expected } g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } // // key decoding test - serialisation test // DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey); checkPublic(k1, vKey); checkEquals(k1, vKey); DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey); checkPrivateKey(k2, sKey); checkEquals(k2, sKey); if (!(k2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } // // ECDSA Fp generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // PublicKey eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // Named curve parameter g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // // ECDSA F2m generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); if (!(eck2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } } private void checkEquals(Object o1, Object o2) { if (!o1.equals(o2)) { fail("comparison test failed"); } if (o1.hashCode() != o2.hashCode()) { fail("hashCode test failed"); } } private void testParameters() throws Exception { AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(512, random); AlgorithmParameters params = a.generateParameters(); byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } private void testDSA2Parameters() throws Exception { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(2048, new DSATestSecureRandom(seed)); AlgorithmParameters params = a.generateParameters(); DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!dsaP.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!dsaP.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); KeyPair p = g.generateKeyPair(); DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); if (!vKey.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!sKey.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } public void performTest() throws Exception { testCompat(); testNONEwithDSA(); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); testECDSA239bitPrime(); testNONEwithECDSA239bitPrime(); testECDSA239bitBinary(); testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160); testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1); testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16)); testGeneration(); testParameters(); testDSA2Parameters(); testNullParameters(); testValidate(); testModified(); } protected BigInteger[] derDecode( byte[] encoding) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(encoding); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence s = (ASN1Sequence)aIn.readObject(); BigInteger[] sig = new BigInteger[2]; sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } public String getName() { return "DSA/ECDSA"; } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4758_2
crossvul-java_data_bad_4762_4
404: Not Found
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4762_4
crossvul-java_data_bad_4762_3
package org.bouncycastle.jcajce.provider.asymmetric.rsa; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.InvalidParameterException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidParameterSpecException; import java.security.spec.MGF1ParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.OAEPParameterSpec; import javax.crypto.spec.PSource; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.crypto.AsymmetricBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.encodings.ISO9796d1Encoding; import org.bouncycastle.crypto.encodings.OAEPEncoding; import org.bouncycastle.crypto.encodings.PKCS1Encoding; import org.bouncycastle.crypto.engines.RSABlindedEngine; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.jcajce.provider.asymmetric.util.BaseCipherSpi; import org.bouncycastle.jcajce.provider.util.DigestFactory; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.util.Strings; public class CipherSpi extends BaseCipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private AsymmetricBlockCipher cipher; private AlgorithmParameterSpec paramSpec; private AlgorithmParameters engineParams; private boolean publicKeyOnly = false; private boolean privateKeyOnly = false; private ByteArrayOutputStream bOut = new ByteArrayOutputStream(); public CipherSpi( AsymmetricBlockCipher engine) { cipher = engine; } public CipherSpi( OAEPParameterSpec pSpec) { try { initFromSpec(pSpec); } catch (NoSuchPaddingException e) { throw new IllegalArgumentException(e.getMessage()); } } public CipherSpi( boolean publicKeyOnly, boolean privateKeyOnly, AsymmetricBlockCipher engine) { this.publicKeyOnly = publicKeyOnly; this.privateKeyOnly = privateKeyOnly; cipher = engine; } private void initFromSpec( OAEPParameterSpec pSpec) throws NoSuchPaddingException { MGF1ParameterSpec mgfParams = (MGF1ParameterSpec)pSpec.getMGFParameters(); Digest digest = DigestFactory.getDigest(mgfParams.getDigestAlgorithm()); if (digest == null) { throw new NoSuchPaddingException("no match on OAEP constructor for digest algorithm: "+ mgfParams.getDigestAlgorithm()); } cipher = new OAEPEncoding(new RSABlindedEngine(), digest, ((PSource.PSpecified)pSpec.getPSource()).getValue()); paramSpec = pSpec; } protected int engineGetBlockSize() { try { return cipher.getInputBlockSize(); } catch (NullPointerException e) { throw new IllegalStateException("RSA Cipher not initialised"); } } protected int engineGetKeySize( Key key) { if (key instanceof RSAPrivateKey) { RSAPrivateKey k = (RSAPrivateKey)key; return k.getModulus().bitLength(); } else if (key instanceof RSAPublicKey) { RSAPublicKey k = (RSAPublicKey)key; return k.getModulus().bitLength(); } throw new IllegalArgumentException("not an RSA key!"); } protected int engineGetOutputSize( int inputLen) { try { return cipher.getOutputBlockSize(); } catch (NullPointerException e) { throw new IllegalStateException("RSA Cipher not initialised"); } } protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (paramSpec != null) { try { engineParams = helper.createAlgorithmParameters("OAEP"); engineParams.init(paramSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } } return engineParams; } protected void engineSetMode( String mode) throws NoSuchAlgorithmException { String md = Strings.toUpperCase(mode); if (md.equals("NONE") || md.equals("ECB")) { return; } if (md.equals("1")) { privateKeyOnly = true; publicKeyOnly = false; return; } else if (md.equals("2")) { privateKeyOnly = false; publicKeyOnly = true; return; } throw new NoSuchAlgorithmException("can't support mode " + mode); } protected void engineSetPadding( String padding) throws NoSuchPaddingException { String pad = Strings.toUpperCase(padding); if (pad.equals("NOPADDING")) { cipher = new RSABlindedEngine(); } else if (pad.equals("PKCS1PADDING")) { cipher = new PKCS1Encoding(new RSABlindedEngine()); } else if (pad.equals("ISO9796-1PADDING")) { cipher = new ISO9796d1Encoding(new RSABlindedEngine()); } else if (pad.equals("OAEPWITHMD5ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("MD5", "MGF1", new MGF1ParameterSpec("MD5"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPPADDING")) { initFromSpec(OAEPParameterSpec.DEFAULT); } else if (pad.equals("OAEPWITHSHA1ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-1ANDMGF1PADDING")) { initFromSpec(OAEPParameterSpec.DEFAULT); } else if (pad.equals("OAEPWITHSHA224ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-224ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA-224", "MGF1", new MGF1ParameterSpec("SHA-224"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA256ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-256ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA384ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-384ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA384, PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA512ANDMGF1PADDING") || pad.equals("OAEPWITHSHA-512ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA512, PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA3-224ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA3-224", "MGF1", new MGF1ParameterSpec("SHA3-224"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA3-256ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA3-256", "MGF1", new MGF1ParameterSpec("SHA3-256"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA3-384ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA3-384", "MGF1", new MGF1ParameterSpec("SHA3-384"), PSource.PSpecified.DEFAULT)); } else if (pad.equals("OAEPWITHSHA3-512ANDMGF1PADDING")) { initFromSpec(new OAEPParameterSpec("SHA3-512", "MGF1", new MGF1ParameterSpec("SHA3-512"), PSource.PSpecified.DEFAULT)); } else { throw new NoSuchPaddingException(padding + " unavailable with RSA."); } } protected void engineInit( int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { CipherParameters param; if (params == null || params instanceof OAEPParameterSpec) { if (key instanceof RSAPublicKey) { if (privateKeyOnly && opmode == Cipher.ENCRYPT_MODE) { throw new InvalidKeyException( "mode 1 requires RSAPrivateKey"); } param = RSAUtil.generatePublicKeyParameter((RSAPublicKey)key); } else if (key instanceof RSAPrivateKey) { if (publicKeyOnly && opmode == Cipher.ENCRYPT_MODE) { throw new InvalidKeyException( "mode 2 requires RSAPublicKey"); } param = RSAUtil.generatePrivateKeyParameter((RSAPrivateKey)key); } else { throw new InvalidKeyException("unknown key type passed to RSA"); } if (params != null) { OAEPParameterSpec spec = (OAEPParameterSpec)params; paramSpec = params; if (!spec.getMGFAlgorithm().equalsIgnoreCase("MGF1") && !spec.getMGFAlgorithm().equals(PKCSObjectIdentifiers.id_mgf1.getId())) { throw new InvalidAlgorithmParameterException("unknown mask generation function specified"); } if (!(spec.getMGFParameters() instanceof MGF1ParameterSpec)) { throw new InvalidAlgorithmParameterException("unkown MGF parameters"); } Digest digest = DigestFactory.getDigest(spec.getDigestAlgorithm()); if (digest == null) { throw new InvalidAlgorithmParameterException("no match on digest algorithm: "+ spec.getDigestAlgorithm()); } MGF1ParameterSpec mgfParams = (MGF1ParameterSpec)spec.getMGFParameters(); Digest mgfDigest = DigestFactory.getDigest(mgfParams.getDigestAlgorithm()); if (mgfDigest == null) { throw new InvalidAlgorithmParameterException("no match on MGF digest algorithm: "+ mgfParams.getDigestAlgorithm()); } cipher = new OAEPEncoding(new RSABlindedEngine(), digest, mgfDigest, ((PSource.PSpecified)spec.getPSource()).getValue()); } } else { throw new InvalidAlgorithmParameterException("unknown parameter type: " + params.getClass().getName()); } if (!(cipher instanceof RSABlindedEngine)) { if (random != null) { param = new ParametersWithRandom(param, random); } else { param = new ParametersWithRandom(param, new SecureRandom()); } } bOut.reset(); switch (opmode) { case Cipher.ENCRYPT_MODE: case Cipher.WRAP_MODE: cipher.init(true, param); break; case Cipher.DECRYPT_MODE: case Cipher.UNWRAP_MODE: cipher.init(false, param); break; default: throw new InvalidParameterException("unknown opmode " + opmode + " passed to RSA"); } } protected void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(OAEPParameterSpec.class); } catch (InvalidParameterSpecException e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString(), e); } } engineParams = params; engineInit(opmode, key, paramSpec, random); } protected void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { // this shouldn't happen throw new InvalidKeyException("Eeeek! " + e.toString(), e); } } protected byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { bOut.write(input, inputOffset, inputLen); if (cipher instanceof RSABlindedEngine) { if (bOut.size() > cipher.getInputBlockSize() + 1) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } else { if (bOut.size() > cipher.getInputBlockSize()) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } return null; } protected int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { bOut.write(input, inputOffset, inputLen); if (cipher instanceof RSABlindedEngine) { if (bOut.size() > cipher.getInputBlockSize() + 1) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } else { if (bOut.size() > cipher.getInputBlockSize()) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } return 0; } protected byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (input != null) { bOut.write(input, inputOffset, inputLen); } if (cipher instanceof RSABlindedEngine) { if (bOut.size() > cipher.getInputBlockSize() + 1) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } else { if (bOut.size() > cipher.getInputBlockSize()) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } return getOutput(); } protected int engineDoFinal( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws IllegalBlockSizeException, BadPaddingException { if (input != null) { bOut.write(input, inputOffset, inputLen); } if (cipher instanceof RSABlindedEngine) { if (bOut.size() > cipher.getInputBlockSize() + 1) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } else { if (bOut.size() > cipher.getInputBlockSize()) { throw new ArrayIndexOutOfBoundsException("too much data for RSA block"); } } byte[] out = getOutput(); for (int i = 0; i != out.length; i++) { output[outputOffset + i] = out[i]; } return out.length; } private byte[] getOutput() throws BadPaddingException { try { byte[] bytes = bOut.toByteArray(); return cipher.processBlock(bytes, 0, bytes.length); } catch (final InvalidCipherTextException e) { throw new BadPaddingException("unable to decrypt block") { public synchronized Throwable getCause() { return e; } }; } finally { bOut.reset(); } } /** * classes that inherit from us. */ static public class NoPadding extends CipherSpi { public NoPadding() { super(new RSABlindedEngine()); } } static public class PKCS1v1_5Padding extends CipherSpi { public PKCS1v1_5Padding() { super(new PKCS1Encoding(new RSABlindedEngine())); } } static public class PKCS1v1_5Padding_PrivateOnly extends CipherSpi { public PKCS1v1_5Padding_PrivateOnly() { super(false, true, new PKCS1Encoding(new RSABlindedEngine())); } } static public class PKCS1v1_5Padding_PublicOnly extends CipherSpi { public PKCS1v1_5Padding_PublicOnly() { super(true, false, new PKCS1Encoding(new RSABlindedEngine())); } } static public class OAEPPadding extends CipherSpi { public OAEPPadding() { super(OAEPParameterSpec.DEFAULT); } } static public class ISO9796d1Padding extends CipherSpi { public ISO9796d1Padding() { super(new ISO9796d1Encoding(new RSABlindedEngine())); } } }
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4762_3
crossvul-java_data_good_4762_1
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.io.ByteArrayOutputStream; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.CipherSpi; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.ShortBufferException; import javax.crypto.interfaces.DHKey; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyEncoder; import org.bouncycastle.crypto.agreement.DHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.AESFastEngine; import org.bouncycastle.crypto.engines.DESedeEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.DHKeyPairGenerator; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHKeyGenerationParameters; import org.bouncycastle.crypto.params.DHKeyParameters; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.parsers.DHIESPublicKeyParser; import org.bouncycastle.jcajce.provider.asymmetric.util.DHUtil; import org.bouncycastle.jcajce.provider.asymmetric.util.IESUtil; import org.bouncycastle.jcajce.provider.util.BadBlockException; import org.bouncycastle.jcajce.util.BCJcaJceHelper; import org.bouncycastle.jcajce.util.JcaJceHelper; import org.bouncycastle.jce.interfaces.IESKey; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; public class IESCipher extends CipherSpi { private final JcaJceHelper helper = new BCJcaJceHelper(); private final int ivLength; private IESEngine engine; private int state = -1; private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private AlgorithmParameters engineParam = null; private IESParameterSpec engineSpec = null; private AsymmetricKeyParameter key; private SecureRandom random; private boolean dhaesMode = false; private AsymmetricKeyParameter otherKeyParameter = null; public IESCipher(IESEngine engine) { this.engine = engine; this.ivLength = 0; } public IESCipher(IESEngine engine, int ivLength) { this.engine = engine; this.ivLength = ivLength; } public int engineGetBlockSize() { if (engine.getCipher() != null) { return engine.getCipher().getBlockSize(); } else { return 0; } } public int engineGetKeySize(Key key) { if (key instanceof DHKey) { return ((DHKey)key).getParams().getP().bitLength(); } else { throw new IllegalArgumentException("not a DH key"); } } public byte[] engineGetIV() { if (engineSpec != null) { return engineSpec.getNonce(); } return null; } public AlgorithmParameters engineGetParameters() { if (engineParam == null && engineSpec != null) { try { engineParam = helper.createAlgorithmParameters("IES"); engineParam.init(engineSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } return engineParam; } public void engineSetMode(String mode) throws NoSuchAlgorithmException { String modeName = Strings.toUpperCase(mode); if (modeName.equals("NONE")) { dhaesMode = false; } else if (modeName.equals("DHAES")) { dhaesMode = true; } else { throw new IllegalArgumentException("can't support mode " + mode); } } public int engineGetOutputSize(int inputLen) { int len1, len2, len3; if (key == null) { throw new IllegalStateException("cipher not initialised"); } len1 = engine.getMac().getMacSize(); if (otherKeyParameter == null) { len2 = 1 + 2 * (((DHKeyParameters)key).getParameters().getP().bitLength() + 7) / 8; } else { len2 = 0; } if (engine.getCipher() == null) { len3 = inputLen; } else if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen); } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { len3 = engine.getCipher().getOutputSize(inputLen - len1 - len2); } else { throw new IllegalStateException("cipher not initialised"); } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { return buffer.size() + len1 + len2 + len3; } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { return buffer.size() - len1 - len2 + len3; } else { throw new IllegalStateException("IESCipher not initialised"); } } public void engineSetPadding(String padding) throws NoSuchPaddingException { String paddingName = Strings.toUpperCase(padding); // TDOD: make this meaningful... if (paddingName.equals("NOPADDING")) { } else if (paddingName.equals("PKCS5PADDING") || paddingName.equals("PKCS7PADDING")) { } else { throw new NoSuchPaddingException("padding not available with IESCipher"); } } // Initialisation methods public void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(IESParameterSpec.class); } catch (Exception e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString()); } } engineParam = params; engineInit(opmode, key, paramSpec, random); } public void engineInit( int opmode, Key key, AlgorithmParameterSpec engineSpec, SecureRandom random) throws InvalidAlgorithmParameterException, InvalidKeyException { // Use default parameters (including cipher key size) if none are specified if (engineSpec == null) { byte[] nonce = null; if (ivLength != 0 && opmode == Cipher.ENCRYPT_MODE) { nonce = new byte[ivLength]; random.nextBytes(nonce); } this.engineSpec = IESUtil.guessParameterSpec(engine.getCipher(), nonce); } else if (engineSpec instanceof IESParameterSpec) { this.engineSpec = (IESParameterSpec)engineSpec; } else { throw new InvalidAlgorithmParameterException("must be passed IES parameters"); } byte[] nonce = this.engineSpec.getNonce(); if (ivLength != 0 && (nonce == null || nonce.length != ivLength)) { throw new InvalidAlgorithmParameterException("NONCE in IES Parameters needs to be " + ivLength + " bytes long"); } // Parse the recipient's key if (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE) { if (key instanceof DHPublicKey) { this.key = DHUtil.generatePublicKeyParameter((PublicKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.key = DHUtil.generatePublicKeyParameter(ieKey.getPublic()); this.otherKeyParameter = DHUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's public DH key for encryption"); } } else if (opmode == Cipher.DECRYPT_MODE || opmode == Cipher.UNWRAP_MODE) { if (key instanceof DHPrivateKey) { this.key = DHUtil.generatePrivateKeyParameter((PrivateKey)key); } else if (key instanceof IESKey) { IESKey ieKey = (IESKey)key; this.otherKeyParameter = DHUtil.generatePublicKeyParameter(ieKey.getPublic()); this.key = DHUtil.generatePrivateKeyParameter(ieKey.getPrivate()); } else { throw new InvalidKeyException("must be passed recipient's private DH key for decryption"); } } else { throw new InvalidKeyException("must be passed EC key"); } this.random = random; this.state = opmode; buffer.reset(); } public void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("cannot handle supplied parameter spec: " + e.getMessage()); } } // Update methods - buffer the input public byte[] engineUpdate( byte[] input, int inputOffset, int inputLen) { buffer.write(input, inputOffset, inputLen); return null; } public int engineUpdate( byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) { buffer.write(input, inputOffset, inputLen); return 0; } // Finalisation methods public byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } byte[] in = buffer.toByteArray(); buffer.reset(); // Convert parameters for use in IESEngine CipherParameters params = new IESWithCipherParameters(engineSpec.getDerivationV(), engineSpec.getEncodingV(), engineSpec.getMacKeySize(), engineSpec.getCipherKeySize()); if (engineSpec.getNonce() != null) { params = new ParametersWithIV(params, engineSpec.getNonce()); } DHParameters dhParams = ((DHKeyParameters)key).getParameters(); byte[] V; if (otherKeyParameter != null) { try { if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { engine.init(true, otherKeyParameter, key, params); } else { engine.init(false, key, otherKeyParameter, params); } return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadBlockException("unable to process block", e); } } if (state == Cipher.ENCRYPT_MODE || state == Cipher.WRAP_MODE) { // Generate the ephemeral key pair DHKeyPairGenerator gen = new DHKeyPairGenerator(); gen.init(new DHKeyGenerationParameters(random, dhParams)); EphemeralKeyPairGenerator kGen = new EphemeralKeyPairGenerator(gen, new KeyEncoder() { public byte[] getEncoded(AsymmetricKeyParameter keyParameter) { byte[] Vloc = new byte[(((DHKeyParameters)keyParameter).getParameters().getP().bitLength() + 7) / 8]; byte[] Vtmp = BigIntegers.asUnsignedByteArray(((DHPublicKeyParameters)keyParameter).getY()); if (Vtmp.length > Vloc.length) { throw new IllegalArgumentException("Senders's public key longer than expected."); } else { System.arraycopy(Vtmp, 0, Vloc, Vloc.length - Vtmp.length, Vtmp.length); } return Vloc; } }); // Encrypt the buffer try { engine.init(key, params, kGen); return engine.processBlock(in, 0, in.length); } catch (Exception e) { throw new BadBlockException("unable to process block", e); } } else if (state == Cipher.DECRYPT_MODE || state == Cipher.UNWRAP_MODE) { // Decrypt the buffer try { engine.init(key, params, new DHIESPublicKeyParser(((DHKeyParameters)key).getParameters())); return engine.processBlock(in, 0, in.length); } catch (InvalidCipherTextException e) { throw new BadBlockException("unable to process block", e); } } else { throw new IllegalStateException("IESCipher not initialised"); } } public int engineDoFinal( byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { byte[] buf = engineDoFinal(input, inputOffset, inputLength); System.arraycopy(buf, 0, output, outputOffset, buf.length); return buf.length; } /** * Classes that inherit from us */ static public class IES extends IESCipher { public IES() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()))); } } static public class IESwithDESedeCBC extends IESCipher { public IESwithDESedeCBC() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new CBCBlockCipher(new DESedeEngine()))), 8); } } static public class IESwithAESCBC extends IESCipher { public IESwithAESCBC() { super(new IESEngine(new DHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()))), 16); } } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4762_1
crossvul-java_data_bad_4762_6
package org.bouncycastle.jce.provider.test; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.SecureRandom; import java.security.Security; import java.security.spec.ECGenParameterSpec; import javax.crypto.Cipher; import javax.crypto.SealedObject; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.crypto.engines.DESEngine; import org.bouncycastle.crypto.engines.IESEngine; import org.bouncycastle.crypto.generators.KDF2BytesGenerator; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher; import org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher; import org.bouncycastle.jce.interfaces.ECPrivateKey; import org.bouncycastle.jce.interfaces.ECPublicKey; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.IESParameterSpec; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; /** * Test for ECIES - Elliptic Curve Integrated Encryption Scheme */ public class ECIESTest extends SimpleTest { ECIESTest() { } public String getName() { return "ECIES"; } public void performTest() throws Exception { byte[] derivation = Hex.decode("202122232425262728292a2b2c2d2e2f"); byte[] encoding = Hex.decode("303132333435363738393a3b3c3d3e3f"); IESCipher c1 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIES(); IESCipher c2 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIES(); IESParameterSpec params = new IESParameterSpec(derivation,encoding,128); // Testing ECIES with default curve in streaming mode KeyPairGenerator g = KeyPairGenerator.getInstance("EC", "BC"); doTest("ECIES with default", g, "ECIES", params); // Testing ECIES with 192-bit curve in streaming mode g.initialize(192, new SecureRandom()); doTest("ECIES with 192-bit", g, "ECIES", params); // Testing ECIES with 256-bit curve in streaming mode g.initialize(256, new SecureRandom()); doTest("ECIES with 256-bit", g, "ECIES", params); c1 = new IESCipher(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new DESEngine()))); c2 = new IESCipher(new IESEngine(new ECDHBasicAgreement(), new KDF2BytesGenerator(new SHA1Digest()), new HMac(new SHA1Digest()), new PaddedBufferedBlockCipher(new DESEngine()))); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("0001020304050607")); // Testing ECIES with default curve using DES g = KeyPairGenerator.getInstance("EC", "BC"); // Testing ECIES with 256-bit curve using DES-CBC g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithDESEDE-CBC", params); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("0001020304050607")); g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithDESEDE-CBC", params); try { params = new IESParameterSpec(derivation, encoding, 128, 128, new byte[10]); g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithDESEDE-CBC", params); fail("DESEDE no exception!"); } catch (InvalidAlgorithmParameterException e) { if (!e.getMessage().equals("NONCE in IES Parameters needs to be 8 bytes long")) { fail("DESEDE wrong message!"); } } c1 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIESwithAESCBC(); c2 = new org.bouncycastle.jcajce.provider.asymmetric.ec.IESCipher.ECIESwithAESCBC(); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("000102030405060708090a0b0c0d0e0f")); // Testing ECIES with 256-bit curve using AES-CBC g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithAES-CBC", params); params = new IESParameterSpec(derivation, encoding, 128, 128, Hex.decode("000102030405060708090a0b0c0d0e0f")); g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithAES-CBC", params); try { params = new IESParameterSpec(derivation, encoding, 128, 128, new byte[10]); g.initialize(256, new SecureRandom()); doTest("256-bit", g, "ECIESwithAES-CBC", params); fail("AES no exception!"); } catch (InvalidAlgorithmParameterException e) { if (!e.getMessage().equals("NONCE in IES Parameters needs to be 16 bytes long")) { fail("AES wrong message!"); } } KeyPair keyPair = g.generateKeyPair(); ECPublicKey pub = (ECPublicKey)keyPair.getPublic(); ECPrivateKey priv = (ECPrivateKey)keyPair.getPrivate(); Cipher c = Cipher.getInstance("ECIESwithAES-CBC", "BC"); try { c.init(Cipher.ENCRYPT_MODE, pub, new IESParameterSpec(derivation, encoding, 128, 128, null)); fail("no exception"); } catch (InvalidAlgorithmParameterException e) { isTrue("message ", "NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } try { c.init(Cipher.DECRYPT_MODE, priv); fail("no exception"); } catch (IllegalArgumentException e) { isTrue("message ", "cannot handle supplied parameter spec: NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } try { c.init(Cipher.DECRYPT_MODE, priv, new IESParameterSpec(derivation, encoding, 128, 128, null)); fail("no exception"); } catch (InvalidAlgorithmParameterException e) { isTrue("message ", "NONCE in IES Parameters needs to be 16 bytes long".equals(e.getMessage())); } sealedObjectTest(); } private void sealedObjectTest() throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECIES"); kpg.initialize(new ECGenParameterSpec("secp256r1")); KeyPair keyPair = kpg.generateKeyPair(); Cipher cipher = Cipher.getInstance("ECIES"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); String toEncrypt = "Hello"; // Check that cipher works ok cipher.doFinal(toEncrypt.getBytes()); // Using a SealedObject to encrypt the same string fails with a NullPointerException SealedObject sealedObject = new SealedObject(toEncrypt, cipher); cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); String result = (String)sealedObject.getObject(cipher); isTrue("result wrong", result.equals(toEncrypt)); result = (String)sealedObject.getObject(keyPair.getPrivate()); isTrue("result wrong", result.equals(toEncrypt)); } public void doTest( String testname, KeyPairGenerator g, String cipher, IESParameterSpec p) throws Exception { byte[] message = Hex.decode("0102030405060708090a0b0c0d0e0f10111213141516"); byte[] out1, out2; // Generate static key pair KeyPair KeyPair = g.generateKeyPair(); ECPublicKey Pub = (ECPublicKey) KeyPair.getPublic(); ECPrivateKey Priv = (ECPrivateKey) KeyPair.getPrivate(); Cipher c1 = Cipher.getInstance(cipher); Cipher c2 = Cipher.getInstance(cipher); // Testing with null parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, Priv, c1.getParameters()); isTrue("nonce mismatch", Arrays.areEqual(c1.getIV(), c2.getIV())); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with null parameters, DHAES mode false."); // Testing with given parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, Priv, p); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with non-null parameters, DHAES mode false."); // TODO: DHAES mode is not currently implemented, perhaps it shouldn't be... // c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); // c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); // // // Testing with null parameters and DHAES mode on // c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom()); // c2.init(Cipher.DECRYPT_MODE, Priv, new SecureRandom()); // // out1 = c1.doFinal(message, 0, message.length); // out2 = c2.doFinal(out1, 0, out1.length); // if (!areEqual(out2, message)) // fail(testname + " test failed with null parameters, DHAES mode true."); // // c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); // c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); // // // Testing with given parameters and DHAES mode on // c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom()); // c2.init(Cipher.DECRYPT_MODE, Priv, p, new SecureRandom()); // // out1 = c1.doFinal(message, 0, message.length); // out2 = c2.doFinal(out1, 0, out1.length); // if (!areEqual(out2, message)) // fail(testname + " test failed with non-null parameters, DHAES mode true."); } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new ECIESTest()); } }
./CrossVul/dataset_final_sorted/CWE-361/java/bad_4762_6
crossvul-java_data_good_4762_4
package org.bouncycastle.jcajce.provider.util; import javax.crypto.BadPaddingException; public class BadBlockException extends BadPaddingException { private final Throwable cause; public BadBlockException(String msg, Throwable cause) { super(msg); this.cause = cause; } public Throwable getCause() { return cause; } }
./CrossVul/dataset_final_sorted/CWE-361/java/good_4762_4
crossvul-java_data_good_4306_0
/** * BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ * * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). * * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 3.0 of the License, or (at your option) any later * version. * * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. * */ package org.bigbluebutton.presentation.imp; import java.io.File; import java.util.HashMap; import java.util.Map; import org.bigbluebutton.presentation.ConversionMessageConstants; import org.bigbluebutton.presentation.SupportedFileTypes; import org.bigbluebutton.presentation.UploadedPresentation; import org.jodconverter.core.office.OfficeException; import org.jodconverter.core.office.OfficeManager; import org.jodconverter.local.LocalConverter; import org.jodconverter.local.office.LocalOfficeManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.star.document.UpdateDocMode; import com.google.gson.Gson; public class OfficeToPdfConversionService { private static Logger log = LoggerFactory.getLogger(OfficeToPdfConversionService.class); private OfficeDocumentValidator2 officeDocumentValidator; private final OfficeManager officeManager; private final LocalConverter documentConverter; private boolean skipOfficePrecheck = false; public OfficeToPdfConversionService() throws OfficeException { final Map<String, Object> loadProperties = new HashMap<>(); loadProperties.put("Hidden", true); loadProperties.put("ReadOnly", true); loadProperties.put("UpdateDocMode", UpdateDocMode.NO_UPDATE); officeManager = LocalOfficeManager .builder() .portNumbers(8100, 8101, 8102, 8103, 8104) .build(); documentConverter = LocalConverter .builder() .officeManager(officeManager) .loadProperties(loadProperties) .filterChain(new OfficeDocumentConversionFilter()) .build(); } /* * Convert the Office document to PDF. If successful, update * UploadPresentation.uploadedFile with the new PDF out and * UploadPresentation.lastStepSuccessful to TRUE. */ public UploadedPresentation convertOfficeToPdf(UploadedPresentation pres) { initialize(pres); if (SupportedFileTypes.isOfficeFile(pres.getFileType())) { // Check if we need to precheck office document if (!skipOfficePrecheck && officeDocumentValidator.isValid(pres)) { Map<String, Object> logData = new HashMap<>(); logData.put("meetingId", pres.getMeetingId()); logData.put("presId", pres.getId()); logData.put("filename", pres.getName()); logData.put("logCode", "problems_office_to_pdf_validation"); logData.put("message", "Problems detected prior to converting the file to PDF."); Gson gson = new Gson(); String logStr = gson.toJson(logData); log.warn(" --analytics-- data={}", logStr); pres.setConversionStatus(ConversionMessageConstants.OFFICE_DOC_CONVERSION_INVALID_KEY); return pres; } File pdfOutput = setupOutputPdfFile(pres); if (convertOfficeDocToPdf(pres, pdfOutput)) { Map<String, Object> logData = new HashMap<>(); logData.put("meetingId", pres.getMeetingId()); logData.put("presId", pres.getId()); logData.put("filename", pres.getName()); logData.put("logCode", "office_to_pdf_success"); logData.put("message", "Successfully converted office file to pdf."); Gson gson = new Gson(); String logStr = gson.toJson(logData); log.info(" --analytics-- data={}", logStr); makePdfTheUploadedFileAndSetStepAsSuccess(pres, pdfOutput); } else { Map<String, Object> logData = new HashMap<>(); logData.put("meetingId", pres.getMeetingId()); logData.put("presId", pres.getId()); logData.put("filename", pres.getName()); logData.put("logCode", "office_to_pdf_failed"); logData.put("message", "Failed to convert " + pres.getUploadedFile().getAbsolutePath() + " to Pdf."); Gson gson = new Gson(); String logStr = gson.toJson(logData); log.warn(" --analytics-- data={}", logStr); pres.setConversionStatus(ConversionMessageConstants.OFFICE_DOC_CONVERSION_FAILED_KEY); return pres; } } return pres; } public void initialize(UploadedPresentation pres) { pres.setConversionStatus(ConversionMessageConstants.OFFICE_DOC_CONVERSION_FAILED_KEY); } private File setupOutputPdfFile(UploadedPresentation pres) { File presentationFile = pres.getUploadedFile(); String filenameWithoutExt = presentationFile.getAbsolutePath().substring(0, presentationFile.getAbsolutePath().lastIndexOf('.')); return new File(filenameWithoutExt + ".pdf"); } private boolean convertOfficeDocToPdf(UploadedPresentation pres, File pdfOutput) { Office2PdfPageConverter converter = new Office2PdfPageConverter(); return converter.convert(pres.getUploadedFile(), pdfOutput, 0, pres, documentConverter); } private void makePdfTheUploadedFileAndSetStepAsSuccess(UploadedPresentation pres, File pdf) { pres.setUploadedFile(pdf); pres.setConversionStatus(ConversionMessageConstants.OFFICE_DOC_CONVERSION_SUCCESS_KEY); } public void setOfficeDocumentValidator(OfficeDocumentValidator2 v) { officeDocumentValidator = v; } public void setSkipOfficePrecheck(boolean skipOfficePrecheck) { this.skipOfficePrecheck = skipOfficePrecheck; } public void start() { try { officeManager.start(); } catch (OfficeException e) { log.error("Could not start Office Manager", e); } } public void stop() { try { officeManager.stop(); } catch (OfficeException e) { log.error("Could not stop Office Manager", e); } } }
./CrossVul/dataset_final_sorted/CWE-918/java/good_4306_0
crossvul-java_data_bad_4306_0
/** * BigBlueButton open source conferencing system - http://www.bigbluebutton.org/ * * Copyright (c) 2012 BigBlueButton Inc. and by respective authors (see below). * * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation; either version 3.0 of the License, or (at your option) any later * version. * * BigBlueButton is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along * with BigBlueButton; if not, see <http://www.gnu.org/licenses/>. * */ package org.bigbluebutton.presentation.imp; import java.io.File; import java.util.HashMap; import java.util.Map; import org.bigbluebutton.presentation.ConversionMessageConstants; import org.bigbluebutton.presentation.SupportedFileTypes; import org.bigbluebutton.presentation.UploadedPresentation; import org.jodconverter.core.office.OfficeException; import org.jodconverter.core.office.OfficeManager; import org.jodconverter.local.LocalConverter; import org.jodconverter.local.office.LocalOfficeManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.gson.Gson; public class OfficeToPdfConversionService { private static Logger log = LoggerFactory.getLogger(OfficeToPdfConversionService.class); private OfficeDocumentValidator2 officeDocumentValidator; private final OfficeManager officeManager; private final LocalConverter documentConverter; private boolean skipOfficePrecheck = false; public OfficeToPdfConversionService() throws OfficeException { officeManager = LocalOfficeManager .builder() .portNumbers(8100, 8101, 8102, 8103, 8104) .build(); documentConverter = LocalConverter .builder() .officeManager(officeManager) .filterChain(new OfficeDocumentConversionFilter()) .build(); } /* * Convert the Office document to PDF. If successful, update * UploadPresentation.uploadedFile with the new PDF out and * UploadPresentation.lastStepSuccessful to TRUE. */ public UploadedPresentation convertOfficeToPdf(UploadedPresentation pres) { initialize(pres); if (SupportedFileTypes.isOfficeFile(pres.getFileType())) { // Check if we need to precheck office document if (!skipOfficePrecheck && officeDocumentValidator.isValid(pres)) { Map<String, Object> logData = new HashMap<>(); logData.put("meetingId", pres.getMeetingId()); logData.put("presId", pres.getId()); logData.put("filename", pres.getName()); logData.put("logCode", "problems_office_to_pdf_validation"); logData.put("message", "Problems detected prior to converting the file to PDF."); Gson gson = new Gson(); String logStr = gson.toJson(logData); log.warn(" --analytics-- data={}", logStr); pres.setConversionStatus(ConversionMessageConstants.OFFICE_DOC_CONVERSION_INVALID_KEY); return pres; } File pdfOutput = setupOutputPdfFile(pres); if (convertOfficeDocToPdf(pres, pdfOutput)) { Map<String, Object> logData = new HashMap<>(); logData.put("meetingId", pres.getMeetingId()); logData.put("presId", pres.getId()); logData.put("filename", pres.getName()); logData.put("logCode", "office_to_pdf_success"); logData.put("message", "Successfully converted office file to pdf."); Gson gson = new Gson(); String logStr = gson.toJson(logData); log.info(" --analytics-- data={}", logStr); makePdfTheUploadedFileAndSetStepAsSuccess(pres, pdfOutput); } else { Map<String, Object> logData = new HashMap<>(); logData.put("meetingId", pres.getMeetingId()); logData.put("presId", pres.getId()); logData.put("filename", pres.getName()); logData.put("logCode", "office_to_pdf_failed"); logData.put("message", "Failed to convert " + pres.getUploadedFile().getAbsolutePath() + " to Pdf."); Gson gson = new Gson(); String logStr = gson.toJson(logData); log.warn(" --analytics-- data={}", logStr); pres.setConversionStatus(ConversionMessageConstants.OFFICE_DOC_CONVERSION_FAILED_KEY); return pres; } } return pres; } public void initialize(UploadedPresentation pres) { pres.setConversionStatus(ConversionMessageConstants.OFFICE_DOC_CONVERSION_FAILED_KEY); } private File setupOutputPdfFile(UploadedPresentation pres) { File presentationFile = pres.getUploadedFile(); String filenameWithoutExt = presentationFile.getAbsolutePath().substring(0, presentationFile.getAbsolutePath().lastIndexOf('.')); return new File(filenameWithoutExt + ".pdf"); } private boolean convertOfficeDocToPdf(UploadedPresentation pres, File pdfOutput) { Office2PdfPageConverter converter = new Office2PdfPageConverter(); return converter.convert(pres.getUploadedFile(), pdfOutput, 0, pres, documentConverter); } private void makePdfTheUploadedFileAndSetStepAsSuccess(UploadedPresentation pres, File pdf) { pres.setUploadedFile(pdf); pres.setConversionStatus(ConversionMessageConstants.OFFICE_DOC_CONVERSION_SUCCESS_KEY); } public void setOfficeDocumentValidator(OfficeDocumentValidator2 v) { officeDocumentValidator = v; } public void setSkipOfficePrecheck(boolean skipOfficePrecheck) { this.skipOfficePrecheck = skipOfficePrecheck; } public void start() { try { officeManager.start(); } catch (OfficeException e) { log.error("Could not start Office Manager", e); } } public void stop() { try { officeManager.stop(); } catch (OfficeException e) { log.error("Could not stop Office Manager", e); } } }
./CrossVul/dataset_final_sorted/CWE-918/java/bad_4306_0
crossvul-java_data_good_658_0
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.transport.https; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; /** * Allow all hostnames. This is only suitable for use in testing, and NOT in production! */ class AllowAllHostnameVerifier implements javax.net.ssl.HostnameVerifier { @Override public boolean verify(String host, SSLSession session) { try { Certificate[] certs = session.getPeerCertificates(); return certs != null && certs[0] instanceof X509Certificate; } catch (SSLException e) { return false; } } public boolean verify(final String host, final String certHostname) { return certHostname != null && !certHostname.isEmpty(); } }
./CrossVul/dataset_final_sorted/CWE-755/java/good_658_0
crossvul-java_data_good_658_4
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.systest.https.hostname; import java.net.URL; import javax.xml.ws.BindingProvider; import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.bus.spring.SpringBusFactory; import org.apache.cxf.testutil.common.AbstractBusClientServerTestBase; import org.apache.hello_world.Greeter; import org.apache.hello_world.services.SOAPService; import org.junit.AfterClass; import org.junit.BeforeClass; /** * A test for hostname verification when the Java system property "java.protocol.handler.pkgs" is set to * "com.sun.net.ssl.internal.www.protocol". This means that com.sun.net.ssl.HostnameVerifier is used * instead of the javax version. */ public class HostnameVerificationDeprecatedTest extends AbstractBusClientServerTestBase { static final String PORT = allocatePort(HostnameVerificationDeprecatedServer.class); static final String PORT2 = allocatePort(HostnameVerificationDeprecatedServer.class, 2); @BeforeClass public static void startServers() throws Exception { System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); assertTrue( "Server failed to launch", // run the server in the same process // set this to false to fork launchServer(HostnameVerificationDeprecatedServer.class, true) ); } @AfterClass public static void cleanup() throws Exception { System.clearProperty("java.protocol.handler.pkgs"); stopAllServers(); } // Here we expect an exception, as the default hostname verifier contributed by CXF will object to the // fact that the server certificate does not have "CN=localhost". @org.junit.Test public void testLocalhostNotMatching() throws Exception { SpringBusFactory bf = new SpringBusFactory(); URL busFile = HostnameVerificationDeprecatedTest.class.getResource("hostname-client-bethal.xml"); Bus bus = bf.createBus(busFile.toString()); BusFactory.setDefaultBus(bus); BusFactory.setThreadDefaultBus(bus); URL url = SOAPService.WSDL_LOCATION; SOAPService service = new SOAPService(url, SOAPService.SERVICE); assertNotNull("Service is null", service); final Greeter port = service.getHttpsPort(); assertNotNull("Port is null", port); updateAddressPort(port, PORT); try { port.greetMe("Kitty"); fail("Failure expected on the hostname verification"); } catch (Exception ex) { // expected } ((java.io.Closeable)port).close(); bus.shutdown(true); } // No Subject Alternative Name, but the CN matches ("localhost"), so the default HostnameVerifier // should work fine @org.junit.Test public void testNoSubjectAlternativeNameCNMatch() throws Exception { SpringBusFactory bf = new SpringBusFactory(); URL busFile = HostnameVerificationDeprecatedTest.class.getResource("hostname-client.xml"); Bus bus = bf.createBus(busFile.toString()); BusFactory.setDefaultBus(bus); BusFactory.setThreadDefaultBus(bus); URL url = SOAPService.WSDL_LOCATION; SOAPService service = new SOAPService(url, SOAPService.SERVICE); assertNotNull("Service is null", service); final Greeter port = service.getHttpsPort(); assertNotNull("Port is null", port); updateAddressPort(port, PORT2); assertEquals(port.greetMe("Kitty"), "Hello Kitty"); // Enable Async ((BindingProvider)port).getRequestContext().put("use.async.http.conduit", true); assertEquals(port.greetMe("Kitty"), "Hello Kitty"); ((java.io.Closeable)port).close(); bus.shutdown(true); } }
./CrossVul/dataset_final_sorted/CWE-755/java/good_658_4
crossvul-java_data_bad_658_4
404: Not Found
./CrossVul/dataset_final_sorted/CWE-755/java/bad_658_4
crossvul-java_data_bad_658_2
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.cxf.transport.https.httpclient; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.cert.Certificate; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.InvalidNameException; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.security.auth.x500.X500Principal; import org.apache.cxf.common.logging.LogUtils; /** * Default {@link javax.net.ssl.HostnameVerifier} implementation. * Copied from httpclient. */ public final class DefaultHostnameVerifier implements HostnameVerifier { enum TYPE { IPv4, IPv6, DNS }; static final int DNS_NAME_TYPE = 2; static final int IP_ADDRESS_TYPE = 7; private static final Logger LOG = LogUtils.getL7dLogger(DefaultHostnameVerifier.class); private final PublicSuffixMatcher publicSuffixMatcher; public DefaultHostnameVerifier(final PublicSuffixMatcher publicSuffixMatcher) { this.publicSuffixMatcher = publicSuffixMatcher; } public DefaultHostnameVerifier() { this(null); } @Override public boolean verify(final String host, final SSLSession session) { try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); return true; } catch (final SSLException ex) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, ex.getMessage(), ex); } return false; } } public void verify( final String host, final X509Certificate cert) throws SSLException { TYPE hostFormat = TYPE.DNS; if (InetAddressUtils.isIPv4Address(host)) { hostFormat = TYPE.IPv4; } else { String s = host; if (s.startsWith("[") && s.endsWith("]")) { s = host.substring(1, host.length() - 1); } if (InetAddressUtils.isIPv6Address(s)) { hostFormat = TYPE.IPv6; } } final int subjectType = hostFormat == TYPE.IPv4 || hostFormat == TYPE.IPv6 ? IP_ADDRESS_TYPE : DNS_NAME_TYPE; final List<String> subjectAlts = extractSubjectAlts(cert, subjectType); if (subjectAlts != null && !subjectAlts.isEmpty()) { switch (hostFormat) { case IPv4: matchIPAddress(host, subjectAlts); break; case IPv6: matchIPv6Address(host, subjectAlts); break; default: matchDNSName(host, subjectAlts, this.publicSuffixMatcher); } } else { // CN matching has been deprecated by rfc2818 and can be used // as fallback only when no subjectAlts are available final X500Principal subjectPrincipal = cert.getSubjectX500Principal(); final String cn = extractCN(subjectPrincipal.getName(X500Principal.RFC2253)); if (cn == null) { throw new SSLException("Certificate subject for <" + host + "> doesn't contain " + "a common name and does not have alternative names"); } matchCN(host, cn, this.publicSuffixMatcher); } } static void matchIPAddress(final String host, final List<String> subjectAlts) throws SSLException { for (int i = 0; i < subjectAlts.size(); i++) { final String subjectAlt = subjectAlts.get(i); if (host.equals(subjectAlt)) { return; } } throw new SSLException("Certificate for <" + host + "> doesn't match any " + "of the subject alternative names: " + subjectAlts); } static void matchIPv6Address(final String host, final List<String> subjectAlts) throws SSLException { final String normalisedHost = normaliseAddress(host); for (int i = 0; i < subjectAlts.size(); i++) { final String subjectAlt = subjectAlts.get(i); final String normalizedSubjectAlt = normaliseAddress(subjectAlt); if (normalisedHost.equals(normalizedSubjectAlt)) { return; } } throw new SSLException("Certificate for <" + host + "> doesn't match any " + "of the subject alternative names: " + subjectAlts); } static void matchDNSName(final String host, final List<String> subjectAlts, final PublicSuffixMatcher publicSuffixMatcher) throws SSLException { final String normalizedHost = host.toLowerCase(Locale.ROOT); for (int i = 0; i < subjectAlts.size(); i++) { final String subjectAlt = subjectAlts.get(i); final String normalizedSubjectAlt = subjectAlt.toLowerCase(Locale.ROOT); if (matchIdentityStrict(normalizedHost, normalizedSubjectAlt, publicSuffixMatcher)) { return; } } throw new SSLException("Certificate for <" + host + "> doesn't match any " + "of the subject alternative names: " + subjectAlts); } static void matchCN(final String host, final String cn, final PublicSuffixMatcher publicSuffixMatcher) throws SSLException { if (!matchIdentityStrict(host, cn, publicSuffixMatcher)) { throw new SSLException("Certificate for <" + host + "> doesn't match " + "common name of the certificate subject: " + cn); } } static boolean matchDomainRoot(final String host, final String domainRoot) { if (domainRoot == null) { return false; } return host.endsWith(domainRoot) && (host.length() == domainRoot.length() || host.charAt(host.length() - domainRoot.length() - 1) == '.'); } private static boolean matchIdentity(final String host, final String identity, final PublicSuffixMatcher publicSuffixMatcher, final boolean strict) { if (publicSuffixMatcher != null && host.contains(".") && !matchDomainRoot(host, publicSuffixMatcher.getDomainRoot(identity, DomainType.ICANN))) { return false; } // RFC 2818, 3.1. Server Identity // "...Names may contain the wildcard // character * which is considered to match any single domain name // component or component fragment..." // Based on this statement presuming only singular wildcard is legal final int asteriskIdx = identity.indexOf('*'); if (asteriskIdx != -1) { final String prefix = identity.substring(0, asteriskIdx); final String suffix = identity.substring(asteriskIdx + 1); if (!prefix.isEmpty() && !host.startsWith(prefix)) { return false; } if (!suffix.isEmpty() && !host.endsWith(suffix)) { return false; } // Additional sanity checks on content selected by wildcard can be done here if (strict) { final String remainder = host.substring( prefix.length(), host.length() - suffix.length()); if (remainder.contains(".")) { return false; } } return true; } return host.equalsIgnoreCase(identity); } static boolean matchIdentity(final String host, final String identity, final PublicSuffixMatcher publicSuffixMatcher) { return matchIdentity(host, identity, publicSuffixMatcher, false); } static boolean matchIdentity(final String host, final String identity) { return matchIdentity(host, identity, null, false); } static boolean matchIdentityStrict(final String host, final String identity, final PublicSuffixMatcher publicSuffixMatcher) { return matchIdentity(host, identity, publicSuffixMatcher, true); } static boolean matchIdentityStrict(final String host, final String identity) { return matchIdentity(host, identity, null, true); } static String extractCN(final String subjectPrincipal) throws SSLException { if (subjectPrincipal == null) { return null; } try { final LdapName subjectDN = new LdapName(subjectPrincipal); final List<Rdn> rdns = subjectDN.getRdns(); for (int i = rdns.size() - 1; i >= 0; i--) { final Rdn rds = rdns.get(i); final Attributes attributes = rds.toAttributes(); final Attribute cn = attributes.get("cn"); if (cn != null) { try { final Object value = cn.get(); if (value != null) { return value.toString(); } } catch (NoSuchElementException ignore) { // } catch (NamingException ignore) { // } } } return null; } catch (InvalidNameException e) { throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name"); } } static List<String> extractSubjectAlts(final X509Certificate cert, final int subjectType) { Collection<List<?>> c = null; try { c = cert.getSubjectAlternativeNames(); } catch (final CertificateParsingException ignore) { // } List<String> subjectAltList = null; if (c != null) { for (final List<?> aC : c) { final List<?> list = aC; final int type = ((Integer) list.get(0)).intValue(); if (type == subjectType) { final String s = (String) list.get(1); if (subjectAltList == null) { subjectAltList = new ArrayList<>(); } subjectAltList.add(s); } } } return subjectAltList; } /* * Normalize IPv6 or DNS name. */ static String normaliseAddress(final String hostname) { if (hostname == null) { return hostname; } try { final InetAddress inetAddress = InetAddress.getByName(hostname); return inetAddress.getHostAddress(); } catch (final UnknownHostException unexpected) { // Should not happen, because we check for IPv6 address above return hostname; } } }
./CrossVul/dataset_final_sorted/CWE-755/java/bad_658_2
crossvul-java_data_bad_658_1
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.transport.https; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.security.GeneralSecurityException; import java.util.logging.Handler; import java.util.logging.Logger; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.common.util.ReflectionInvokationHandler; import org.apache.cxf.common.util.ReflectionUtil; import org.apache.cxf.configuration.jsse.SSLUtils; import org.apache.cxf.configuration.jsse.TLSClientParameters; /** * This HttpsURLConnectionFactory implements the HttpURLConnectionFactory * for using the given SSL Policy to configure TLS connections for "https:" * URLs. */ public class HttpsURLConnectionFactory { /** * This constant holds the URL Protocol Identifier for HTTPS */ public static final String HTTPS_URL_PROTOCOL_ID = "https"; private static final Logger LOG = LogUtils.getL7dLogger(HttpsURLConnectionFactory.class); private static boolean weblogicWarned; /** * Cache the last SSLContext to avoid recreation */ SSLSocketFactory socketFactory; int lastTlsHash; /** * This constructor initialized the factory with the configured TLS * Client Parameters for the HTTPConduit for which this factory is used. */ public HttpsURLConnectionFactory() { } /** * Create a HttpURLConnection, proxified if necessary. * * * @param proxy This parameter is non-null if connection should be proxied. * @param url The target URL. * * @return The HttpURLConnection for the given URL. * @throws IOException */ public HttpURLConnection createConnection(TLSClientParameters tlsClientParameters, Proxy proxy, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) (proxy != null ? url.openConnection(proxy) : url.openConnection()); if (HTTPS_URL_PROTOCOL_ID.equals(url.getProtocol())) { if (tlsClientParameters == null) { tlsClientParameters = new TLSClientParameters(); } try { decorateWithTLS(tlsClientParameters, connection); } catch (Throwable ex) { if (ex instanceof IOException) { throw (IOException) ex; } IOException ioException = new IOException("Error while initializing secure socket", ex); throw ioException; } } return connection; } /** * This method assigns the various TLS parameters on the HttpsURLConnection * from the TLS Client Parameters. Connection parameter is of supertype HttpURLConnection, * which allows internal cast to potentially divergent subtype (https) implementations. */ protected synchronized void decorateWithTLS(TLSClientParameters tlsClientParameters, HttpURLConnection connection) throws GeneralSecurityException { int hash = tlsClientParameters.hashCode(); if (hash != lastTlsHash) { lastTlsHash = hash; socketFactory = null; } // always reload socketFactory from HttpsURLConnection.defaultSSLSocketFactory and // tlsClientParameters.sslSocketFactory to allow runtime configuration change if (tlsClientParameters.isUseHttpsURLConnectionDefaultSslSocketFactory()) { socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); } else if (tlsClientParameters.getSSLSocketFactory() != null) { // see if an SSLSocketFactory was set. This allows easy interop // with not-yet-commons-ssl.jar, or even just people who like doing their // own JSSE. socketFactory = tlsClientParameters.getSSLSocketFactory(); } else if (socketFactory == null) { // ssl socket factory not yet instantiated, create a new one with tlsClientParameters's Trust // Managers, Key Managers, etc SSLContext ctx = org.apache.cxf.transport.https.SSLUtils.getSSLContext(tlsClientParameters); String[] cipherSuites = SSLUtils.getCiphersuitesToInclude(tlsClientParameters.getCipherSuites(), tlsClientParameters.getCipherSuitesFilter(), ctx.getSocketFactory().getDefaultCipherSuites(), SSLUtils.getSupportedCipherSuites(ctx), LOG); // The SSLSocketFactoryWrapper enables certain cipher suites // from the policy. String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters .getSecureSocketProtocol() : "TLS"; socketFactory = new SSLSocketFactoryWrapper(ctx.getSocketFactory(), cipherSuites, protocol); //recalc the hashcode since some of the above MAY have changed the tlsClientParameters lastTlsHash = tlsClientParameters.hashCode(); } else { // ssl socket factory already initialized, reuse it to benefit of keep alive } HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils .getHostnameVerifier(tlsClientParameters); if (connection instanceof HttpsURLConnection) { // handle the expected case (javax.net.ssl) HttpsURLConnection conn = (HttpsURLConnection) connection; conn.setHostnameVerifier(verifier); conn.setSSLSocketFactory(socketFactory); } else { // handle the deprecated sun case and other possible hidden API's // that are similar to the Sun cases try { Method method = connection.getClass().getMethod("getHostnameVerifier"); InvocationHandler handler = new ReflectionInvokationHandler(verifier) { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return super.invoke(proxy, method, args); } catch (Exception ex) { return true; } } }; Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {method.getReturnType()}, handler); method = connection.getClass().getMethod("setHostnameVerifier", method.getReturnType()); method.invoke(connection, proxy); } catch (Exception ex) { //Ignore this one } try { Method getSSLSocketFactory = connection.getClass().getMethod("getSSLSocketFactory"); Method setSSLSocketFactory = connection.getClass() .getMethod("setSSLSocketFactory", getSSLSocketFactory.getReturnType()); if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) { setSSLSocketFactory.invoke(connection, socketFactory); } else { //need to see if we can create one - mostly the weblogic case. The //weblogic SSLSocketFactory has a protected constructor that can take //a JSSE SSLSocketFactory so we'll try and use that Constructor<?> c = getSSLSocketFactory.getReturnType() .getDeclaredConstructor(SSLSocketFactory.class); ReflectionUtil.setAccessible(c); setSSLSocketFactory.invoke(connection, c.newInstance(socketFactory)); } } catch (Exception ex) { if (connection.getClass().getName().contains("weblogic")) { if (!weblogicWarned) { weblogicWarned = true; LOG.warning("Could not configure SSLSocketFactory on Weblogic. " + " Use the Weblogic control panel to configure the SSL settings."); } return; } //if we cannot set the SSLSocketFactory, we're in serious trouble. throw new IllegalArgumentException("Error decorating connection class " + connection.getClass().getName(), ex); } } } /* * For development and testing only */ protected void addLogHandler(Handler handler) { LOG.addHandler(handler); } }
./CrossVul/dataset_final_sorted/CWE-755/java/bad_658_1
crossvul-java_data_bad_658_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-755/java/bad_658_3
crossvul-java_data_good_658_2
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.cxf.transport.https.httpclient; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.cert.Certificate; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.InvalidNameException; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; import javax.security.auth.x500.X500Principal; import org.apache.cxf.common.logging.LogUtils; /** * Default {@link javax.net.ssl.HostnameVerifier} implementation. * Copied from httpclient. */ public final class DefaultHostnameVerifier implements HostnameVerifier { enum TYPE { IPv4, IPv6, DNS }; static final int DNS_NAME_TYPE = 2; static final int IP_ADDRESS_TYPE = 7; private static final Logger LOG = LogUtils.getL7dLogger(DefaultHostnameVerifier.class); private final PublicSuffixMatcher publicSuffixMatcher; public DefaultHostnameVerifier(final PublicSuffixMatcher publicSuffixMatcher) { this.publicSuffixMatcher = publicSuffixMatcher; } public DefaultHostnameVerifier() { this(null); } @Override public boolean verify(final String host, final SSLSession session) { try { final Certificate[] certs = session.getPeerCertificates(); final X509Certificate x509 = (X509Certificate) certs[0]; verify(host, x509); return true; } catch (final SSLException ex) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, ex.getMessage(), ex); } return false; } } public void verify( final String host, final X509Certificate cert) throws SSLException { TYPE hostFormat = TYPE.DNS; if (InetAddressUtils.isIPv4Address(host)) { hostFormat = TYPE.IPv4; } else { String s = host; if (s.startsWith("[") && s.endsWith("]")) { s = host.substring(1, host.length() - 1); } if (InetAddressUtils.isIPv6Address(s)) { hostFormat = TYPE.IPv6; } } final int subjectType = hostFormat == TYPE.IPv4 || hostFormat == TYPE.IPv6 ? IP_ADDRESS_TYPE : DNS_NAME_TYPE; final List<String> subjectAlts = extractSubjectAlts(cert, subjectType); if (subjectAlts != null && !subjectAlts.isEmpty()) { switch (hostFormat) { case IPv4: matchIPAddress(host, subjectAlts); break; case IPv6: matchIPv6Address(host, subjectAlts); break; default: matchDNSName(host, subjectAlts, this.publicSuffixMatcher); } } else { // CN matching has been deprecated by rfc2818 and can be used // as fallback only when no subjectAlts are available final X500Principal subjectPrincipal = cert.getSubjectX500Principal(); final String cn = extractCN(subjectPrincipal.getName(X500Principal.RFC2253)); if (cn == null) { throw new SSLException("Certificate subject for <" + host + "> doesn't contain " + "a common name and does not have alternative names"); } matchCN(host, cn, this.publicSuffixMatcher); } } public boolean verify(final String host, final String certHostname) { try { matchCN(host, certHostname, this.publicSuffixMatcher); return true; } catch (SSLException ex) { if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, ex.getMessage(), ex); } return false; } } static void matchIPAddress(final String host, final List<String> subjectAlts) throws SSLException { for (int i = 0; i < subjectAlts.size(); i++) { final String subjectAlt = subjectAlts.get(i); if (host.equals(subjectAlt)) { return; } } throw new SSLException("Certificate for <" + host + "> doesn't match any " + "of the subject alternative names: " + subjectAlts); } static void matchIPv6Address(final String host, final List<String> subjectAlts) throws SSLException { final String normalisedHost = normaliseAddress(host); for (int i = 0; i < subjectAlts.size(); i++) { final String subjectAlt = subjectAlts.get(i); final String normalizedSubjectAlt = normaliseAddress(subjectAlt); if (normalisedHost.equals(normalizedSubjectAlt)) { return; } } throw new SSLException("Certificate for <" + host + "> doesn't match any " + "of the subject alternative names: " + subjectAlts); } static void matchDNSName(final String host, final List<String> subjectAlts, final PublicSuffixMatcher publicSuffixMatcher) throws SSLException { final String normalizedHost = host.toLowerCase(Locale.ROOT); for (int i = 0; i < subjectAlts.size(); i++) { final String subjectAlt = subjectAlts.get(i); final String normalizedSubjectAlt = subjectAlt.toLowerCase(Locale.ROOT); if (matchIdentityStrict(normalizedHost, normalizedSubjectAlt, publicSuffixMatcher)) { return; } } throw new SSLException("Certificate for <" + host + "> doesn't match any " + "of the subject alternative names: " + subjectAlts); } static void matchCN(final String host, final String cn, final PublicSuffixMatcher publicSuffixMatcher) throws SSLException { if (!matchIdentityStrict(host, cn, publicSuffixMatcher)) { throw new SSLException("Certificate for <" + host + "> doesn't match " + "common name of the certificate subject: " + cn); } } static boolean matchDomainRoot(final String host, final String domainRoot) { if (domainRoot == null) { return false; } return host.endsWith(domainRoot) && (host.length() == domainRoot.length() || host.charAt(host.length() - domainRoot.length() - 1) == '.'); } private static boolean matchIdentity(final String host, final String identity, final PublicSuffixMatcher publicSuffixMatcher, final boolean strict) { if (publicSuffixMatcher != null && host.contains(".") && !matchDomainRoot(host, publicSuffixMatcher.getDomainRoot(identity, DomainType.ICANN))) { return false; } // RFC 2818, 3.1. Server Identity // "...Names may contain the wildcard // character * which is considered to match any single domain name // component or component fragment..." // Based on this statement presuming only singular wildcard is legal final int asteriskIdx = identity.indexOf('*'); if (asteriskIdx != -1) { final String prefix = identity.substring(0, asteriskIdx); final String suffix = identity.substring(asteriskIdx + 1); if (!prefix.isEmpty() && !host.startsWith(prefix)) { return false; } if (!suffix.isEmpty() && !host.endsWith(suffix)) { return false; } // Additional sanity checks on content selected by wildcard can be done here if (strict) { final String remainder = host.substring( prefix.length(), host.length() - suffix.length()); if (remainder.contains(".")) { return false; } } return true; } return host.equalsIgnoreCase(identity); } static boolean matchIdentity(final String host, final String identity, final PublicSuffixMatcher publicSuffixMatcher) { return matchIdentity(host, identity, publicSuffixMatcher, false); } static boolean matchIdentity(final String host, final String identity) { return matchIdentity(host, identity, null, false); } static boolean matchIdentityStrict(final String host, final String identity, final PublicSuffixMatcher publicSuffixMatcher) { return matchIdentity(host, identity, publicSuffixMatcher, true); } static boolean matchIdentityStrict(final String host, final String identity) { return matchIdentity(host, identity, null, true); } static String extractCN(final String subjectPrincipal) throws SSLException { if (subjectPrincipal == null) { return null; } try { final LdapName subjectDN = new LdapName(subjectPrincipal); final List<Rdn> rdns = subjectDN.getRdns(); for (int i = rdns.size() - 1; i >= 0; i--) { final Rdn rds = rdns.get(i); final Attributes attributes = rds.toAttributes(); final Attribute cn = attributes.get("cn"); if (cn != null) { try { final Object value = cn.get(); if (value != null) { return value.toString(); } } catch (NoSuchElementException ignore) { // } catch (NamingException ignore) { // } } } return null; } catch (InvalidNameException e) { throw new SSLException(subjectPrincipal + " is not a valid X500 distinguished name"); } } static List<String> extractSubjectAlts(final X509Certificate cert, final int subjectType) { Collection<List<?>> c = null; try { c = cert.getSubjectAlternativeNames(); } catch (final CertificateParsingException ignore) { // } List<String> subjectAltList = null; if (c != null) { for (final List<?> aC : c) { final List<?> list = aC; final int type = ((Integer) list.get(0)).intValue(); if (type == subjectType) { final String s = (String) list.get(1); if (subjectAltList == null) { subjectAltList = new ArrayList<>(); } subjectAltList.add(s); } } } return subjectAltList; } /* * Normalize IPv6 or DNS name. */ static String normaliseAddress(final String hostname) { if (hostname == null) { return hostname; } try { final InetAddress inetAddress = InetAddress.getByName(hostname); return inetAddress.getHostAddress(); } catch (final UnknownHostException unexpected) { // Should not happen, because we check for IPv6 address above return hostname; } } }
./CrossVul/dataset_final_sorted/CWE-755/java/good_658_2
crossvul-java_data_good_658_1
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.transport.https; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.Proxy; import java.net.URL; import java.security.GeneralSecurityException; import java.util.logging.Handler; import java.util.logging.Logger; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.common.util.ReflectionInvokationHandler; import org.apache.cxf.common.util.ReflectionUtil; import org.apache.cxf.configuration.jsse.SSLUtils; import org.apache.cxf.configuration.jsse.TLSClientParameters; /** * This HttpsURLConnectionFactory implements the HttpURLConnectionFactory * for using the given SSL Policy to configure TLS connections for "https:" * URLs. */ public class HttpsURLConnectionFactory { /** * This constant holds the URL Protocol Identifier for HTTPS */ public static final String HTTPS_URL_PROTOCOL_ID = "https"; private static final Logger LOG = LogUtils.getL7dLogger(HttpsURLConnectionFactory.class); private static boolean weblogicWarned; /** * Cache the last SSLContext to avoid recreation */ SSLSocketFactory socketFactory; int lastTlsHash; /** * This constructor initialized the factory with the configured TLS * Client Parameters for the HTTPConduit for which this factory is used. */ public HttpsURLConnectionFactory() { } /** * Create a HttpURLConnection, proxified if necessary. * * * @param proxy This parameter is non-null if connection should be proxied. * @param url The target URL. * * @return The HttpURLConnection for the given URL. * @throws IOException */ public HttpURLConnection createConnection(TLSClientParameters tlsClientParameters, Proxy proxy, URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) (proxy != null ? url.openConnection(proxy) : url.openConnection()); if (HTTPS_URL_PROTOCOL_ID.equals(url.getProtocol())) { if (tlsClientParameters == null) { tlsClientParameters = new TLSClientParameters(); } try { decorateWithTLS(tlsClientParameters, connection); } catch (Throwable ex) { if (ex instanceof IOException) { throw (IOException) ex; } IOException ioException = new IOException("Error while initializing secure socket", ex); throw ioException; } } return connection; } /** * This method assigns the various TLS parameters on the HttpsURLConnection * from the TLS Client Parameters. Connection parameter is of supertype HttpURLConnection, * which allows internal cast to potentially divergent subtype (https) implementations. */ protected synchronized void decorateWithTLS(TLSClientParameters tlsClientParameters, HttpURLConnection connection) throws GeneralSecurityException { int hash = tlsClientParameters.hashCode(); if (hash != lastTlsHash) { lastTlsHash = hash; socketFactory = null; } // always reload socketFactory from HttpsURLConnection.defaultSSLSocketFactory and // tlsClientParameters.sslSocketFactory to allow runtime configuration change if (tlsClientParameters.isUseHttpsURLConnectionDefaultSslSocketFactory()) { socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); } else if (tlsClientParameters.getSSLSocketFactory() != null) { // see if an SSLSocketFactory was set. This allows easy interop // with not-yet-commons-ssl.jar, or even just people who like doing their // own JSSE. socketFactory = tlsClientParameters.getSSLSocketFactory(); } else if (socketFactory == null) { // ssl socket factory not yet instantiated, create a new one with tlsClientParameters's Trust // Managers, Key Managers, etc SSLContext ctx = org.apache.cxf.transport.https.SSLUtils.getSSLContext(tlsClientParameters); String[] cipherSuites = SSLUtils.getCiphersuitesToInclude(tlsClientParameters.getCipherSuites(), tlsClientParameters.getCipherSuitesFilter(), ctx.getSocketFactory().getDefaultCipherSuites(), SSLUtils.getSupportedCipherSuites(ctx), LOG); // The SSLSocketFactoryWrapper enables certain cipher suites // from the policy. String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters .getSecureSocketProtocol() : "TLS"; socketFactory = new SSLSocketFactoryWrapper(ctx.getSocketFactory(), cipherSuites, protocol); //recalc the hashcode since some of the above MAY have changed the tlsClientParameters lastTlsHash = tlsClientParameters.hashCode(); } else { // ssl socket factory already initialized, reuse it to benefit of keep alive } HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils .getHostnameVerifier(tlsClientParameters); if (connection instanceof HttpsURLConnection) { // handle the expected case (javax.net.ssl) HttpsURLConnection conn = (HttpsURLConnection) connection; conn.setHostnameVerifier(verifier); conn.setSSLSocketFactory(socketFactory); } else { // handle the deprecated sun case and other possible hidden API's // that are similar to the Sun cases try { Method method = connection.getClass().getMethod("getHostnameVerifier"); InvocationHandler handler = new ReflectionInvokationHandler(verifier) { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { return super.invoke(proxy, method, args); } catch (Exception ex) { return false; } } }; Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {method.getReturnType()}, handler); method = connection.getClass().getMethod("setHostnameVerifier", method.getReturnType()); method.invoke(connection, proxy); } catch (Exception ex) { //Ignore this one } try { Method getSSLSocketFactory = connection.getClass().getMethod("getSSLSocketFactory"); Method setSSLSocketFactory = connection.getClass() .getMethod("setSSLSocketFactory", getSSLSocketFactory.getReturnType()); if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) { setSSLSocketFactory.invoke(connection, socketFactory); } else { //need to see if we can create one - mostly the weblogic case. The //weblogic SSLSocketFactory has a protected constructor that can take //a JSSE SSLSocketFactory so we'll try and use that Constructor<?> c = getSSLSocketFactory.getReturnType() .getDeclaredConstructor(SSLSocketFactory.class); ReflectionUtil.setAccessible(c); setSSLSocketFactory.invoke(connection, c.newInstance(socketFactory)); } } catch (Exception ex) { if (connection.getClass().getName().contains("weblogic")) { if (!weblogicWarned) { weblogicWarned = true; LOG.warning("Could not configure SSLSocketFactory on Weblogic. " + " Use the Weblogic control panel to configure the SSL settings."); } return; } //if we cannot set the SSLSocketFactory, we're in serious trouble. throw new IllegalArgumentException("Error decorating connection class " + connection.getClass().getName(), ex); } } } /* * For development and testing only */ protected void addLogHandler(Handler handler) { LOG.addHandler(handler); } }
./CrossVul/dataset_final_sorted/CWE-755/java/good_658_1
crossvul-java_data_good_658_3
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.systest.https.hostname; import java.net.URL; import org.apache.cxf.Bus; import org.apache.cxf.BusFactory; import org.apache.cxf.bus.spring.SpringBusFactory; import org.apache.cxf.testutil.common.AbstractBusTestServerBase; public class HostnameVerificationDeprecatedServer extends AbstractBusTestServerBase { public HostnameVerificationDeprecatedServer() { } protected void run() { URL busFile = HostnameVerificationDeprecatedServer.class.getResource("hostname-server-bethal.xml"); Bus busLocal = new SpringBusFactory().createBus(busFile); BusFactory.setDefaultBus(busLocal); setBus(busLocal); try { new HostnameVerificationDeprecatedServer(); } catch (Exception e) { e.printStackTrace(); } } }
./CrossVul/dataset_final_sorted/CWE-755/java/good_658_3
crossvul-java_data_bad_658_0
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.transport.https; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import javax.net.ssl.SSLException; import javax.net.ssl.SSLSession; /** * Allow all hostnames. This is only suitable for use in testing, and NOT in production! */ class AllowAllHostnameVerifier implements javax.net.ssl.HostnameVerifier { @Override public boolean verify(String host, SSLSession session) { try { Certificate[] certs = session.getPeerCertificates(); return certs != null && certs[0] instanceof X509Certificate; } catch (SSLException e) { return false; } } }
./CrossVul/dataset_final_sorted/CWE-755/java/bad_658_0
crossvul-java_data_bad_4763_1
package org.bouncycastle.crypto.agreement; import java.math.BigInteger; import org.bouncycastle.crypto.BasicAgreement; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPrivateKeyParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; /** * a Diffie-Hellman key agreement class. * <p> * note: This is only the basic algorithm, it doesn't take advantage of * long term public keys if they are available. See the DHAgreement class * for a "better" implementation. */ public class DHBasicAgreement implements BasicAgreement { private DHPrivateKeyParameters key; private DHParameters dhParams; public void init( CipherParameters param) { AsymmetricKeyParameter kParam; if (param instanceof ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; kParam = (AsymmetricKeyParameter)rParam.getParameters(); } else { kParam = (AsymmetricKeyParameter)param; } if (!(kParam instanceof DHPrivateKeyParameters)) { throw new IllegalArgumentException("DHEngine expects DHPrivateKeyParameters"); } this.key = (DHPrivateKeyParameters)kParam; this.dhParams = key.getParameters(); } public int getFieldSize() { return (key.getParameters().getP().bitLength() + 7) / 8; } /** * given a short term public key from a given party calculate the next * message in the agreement sequence. */ public BigInteger calculateAgreement( CipherParameters pubKey) { DHPublicKeyParameters pub = (DHPublicKeyParameters)pubKey; if (!pub.getParameters().equals(dhParams)) { throw new IllegalArgumentException("Diffie-Hellman public key has wrong parameters."); } return pub.getY().modPow(key.getX(), dhParams.getP()); } }
./CrossVul/dataset_final_sorted/CWE-320/java/bad_4763_1
crossvul-java_data_good_4763_4
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.crypto.DerivationFunction; import org.bouncycastle.crypto.agreement.kdf.DHKEKGenerator; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.jcajce.provider.asymmetric.util.BaseAgreementSpi; import org.bouncycastle.jcajce.spec.UserKeyingMaterialSpec; /** * Diffie-Hellman key agreement. There's actually a better way of doing this * if you are using long term public keys, see the light-weight version for * details. */ public class KeyAgreementSpi extends BaseAgreementSpi { private static final BigInteger ONE = BigInteger.valueOf(1); private static final BigInteger TWO = BigInteger.valueOf(2); private BigInteger x; private BigInteger p; private BigInteger g; private BigInteger result; public KeyAgreementSpi() { super("Diffie-Hellman", null); } public KeyAgreementSpi( String kaAlgorithm, DerivationFunction kdf) { super(kaAlgorithm, kdf); } protected byte[] bigIntToBytes( BigInteger r) { // // RFC 2631 (2.1.2) specifies that the secret should be padded with leading zeros if necessary // must be the same length as p // int expectedLength = (p.bitLength() + 7) / 8; byte[] tmp = r.toByteArray(); if (tmp.length == expectedLength) { return tmp; } if (tmp[0] == 0 && tmp.length == expectedLength + 1) { byte[] rv = new byte[tmp.length - 1]; System.arraycopy(tmp, 1, rv, 0, rv.length); return rv; } // tmp must be shorter than expectedLength // pad to the left with zeros. byte[] rv = new byte[expectedLength]; System.arraycopy(tmp, 0, rv, rv.length - tmp.length, tmp.length); return rv; } protected Key engineDoPhase( Key key, boolean lastPhase) throws InvalidKeyException, IllegalStateException { if (x == null) { throw new IllegalStateException("Diffie-Hellman not initialised."); } if (!(key instanceof DHPublicKey)) { throw new InvalidKeyException("DHKeyAgreement doPhase requires DHPublicKey"); } DHPublicKey pubKey = (DHPublicKey)key; if (!pubKey.getParams().getG().equals(g) || !pubKey.getParams().getP().equals(p)) { throw new InvalidKeyException("DHPublicKey not for this KeyAgreement!"); } BigInteger peerY = ((DHPublicKey)key).getY(); if (peerY == null || peerY.compareTo(TWO) < 0 || peerY.compareTo(p.subtract(ONE)) >= 0) { throw new InvalidKeyException("Invalid DH PublicKey"); } result = peerY.modPow(x, p); if (result.compareTo(ONE) == 0) { throw new InvalidKeyException("Shared key can't be 1"); } if (lastPhase) { return null; } return new BCDHPublicKey(result, pubKey.getParams()); } protected byte[] engineGenerateSecret() throws IllegalStateException { if (x == null) { throw new IllegalStateException("Diffie-Hellman not initialised."); } return super.engineGenerateSecret(); } protected int engineGenerateSecret( byte[] sharedSecret, int offset) throws IllegalStateException, ShortBufferException { if (x == null) { throw new IllegalStateException("Diffie-Hellman not initialised."); } return super.engineGenerateSecret(sharedSecret, offset); } protected SecretKey engineGenerateSecret( String algorithm) throws NoSuchAlgorithmException { if (x == null) { throw new IllegalStateException("Diffie-Hellman not initialised."); } byte[] res = bigIntToBytes(result); // for JSSE compatibility if (algorithm.equals("TlsPremasterSecret")) { return new SecretKeySpec(trimZeroes(res), algorithm); } return super.engineGenerateSecret(algorithm); } protected void engineInit( Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { if (!(key instanceof DHPrivateKey)) { throw new InvalidKeyException("DHKeyAgreement requires DHPrivateKey for initialisation"); } DHPrivateKey privKey = (DHPrivateKey)key; if (params != null) { if (params instanceof DHParameterSpec) // p, g override. { DHParameterSpec p = (DHParameterSpec)params; this.p = p.getP(); this.g = p.getG(); } else if (params instanceof UserKeyingMaterialSpec) { this.p = privKey.getParams().getP(); this.g = privKey.getParams().getG(); this.ukmParameters = ((UserKeyingMaterialSpec)params).getUserKeyingMaterial(); } else { throw new InvalidAlgorithmParameterException("DHKeyAgreement only accepts DHParameterSpec"); } } else { this.p = privKey.getParams().getP(); this.g = privKey.getParams().getG(); } this.x = this.result = privKey.getX(); } protected void engineInit( Key key, SecureRandom random) throws InvalidKeyException { if (!(key instanceof DHPrivateKey)) { throw new InvalidKeyException("DHKeyAgreement requires DHPrivateKey"); } DHPrivateKey privKey = (DHPrivateKey)key; this.p = privKey.getParams().getP(); this.g = privKey.getParams().getG(); this.x = this.result = privKey.getX(); } protected byte[] calcSecret() { return bigIntToBytes(result); } public static class DHwithRFC2631KDF extends KeyAgreementSpi { public DHwithRFC2631KDF() { super("DHwithRFC2631KDF", new DHKEKGenerator(new SHA1Digest())); } } }
./CrossVul/dataset_final_sorted/CWE-320/java/good_4763_4
crossvul-java_data_bad_4763_0
package org.bouncycastle.crypto.agreement; import java.math.BigInteger; import java.security.SecureRandom; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.generators.DHKeyPairGenerator; import org.bouncycastle.crypto.params.DHKeyGenerationParameters; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.DHPrivateKeyParameters; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ParametersWithRandom; /** * a Diffie-Hellman key exchange engine. * <p> * note: This uses MTI/A0 key agreement in order to make the key agreement * secure against passive attacks. If you're doing Diffie-Hellman and both * parties have long term public keys you should look at using this. For * further information have a look at RFC 2631. * <p> * It's possible to extend this to more than two parties as well, for the moment * that is left as an exercise for the reader. */ public class DHAgreement { private DHPrivateKeyParameters key; private DHParameters dhParams; private BigInteger privateValue; private SecureRandom random; public void init( CipherParameters param) { AsymmetricKeyParameter kParam; if (param instanceof ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; this.random = rParam.getRandom(); kParam = (AsymmetricKeyParameter)rParam.getParameters(); } else { this.random = new SecureRandom(); kParam = (AsymmetricKeyParameter)param; } if (!(kParam instanceof DHPrivateKeyParameters)) { throw new IllegalArgumentException("DHEngine expects DHPrivateKeyParameters"); } this.key = (DHPrivateKeyParameters)kParam; this.dhParams = key.getParameters(); } /** * calculate our initial message. */ public BigInteger calculateMessage() { DHKeyPairGenerator dhGen = new DHKeyPairGenerator(); dhGen.init(new DHKeyGenerationParameters(random, dhParams)); AsymmetricCipherKeyPair dhPair = dhGen.generateKeyPair(); this.privateValue = ((DHPrivateKeyParameters)dhPair.getPrivate()).getX(); return ((DHPublicKeyParameters)dhPair.getPublic()).getY(); } /** * given a message from a given party and the corresponding public key, * calculate the next message in the agreement sequence. In this case * this will represent the shared secret. */ public BigInteger calculateAgreement( DHPublicKeyParameters pub, BigInteger message) { if (!pub.getParameters().equals(dhParams)) { throw new IllegalArgumentException("Diffie-Hellman public key has wrong parameters."); } BigInteger p = dhParams.getP(); return message.modPow(key.getX(), p).multiply(pub.getY().modPow(privateValue, p)).mod(p); } }
./CrossVul/dataset_final_sorted/CWE-320/java/bad_4763_0
crossvul-java_data_good_4763_1
package org.bouncycastle.crypto.agreement; import java.math.BigInteger; import org.bouncycastle.crypto.BasicAgreement; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPrivateKeyParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; /** * a Diffie-Hellman key agreement class. * <p> * note: This is only the basic algorithm, it doesn't take advantage of * long term public keys if they are available. See the DHAgreement class * for a "better" implementation. */ public class DHBasicAgreement implements BasicAgreement { private static final BigInteger ONE = BigInteger.valueOf(1); private DHPrivateKeyParameters key; private DHParameters dhParams; public void init( CipherParameters param) { AsymmetricKeyParameter kParam; if (param instanceof ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; kParam = (AsymmetricKeyParameter)rParam.getParameters(); } else { kParam = (AsymmetricKeyParameter)param; } if (!(kParam instanceof DHPrivateKeyParameters)) { throw new IllegalArgumentException("DHEngine expects DHPrivateKeyParameters"); } this.key = (DHPrivateKeyParameters)kParam; this.dhParams = key.getParameters(); } public int getFieldSize() { return (key.getParameters().getP().bitLength() + 7) / 8; } /** * given a short term public key from a given party calculate the next * message in the agreement sequence. */ public BigInteger calculateAgreement( CipherParameters pubKey) { DHPublicKeyParameters pub = (DHPublicKeyParameters)pubKey; if (!pub.getParameters().equals(dhParams)) { throw new IllegalArgumentException("Diffie-Hellman public key has wrong parameters."); } BigInteger result = pub.getY().modPow(key.getX(), dhParams.getP()); if (result.compareTo(ONE) == 0) { throw new IllegalStateException("Shared key can't be 1"); } return result; } }
./CrossVul/dataset_final_sorted/CWE-320/java/good_4763_1
crossvul-java_data_bad_4763_2
package org.bouncycastle.crypto.engines; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.crypto.BasicAgreement; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DerivationFunction; import org.bouncycastle.crypto.EphemeralKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyParser; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.IESParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.KDFParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Pack; /** * Support class for constructing integrated encryption ciphers * for doing basic message exchanges on top of key agreement ciphers. * Follows the description given in IEEE Std 1363a. */ public class IESEngine { BasicAgreement agree; DerivationFunction kdf; Mac mac; BufferedBlockCipher cipher; byte[] macBuf; boolean forEncryption; CipherParameters privParam, pubParam; IESParameters param; byte[] V; private EphemeralKeyPairGenerator keyPairGenerator; private KeyParser keyParser; private byte[] IV; /** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message */ public IESEngine( BasicAgreement agree, DerivationFunction kdf, Mac mac) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.getMacSize()]; this.cipher = null; } /** * Set up for use in conjunction with a block cipher to handle the * message.It is <b>strongly</b> recommended that the cipher is not in ECB mode. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param cipher the cipher to used for encrypting the message */ public IESEngine( BasicAgreement agree, DerivationFunction kdf, Mac mac, BufferedBlockCipher cipher) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.getMacSize()]; this.cipher = cipher; } /** * Initialise the encryptor. * * @param forEncryption whether or not this is encryption/decryption. * @param privParam our private key parameters * @param pubParam the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. */ public void init( boolean forEncryption, CipherParameters privParam, CipherParameters pubParam, CipherParameters params) { this.forEncryption = forEncryption; this.privParam = privParam; this.pubParam = pubParam; this.V = new byte[0]; extractParams(params); } /** * Initialise the decryptor. * * @param publicKey the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param ephemeralKeyPairGenerator the ephemeral key pair generator to use. */ public void init(AsymmetricKeyParameter publicKey, CipherParameters params, EphemeralKeyPairGenerator ephemeralKeyPairGenerator) { this.forEncryption = true; this.pubParam = publicKey; this.keyPairGenerator = ephemeralKeyPairGenerator; extractParams(params); } /** * Initialise the encryptor. * * @param privateKey the recipient's private key. * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param publicKeyParser the parser for reading the ephemeral public key. */ public void init(AsymmetricKeyParameter privateKey, CipherParameters params, KeyParser publicKeyParser) { this.forEncryption = false; this.privParam = privateKey; this.keyParser = publicKeyParser; extractParams(params); } private void extractParams(CipherParameters params) { if (params instanceof ParametersWithIV) { this.IV = ((ParametersWithIV)params).getIV(); this.param = (IESParameters)((ParametersWithIV)params).getParameters(); } else { this.IV = null; this.param = (IESParameters)params; } } public BufferedBlockCipher getCipher() { return cipher; } public Mac getMac() { return mac; } private byte[] encryptBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { byte[] C = null, K = null, K1 = null, K2 = null; int len; if (cipher == null) { // Streaming mode. K1 = new byte[inLen]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); if (V.length != 0) { System.arraycopy(K, 0, K2, 0, K2.length); System.arraycopy(K, K2.length, K1, 0, K1.length); } else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, inLen, K2, 0, K2.length); } C = new byte[inLen]; for (int i = 0; i != inLen; i++) { C[i] = (byte)(in[inOff + i] ^ K1[i]); } len = inLen; } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If iv provided use it to initialise the cipher if (IV != null) { cipher.init(true, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(true, new KeyParameter(K1)); } C = new byte[cipher.getOutputSize(inLen)]; len = cipher.processBytes(in, inOff, inLen, C, 0); len += cipher.doFinal(C, len); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); byte[] L2 = null; if (V.length != 0) { L2 = getLengthTag(P2); } // Apply the MAC. byte[] T = new byte[mac.getMacSize()]; mac.init(new KeyParameter(K2)); mac.update(C, 0, C.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0) { mac.update(L2, 0, L2.length); } mac.doFinal(T, 0); // Output the triple (V,C,T). byte[] Output = new byte[V.length + len + T.length]; System.arraycopy(V, 0, Output, 0, V.length); System.arraycopy(C, 0, Output, V.length, len); System.arraycopy(T, 0, Output, V.length + len, T.length); return Output; } private byte[] decryptBlock( byte[] in_enc, int inOff, int inLen) throws InvalidCipherTextException { byte[] M, K, K1, K2; int len = 0; // Ensure that the length of the input is greater than the MAC in bytes if (inLen < V.length + mac.getMacSize()) { throw new InvalidCipherTextException("Length of input must be greater than the MAC and V combined"); } // note order is important: set up keys, do simple encryptions, check mac, do final encryption. if (cipher == null) { // Streaming mode. K1 = new byte[inLen - V.length - mac.getMacSize()]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); if (V.length != 0) { System.arraycopy(K, 0, K2, 0, K2.length); System.arraycopy(K, K2.length, K1, 0, K1.length); } else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); } // process the message M = new byte[K1.length]; for (int i = 0; i != K1.length; i++) { M[i] = (byte)(in_enc[inOff + V.length + i] ^ K1[i]); } } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If IV provide use it to initialize the cipher if (IV != null) { cipher.init(false, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(false, new KeyParameter(K1)); } M = new byte[cipher.getOutputSize(inLen - V.length - mac.getMacSize())]; // do initial processing len = cipher.processBytes(in_enc, inOff + V.length, inLen - V.length - mac.getMacSize(), M, 0); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); byte[] L2 = null; if (V.length != 0) { L2 = getLengthTag(P2); } // Verify the MAC. int end = inOff + inLen; byte[] T1 = Arrays.copyOfRange(in_enc, end - mac.getMacSize(), end); byte[] T2 = new byte[T1.length]; mac.init(new KeyParameter(K2)); mac.update(in_enc, inOff + V.length, inLen - V.length - T2.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0) { mac.update(L2, 0, L2.length); } mac.doFinal(T2, 0); if (!Arrays.constantTimeAreEqual(T1, T2)) { throw new InvalidCipherTextException("invalid MAC"); } if (cipher == null) { return M; } else { len += cipher.doFinal(M, len); return Arrays.copyOfRange(M, 0, len); } } public byte[] processBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { if (forEncryption) { if (keyPairGenerator != null) { EphemeralKeyPair ephKeyPair = keyPairGenerator.generate(); this.privParam = ephKeyPair.getKeyPair().getPrivate(); this.V = ephKeyPair.getEncodedPublicKey(); } } else { if (keyParser != null) { ByteArrayInputStream bIn = new ByteArrayInputStream(in, inOff, inLen); try { this.pubParam = keyParser.readKey(bIn); } catch (IOException e) { throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.getMessage(), e); } int encLength = (inLen - bIn.available()); this.V = Arrays.copyOfRange(in, inOff, inOff + encLength); } } // Compute the common value and convert to byte array. agree.init(privParam); BigInteger z = agree.calculateAgreement(pubParam); byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z); // Create input to KDF. if (V.length != 0) { byte[] VZ = Arrays.concatenate(V, Z); Arrays.fill(Z, (byte)0); Z = VZ; } try { // Initialise the KDF. KDFParameters kdfParam = new KDFParameters(Z, param.getDerivationV()); kdf.init(kdfParam); return forEncryption ? encryptBlock(in, inOff, inLen) : decryptBlock(in, inOff, inLen); } finally { Arrays.fill(Z, (byte)0); } } // as described in Shroup's paper and P1363a protected byte[] getLengthTag(byte[] p2) { byte[] L2 = new byte[8]; if (p2 != null) { Pack.longToBigEndian(p2.length * 8L, L2, 0); } return L2; } }
./CrossVul/dataset_final_sorted/CWE-320/java/bad_4763_2
crossvul-java_data_bad_4763_3
package org.bouncycastle.crypto.params; import java.math.BigInteger; public class DHPublicKeyParameters extends DHKeyParameters { private BigInteger y; public DHPublicKeyParameters( BigInteger y, DHParameters params) { super(false, params); this.y = validate(y, params); } private BigInteger validate(BigInteger y, DHParameters dhParams) { if (dhParams.getQ() != null) { if (BigInteger.ONE.equals(y.modPow(dhParams.getQ(), dhParams.getP()))) { return y; } throw new IllegalArgumentException("Y value does not appear to be in correct group"); } else { return y; // we can't validate without Q. } } public BigInteger getY() { return y; } public int hashCode() { return y.hashCode() ^ super.hashCode(); } public boolean equals( Object obj) { if (!(obj instanceof DHPublicKeyParameters)) { return false; } DHPublicKeyParameters other = (DHPublicKeyParameters)obj; return other.getY().equals(y) && super.equals(obj); } }
./CrossVul/dataset_final_sorted/CWE-320/java/bad_4763_3
crossvul-java_data_good_4763_3
package org.bouncycastle.crypto.params; import java.math.BigInteger; public class DHPublicKeyParameters extends DHKeyParameters { private static final BigInteger ONE = BigInteger.valueOf(1); private static final BigInteger TWO = BigInteger.valueOf(2); private BigInteger y; public DHPublicKeyParameters( BigInteger y, DHParameters params) { super(false, params); this.y = validate(y, params); } private BigInteger validate(BigInteger y, DHParameters dhParams) { if (y == null) { throw new NullPointerException("y value cannot be null"); } if (dhParams.getQ() != null) { if (ONE.equals(y.modPow(dhParams.getQ(), dhParams.getP()))) { return y; } throw new IllegalArgumentException("Y value does not appear to be in correct group"); } else { // TLS check if (y.compareTo(TWO) < 0 || y.compareTo(dhParams.getP().subtract(TWO)) > 0) { throw new IllegalArgumentException("invalid DH public key"); } return y; // we can't validate without Q. } } public BigInteger getY() { return y; } public int hashCode() { return y.hashCode() ^ super.hashCode(); } public boolean equals( Object obj) { if (!(obj instanceof DHPublicKeyParameters)) { return false; } DHPublicKeyParameters other = (DHPublicKeyParameters)obj; return other.getY().equals(y) && super.equals(obj); } }
./CrossVul/dataset_final_sorted/CWE-320/java/good_4763_3
crossvul-java_data_bad_4763_4
package org.bouncycastle.jcajce.provider.asymmetric.dh; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import javax.crypto.SecretKey; import javax.crypto.ShortBufferException; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import javax.crypto.spec.DHParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.crypto.DerivationFunction; import org.bouncycastle.crypto.agreement.kdf.DHKEKGenerator; import org.bouncycastle.crypto.digests.SHA1Digest; import org.bouncycastle.jcajce.provider.asymmetric.util.BaseAgreementSpi; import org.bouncycastle.jcajce.spec.UserKeyingMaterialSpec; /** * Diffie-Hellman key agreement. There's actually a better way of doing this * if you are using long term public keys, see the light-weight version for * details. */ public class KeyAgreementSpi extends BaseAgreementSpi { private BigInteger x; private BigInteger p; private BigInteger g; private BigInteger result; public KeyAgreementSpi() { super("Diffie-Hellman", null); } public KeyAgreementSpi( String kaAlgorithm, DerivationFunction kdf) { super(kaAlgorithm, kdf); } protected byte[] bigIntToBytes( BigInteger r) { // // RFC 2631 (2.1.2) specifies that the secret should be padded with leading zeros if necessary // must be the same length as p // int expectedLength = (p.bitLength() + 7) / 8; byte[] tmp = r.toByteArray(); if (tmp.length == expectedLength) { return tmp; } if (tmp[0] == 0 && tmp.length == expectedLength + 1) { byte[] rv = new byte[tmp.length - 1]; System.arraycopy(tmp, 1, rv, 0, rv.length); return rv; } // tmp must be shorter than expectedLength // pad to the left with zeros. byte[] rv = new byte[expectedLength]; System.arraycopy(tmp, 0, rv, rv.length - tmp.length, tmp.length); return rv; } protected Key engineDoPhase( Key key, boolean lastPhase) throws InvalidKeyException, IllegalStateException { if (x == null) { throw new IllegalStateException("Diffie-Hellman not initialised."); } if (!(key instanceof DHPublicKey)) { throw new InvalidKeyException("DHKeyAgreement doPhase requires DHPublicKey"); } DHPublicKey pubKey = (DHPublicKey)key; if (!pubKey.getParams().getG().equals(g) || !pubKey.getParams().getP().equals(p)) { throw new InvalidKeyException("DHPublicKey not for this KeyAgreement!"); } if (lastPhase) { result = ((DHPublicKey)key).getY().modPow(x, p); return null; } else { result = ((DHPublicKey)key).getY().modPow(x, p); } return new BCDHPublicKey(result, pubKey.getParams()); } protected byte[] engineGenerateSecret() throws IllegalStateException { if (x == null) { throw new IllegalStateException("Diffie-Hellman not initialised."); } return super.engineGenerateSecret(); } protected int engineGenerateSecret( byte[] sharedSecret, int offset) throws IllegalStateException, ShortBufferException { if (x == null) { throw new IllegalStateException("Diffie-Hellman not initialised."); } return super.engineGenerateSecret(sharedSecret, offset); } protected SecretKey engineGenerateSecret( String algorithm) throws NoSuchAlgorithmException { if (x == null) { throw new IllegalStateException("Diffie-Hellman not initialised."); } byte[] res = bigIntToBytes(result); // for JSSE compatibility if (algorithm.equals("TlsPremasterSecret")) { return new SecretKeySpec(trimZeroes(res), algorithm); } return super.engineGenerateSecret(algorithm); } protected void engineInit( Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { if (!(key instanceof DHPrivateKey)) { throw new InvalidKeyException("DHKeyAgreement requires DHPrivateKey for initialisation"); } DHPrivateKey privKey = (DHPrivateKey)key; if (params != null) { if (params instanceof DHParameterSpec) // p, g override. { DHParameterSpec p = (DHParameterSpec)params; this.p = p.getP(); this.g = p.getG(); } else if (params instanceof UserKeyingMaterialSpec) { this.p = privKey.getParams().getP(); this.g = privKey.getParams().getG(); this.ukmParameters = ((UserKeyingMaterialSpec)params).getUserKeyingMaterial(); } else { throw new InvalidAlgorithmParameterException("DHKeyAgreement only accepts DHParameterSpec"); } } else { this.p = privKey.getParams().getP(); this.g = privKey.getParams().getG(); } this.x = this.result = privKey.getX(); } protected void engineInit( Key key, SecureRandom random) throws InvalidKeyException { if (!(key instanceof DHPrivateKey)) { throw new InvalidKeyException("DHKeyAgreement requires DHPrivateKey"); } DHPrivateKey privKey = (DHPrivateKey)key; this.p = privKey.getParams().getP(); this.g = privKey.getParams().getG(); this.x = this.result = privKey.getX(); } protected byte[] calcSecret() { return bigIntToBytes(result); } public static class DHwithRFC2631KDF extends KeyAgreementSpi { public DHwithRFC2631KDF() { super("DHwithRFC2631KDF", new DHKEKGenerator(new SHA1Digest())); } } }
./CrossVul/dataset_final_sorted/CWE-320/java/bad_4763_4
crossvul-java_data_good_4763_2
package org.bouncycastle.crypto.engines; import java.io.ByteArrayInputStream; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.crypto.BasicAgreement; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DerivationFunction; import org.bouncycastle.crypto.EphemeralKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.KeyParser; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.generators.EphemeralKeyPairGenerator; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.IESParameters; import org.bouncycastle.crypto.params.IESWithCipherParameters; import org.bouncycastle.crypto.params.KDFParameters; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Pack; /** * Support class for constructing integrated encryption ciphers * for doing basic message exchanges on top of key agreement ciphers. * Follows the description given in IEEE Std 1363a. */ public class IESEngine { BasicAgreement agree; DerivationFunction kdf; Mac mac; BufferedBlockCipher cipher; byte[] macBuf; boolean forEncryption; CipherParameters privParam, pubParam; IESParameters param; byte[] V; private EphemeralKeyPairGenerator keyPairGenerator; private KeyParser keyParser; private byte[] IV; /** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message */ public IESEngine( BasicAgreement agree, DerivationFunction kdf, Mac mac) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.getMacSize()]; this.cipher = null; } /** * Set up for use in conjunction with a block cipher to handle the * message.It is <b>strongly</b> recommended that the cipher is not in ECB mode. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param cipher the cipher to used for encrypting the message */ public IESEngine( BasicAgreement agree, DerivationFunction kdf, Mac mac, BufferedBlockCipher cipher) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.getMacSize()]; this.cipher = cipher; } /** * Initialise the encryptor. * * @param forEncryption whether or not this is encryption/decryption. * @param privParam our private key parameters * @param pubParam the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. */ public void init( boolean forEncryption, CipherParameters privParam, CipherParameters pubParam, CipherParameters params) { this.forEncryption = forEncryption; this.privParam = privParam; this.pubParam = pubParam; this.V = new byte[0]; extractParams(params); } /** * Initialise the decryptor. * * @param publicKey the recipient's/sender's public key parameters * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param ephemeralKeyPairGenerator the ephemeral key pair generator to use. */ public void init(AsymmetricKeyParameter publicKey, CipherParameters params, EphemeralKeyPairGenerator ephemeralKeyPairGenerator) { this.forEncryption = true; this.pubParam = publicKey; this.keyPairGenerator = ephemeralKeyPairGenerator; extractParams(params); } /** * Initialise the encryptor. * * @param privateKey the recipient's private key. * @param params encoding and derivation parameters, may be wrapped to include an IV for an underlying block cipher. * @param publicKeyParser the parser for reading the ephemeral public key. */ public void init(AsymmetricKeyParameter privateKey, CipherParameters params, KeyParser publicKeyParser) { this.forEncryption = false; this.privParam = privateKey; this.keyParser = publicKeyParser; extractParams(params); } private void extractParams(CipherParameters params) { if (params instanceof ParametersWithIV) { this.IV = ((ParametersWithIV)params).getIV(); this.param = (IESParameters)((ParametersWithIV)params).getParameters(); } else { this.IV = null; this.param = (IESParameters)params; } } public BufferedBlockCipher getCipher() { return cipher; } public Mac getMac() { return mac; } private byte[] encryptBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { byte[] C = null, K = null, K1 = null, K2 = null; int len; if (cipher == null) { // Streaming mode. K1 = new byte[inLen]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); if (V.length != 0) { System.arraycopy(K, 0, K2, 0, K2.length); System.arraycopy(K, K2.length, K1, 0, K1.length); } else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, inLen, K2, 0, K2.length); } C = new byte[inLen]; for (int i = 0; i != inLen; i++) { C[i] = (byte)(in[inOff + i] ^ K1[i]); } len = inLen; } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If iv provided use it to initialise the cipher if (IV != null) { cipher.init(true, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(true, new KeyParameter(K1)); } C = new byte[cipher.getOutputSize(inLen)]; len = cipher.processBytes(in, inOff, inLen, C, 0); len += cipher.doFinal(C, len); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); byte[] L2 = null; if (V.length != 0) { L2 = getLengthTag(P2); } // Apply the MAC. byte[] T = new byte[mac.getMacSize()]; mac.init(new KeyParameter(K2)); mac.update(C, 0, C.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0) { mac.update(L2, 0, L2.length); } mac.doFinal(T, 0); // Output the triple (V,C,T). byte[] Output = new byte[V.length + len + T.length]; System.arraycopy(V, 0, Output, 0, V.length); System.arraycopy(C, 0, Output, V.length, len); System.arraycopy(T, 0, Output, V.length + len, T.length); return Output; } private byte[] decryptBlock( byte[] in_enc, int inOff, int inLen) throws InvalidCipherTextException { byte[] M, K, K1, K2; int len = 0; // Ensure that the length of the input is greater than the MAC in bytes if (inLen < V.length + mac.getMacSize()) { throw new InvalidCipherTextException("Length of input must be greater than the MAC and V combined"); } // note order is important: set up keys, do simple encryptions, check mac, do final encryption. if (cipher == null) { // Streaming mode. K1 = new byte[inLen - V.length - mac.getMacSize()]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); if (V.length != 0) { System.arraycopy(K, 0, K2, 0, K2.length); System.arraycopy(K, K2.length, K1, 0, K1.length); } else { System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); } // process the message M = new byte[K1.length]; for (int i = 0; i != K1.length; i++) { M[i] = (byte)(in_enc[inOff + V.length + i] ^ K1[i]); } } else { // Block cipher mode. K1 = new byte[((IESWithCipherParameters)param).getCipherKeySize() / 8]; K2 = new byte[param.getMacKeySize() / 8]; K = new byte[K1.length + K2.length]; kdf.generateBytes(K, 0, K.length); System.arraycopy(K, 0, K1, 0, K1.length); System.arraycopy(K, K1.length, K2, 0, K2.length); // If IV provide use it to initialize the cipher if (IV != null) { cipher.init(false, new ParametersWithIV(new KeyParameter(K1), IV)); } else { cipher.init(false, new KeyParameter(K1)); } M = new byte[cipher.getOutputSize(inLen - V.length - mac.getMacSize())]; // do initial processing len = cipher.processBytes(in_enc, inOff + V.length, inLen - V.length - mac.getMacSize(), M, 0); } // Convert the length of the encoding vector into a byte array. byte[] P2 = param.getEncodingV(); byte[] L2 = null; if (V.length != 0) { L2 = getLengthTag(P2); } // Verify the MAC. int end = inOff + inLen; byte[] T1 = Arrays.copyOfRange(in_enc, end - mac.getMacSize(), end); byte[] T2 = new byte[T1.length]; mac.init(new KeyParameter(K2)); mac.update(in_enc, inOff + V.length, inLen - V.length - T2.length); if (P2 != null) { mac.update(P2, 0, P2.length); } if (V.length != 0) { mac.update(L2, 0, L2.length); } mac.doFinal(T2, 0); if (!Arrays.constantTimeAreEqual(T1, T2)) { throw new InvalidCipherTextException("invalid MAC"); } if (cipher == null) { return M; } else { len += cipher.doFinal(M, len); return Arrays.copyOfRange(M, 0, len); } } public byte[] processBlock( byte[] in, int inOff, int inLen) throws InvalidCipherTextException { if (forEncryption) { if (keyPairGenerator != null) { EphemeralKeyPair ephKeyPair = keyPairGenerator.generate(); this.privParam = ephKeyPair.getKeyPair().getPrivate(); this.V = ephKeyPair.getEncodedPublicKey(); } } else { if (keyParser != null) { ByteArrayInputStream bIn = new ByteArrayInputStream(in, inOff, inLen); try { this.pubParam = keyParser.readKey(bIn); } catch (IOException e) { throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.getMessage(), e); } catch (IllegalArgumentException e) { throw new InvalidCipherTextException("unable to recover ephemeral public key: " + e.getMessage(), e); } int encLength = (inLen - bIn.available()); this.V = Arrays.copyOfRange(in, inOff, inOff + encLength); } } // Compute the common value and convert to byte array. agree.init(privParam); BigInteger z = agree.calculateAgreement(pubParam); byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z); // Create input to KDF. if (V.length != 0) { byte[] VZ = Arrays.concatenate(V, Z); Arrays.fill(Z, (byte)0); Z = VZ; } try { // Initialise the KDF. KDFParameters kdfParam = new KDFParameters(Z, param.getDerivationV()); kdf.init(kdfParam); return forEncryption ? encryptBlock(in, inOff, inLen) : decryptBlock(in, inOff, inLen); } finally { Arrays.fill(Z, (byte)0); } } // as described in Shroup's paper and P1363a protected byte[] getLengthTag(byte[] p2) { byte[] L2 = new byte[8]; if (p2 != null) { Pack.longToBigEndian(p2.length * 8L, L2, 0); } return L2; } }
./CrossVul/dataset_final_sorted/CWE-320/java/good_4763_2
crossvul-java_data_good_4763_0
package org.bouncycastle.crypto.agreement; import java.math.BigInteger; import java.security.SecureRandom; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.generators.DHKeyPairGenerator; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.DHKeyGenerationParameters; import org.bouncycastle.crypto.params.DHParameters; import org.bouncycastle.crypto.params.DHPrivateKeyParameters; import org.bouncycastle.crypto.params.DHPublicKeyParameters; import org.bouncycastle.crypto.params.ParametersWithRandom; /** * a Diffie-Hellman key exchange engine. * <p> * note: This uses MTI/A0 key agreement in order to make the key agreement * secure against passive attacks. If you're doing Diffie-Hellman and both * parties have long term public keys you should look at using this. For * further information have a look at RFC 2631. * <p> * It's possible to extend this to more than two parties as well, for the moment * that is left as an exercise for the reader. */ public class DHAgreement { private static final BigInteger ONE = BigInteger.valueOf(1); private DHPrivateKeyParameters key; private DHParameters dhParams; private BigInteger privateValue; private SecureRandom random; public void init( CipherParameters param) { AsymmetricKeyParameter kParam; if (param instanceof ParametersWithRandom) { ParametersWithRandom rParam = (ParametersWithRandom)param; this.random = rParam.getRandom(); kParam = (AsymmetricKeyParameter)rParam.getParameters(); } else { this.random = new SecureRandom(); kParam = (AsymmetricKeyParameter)param; } if (!(kParam instanceof DHPrivateKeyParameters)) { throw new IllegalArgumentException("DHEngine expects DHPrivateKeyParameters"); } this.key = (DHPrivateKeyParameters)kParam; this.dhParams = key.getParameters(); } /** * calculate our initial message. */ public BigInteger calculateMessage() { DHKeyPairGenerator dhGen = new DHKeyPairGenerator(); dhGen.init(new DHKeyGenerationParameters(random, dhParams)); AsymmetricCipherKeyPair dhPair = dhGen.generateKeyPair(); this.privateValue = ((DHPrivateKeyParameters)dhPair.getPrivate()).getX(); return ((DHPublicKeyParameters)dhPair.getPublic()).getY(); } /** * given a message from a given party and the corresponding public key, * calculate the next message in the agreement sequence. In this case * this will represent the shared secret. */ public BigInteger calculateAgreement( DHPublicKeyParameters pub, BigInteger message) { if (!pub.getParameters().equals(dhParams)) { throw new IllegalArgumentException("Diffie-Hellman public key has wrong parameters."); } BigInteger p = dhParams.getP(); BigInteger result = pub.getY().modPow(privateValue, p); if (result.compareTo(ONE) == 0) { throw new IllegalStateException("Shared key can't be 1"); } return message.modPow(key.getX(), p).multiply(result).mod(p); } }
./CrossVul/dataset_final_sorted/CWE-320/java/good_4763_0
crossvul-java_data_bad_1997_0
/******************************************************************************* * Copyright 2018 The MIT Internet Trust Consortium * * Portions copyright 2011-2013 The MITRE Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /** * */ package org.mitre.oauth2.web; import static org.mitre.openid.connect.request.ConnectRequestParameters.PROMPT; import static org.mitre.openid.connect.request.ConnectRequestParameters.PROMPT_SEPARATOR; import java.net.URISyntaxException; import java.security.Principal; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.http.client.utils.URIBuilder; import org.mitre.oauth2.model.ClientDetailsEntity; import org.mitre.oauth2.model.SystemScope; import org.mitre.oauth2.service.ClientDetailsEntityService; import org.mitre.oauth2.service.SystemScopeService; import org.mitre.openid.connect.model.UserInfo; import org.mitre.openid.connect.service.ScopeClaimTranslationService; import org.mitre.openid.connect.service.StatsService; import org.mitre.openid.connect.service.UserInfoService; import org.mitre.openid.connect.view.HttpCodeView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; import org.springframework.security.oauth2.provider.AuthorizationRequest; import org.springframework.security.oauth2.provider.endpoint.RedirectResolver; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Sets; import com.google.gson.JsonObject; /** * @author jricher * */ @Controller @SessionAttributes("authorizationRequest") public class OAuthConfirmationController { @Autowired private ClientDetailsEntityService clientService; @Autowired private SystemScopeService scopeService; @Autowired private ScopeClaimTranslationService scopeClaimTranslationService; @Autowired private UserInfoService userInfoService; @Autowired private StatsService statsService; @Autowired private RedirectResolver redirectResolver; /** * Logger for this class */ private static final Logger logger = LoggerFactory.getLogger(OAuthConfirmationController.class); public OAuthConfirmationController() { } public OAuthConfirmationController(ClientDetailsEntityService clientService) { this.clientService = clientService; } @PreAuthorize("hasRole('ROLE_USER')") @RequestMapping("/oauth/confirm_access") public String confimAccess(Map<String, Object> model, @ModelAttribute("authorizationRequest") AuthorizationRequest authRequest, Principal p) { // Check the "prompt" parameter to see if we need to do special processing String prompt = (String)authRequest.getExtensions().get(PROMPT); List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt)); ClientDetailsEntity client = null; try { client = clientService.loadClientByClientId(authRequest.getClientId()); } catch (OAuth2Exception e) { logger.error("confirmAccess: OAuth2Exception was thrown when attempting to load client", e); model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } catch (IllegalArgumentException e) { logger.error("confirmAccess: IllegalArgumentException was thrown when attempting to load client", e); model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } if (client == null) { logger.error("confirmAccess: could not find client " + authRequest.getClientId()); model.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } if (prompts.contains("none")) { // if we've got a redirect URI then we'll send it String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client); try { URIBuilder uriBuilder = new URIBuilder(url); uriBuilder.addParameter("error", "interaction_required"); if (!Strings.isNullOrEmpty(authRequest.getState())) { uriBuilder.addParameter("state", authRequest.getState()); // copy the state parameter if one was given } return "redirect:" + uriBuilder.toString(); } catch (URISyntaxException e) { logger.error("Can't build redirect URI for prompt=none, sending error instead", e); model.put("code", HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } } model.put("auth_request", authRequest); model.put("client", client); String redirect_uri = authRequest.getRedirectUri(); model.put("redirect_uri", redirect_uri); // pre-process the scopes Set<SystemScope> scopes = scopeService.fromStrings(authRequest.getScope()); Set<SystemScope> sortedScopes = new LinkedHashSet<>(scopes.size()); Set<SystemScope> systemScopes = scopeService.getAll(); // sort scopes for display based on the inherent order of system scopes for (SystemScope s : systemScopes) { if (scopes.contains(s)) { sortedScopes.add(s); } } // add in any scopes that aren't system scopes to the end of the list sortedScopes.addAll(Sets.difference(scopes, systemScopes)); model.put("scopes", sortedScopes); // get the userinfo claims for each scope UserInfo user = userInfoService.getByUsername(p.getName()); Map<String, Map<String, String>> claimsForScopes = new HashMap<>(); if (user != null) { JsonObject userJson = user.toJson(); for (SystemScope systemScope : sortedScopes) { Map<String, String> claimValues = new HashMap<>(); Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue()); for (String claim : claims) { if (userJson.has(claim) && userJson.get(claim).isJsonPrimitive()) { // TODO: this skips the address claim claimValues.put(claim, userJson.get(claim).getAsString()); } } claimsForScopes.put(systemScope.getValue(), claimValues); } } model.put("claims", claimsForScopes); // client stats Integer count = statsService.getCountForClientId(client.getClientId()).getApprovedSiteCount(); model.put("count", count); // contacts if (client.getContacts() != null) { String contacts = Joiner.on(", ").join(client.getContacts()); model.put("contacts", contacts); } // if the client is over a week old and has more than one registration, don't give such a big warning // instead, tag as "Generally Recognized As Safe" (gras) Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000)); if (count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek)) { model.put("gras", true); } else { model.put("gras", false); } return "approve"; } /** * @return the clientService */ public ClientDetailsEntityService getClientService() { return clientService; } /** * @param clientService the clientService to set */ public void setClientService(ClientDetailsEntityService clientService) { this.clientService = clientService; } }
./CrossVul/dataset_final_sorted/CWE-915/java/bad_1997_0
crossvul-java_data_good_1997_0
/******************************************************************************* * Copyright 2018 The MIT Internet Trust Consortium * * Portions copyright 2011-2013 The MITRE Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /** * */ package org.mitre.oauth2.web; import static org.mitre.openid.connect.request.ConnectRequestParameters.PROMPT; import static org.mitre.openid.connect.request.ConnectRequestParameters.PROMPT_SEPARATOR; import java.net.URISyntaxException; import java.security.Principal; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.http.client.utils.URIBuilder; import org.mitre.oauth2.model.ClientDetailsEntity; import org.mitre.oauth2.model.SystemScope; import org.mitre.oauth2.service.ClientDetailsEntityService; import org.mitre.oauth2.service.SystemScopeService; import org.mitre.openid.connect.model.UserInfo; import org.mitre.openid.connect.service.ScopeClaimTranslationService; import org.mitre.openid.connect.service.StatsService; import org.mitre.openid.connect.service.UserInfoService; import org.mitre.openid.connect.view.HttpCodeView; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.oauth2.common.exceptions.OAuth2Exception; import org.springframework.security.oauth2.provider.AuthorizationRequest; import org.springframework.security.oauth2.provider.endpoint.RedirectResolver; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Sets; import com.google.gson.JsonObject; /** * @author jricher * */ @Controller @SessionAttributes("authorizationRequest") public class OAuthConfirmationController { @Autowired private ClientDetailsEntityService clientService; @Autowired private SystemScopeService scopeService; @Autowired private ScopeClaimTranslationService scopeClaimTranslationService; @Autowired private UserInfoService userInfoService; @Autowired private StatsService statsService; @Autowired private RedirectResolver redirectResolver; /** * Logger for this class */ private static final Logger logger = LoggerFactory.getLogger(OAuthConfirmationController.class); public OAuthConfirmationController() { } public OAuthConfirmationController(ClientDetailsEntityService clientService) { this.clientService = clientService; } @PreAuthorize("hasRole('ROLE_USER')") @RequestMapping("/oauth/confirm_access") public String confirmAccess(Map<String, Object> model, Principal p) { AuthorizationRequest authRequest = (AuthorizationRequest) model.get("authorizationRequest"); // Check the "prompt" parameter to see if we need to do special processing String prompt = (String)authRequest.getExtensions().get(PROMPT); List<String> prompts = Splitter.on(PROMPT_SEPARATOR).splitToList(Strings.nullToEmpty(prompt)); ClientDetailsEntity client = null; try { client = clientService.loadClientByClientId(authRequest.getClientId()); } catch (OAuth2Exception e) { logger.error("confirmAccess: OAuth2Exception was thrown when attempting to load client", e); model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } catch (IllegalArgumentException e) { logger.error("confirmAccess: IllegalArgumentException was thrown when attempting to load client", e); model.put(HttpCodeView.CODE, HttpStatus.BAD_REQUEST); return HttpCodeView.VIEWNAME; } if (client == null) { logger.error("confirmAccess: could not find client " + authRequest.getClientId()); model.put(HttpCodeView.CODE, HttpStatus.NOT_FOUND); return HttpCodeView.VIEWNAME; } if (prompts.contains("none")) { // if we've got a redirect URI then we'll send it String url = redirectResolver.resolveRedirect(authRequest.getRedirectUri(), client); try { URIBuilder uriBuilder = new URIBuilder(url); uriBuilder.addParameter("error", "interaction_required"); if (!Strings.isNullOrEmpty(authRequest.getState())) { uriBuilder.addParameter("state", authRequest.getState()); // copy the state parameter if one was given } return "redirect:" + uriBuilder.toString(); } catch (URISyntaxException e) { logger.error("Can't build redirect URI for prompt=none, sending error instead", e); model.put("code", HttpStatus.FORBIDDEN); return HttpCodeView.VIEWNAME; } } model.put("auth_request", authRequest); model.put("client", client); String redirect_uri = authRequest.getRedirectUri(); model.put("redirect_uri", redirect_uri); // pre-process the scopes Set<SystemScope> scopes = scopeService.fromStrings(authRequest.getScope()); Set<SystemScope> sortedScopes = new LinkedHashSet<>(scopes.size()); Set<SystemScope> systemScopes = scopeService.getAll(); // sort scopes for display based on the inherent order of system scopes for (SystemScope s : systemScopes) { if (scopes.contains(s)) { sortedScopes.add(s); } } // add in any scopes that aren't system scopes to the end of the list sortedScopes.addAll(Sets.difference(scopes, systemScopes)); model.put("scopes", sortedScopes); // get the userinfo claims for each scope UserInfo user = userInfoService.getByUsername(p.getName()); Map<String, Map<String, String>> claimsForScopes = new HashMap<>(); if (user != null) { JsonObject userJson = user.toJson(); for (SystemScope systemScope : sortedScopes) { Map<String, String> claimValues = new HashMap<>(); Set<String> claims = scopeClaimTranslationService.getClaimsForScope(systemScope.getValue()); for (String claim : claims) { if (userJson.has(claim) && userJson.get(claim).isJsonPrimitive()) { // TODO: this skips the address claim claimValues.put(claim, userJson.get(claim).getAsString()); } } claimsForScopes.put(systemScope.getValue(), claimValues); } } model.put("claims", claimsForScopes); // client stats Integer count = statsService.getCountForClientId(client.getClientId()).getApprovedSiteCount(); model.put("count", count); // contacts if (client.getContacts() != null) { String contacts = Joiner.on(", ").join(client.getContacts()); model.put("contacts", contacts); } // if the client is over a week old and has more than one registration, don't give such a big warning // instead, tag as "Generally Recognized As Safe" (gras) Date lastWeek = new Date(System.currentTimeMillis() - (60 * 60 * 24 * 7 * 1000)); if (count > 1 && client.getCreatedAt() != null && client.getCreatedAt().before(lastWeek)) { model.put("gras", true); } else { model.put("gras", false); } return "approve"; } /** * @return the clientService */ public ClientDetailsEntityService getClientService() { return clientService; } /** * @param clientService the clientService to set */ public void setClientService(ClientDetailsEntityService clientService) { this.clientService = clientService; } }
./CrossVul/dataset_final_sorted/CWE-915/java/good_1997_0
crossvul-java_data_bad_434_4
// © 2017 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License package com.ibm.icu.impl.number; import java.math.BigDecimal; import java.math.BigInteger; /** * A DecimalQuantity with internal storage as a 64-bit BCD, with fallback to a byte array for numbers * that don't fit into the standard BCD. */ public final class DecimalQuantity_DualStorageBCD extends DecimalQuantity_AbstractBCD { /** * The BCD of the 16 digits of the number represented by this object. Every 4 bits of the long map to * one digit. For example, the number "12345" in BCD is "0x12345". * * <p> * Whenever bcd changes internally, {@link #compact()} must be called, except in special cases like * setting the digit to zero. */ private byte[] bcdBytes; private long bcdLong = 0L; private boolean usingBytes = false; @Override public int maxRepresentableDigits() { return Integer.MAX_VALUE; } public DecimalQuantity_DualStorageBCD() { setBcdToZero(); flags = 0; } public DecimalQuantity_DualStorageBCD(long input) { setToLong(input); } public DecimalQuantity_DualStorageBCD(int input) { setToInt(input); } public DecimalQuantity_DualStorageBCD(double input) { setToDouble(input); } public DecimalQuantity_DualStorageBCD(BigInteger input) { setToBigInteger(input); } public DecimalQuantity_DualStorageBCD(BigDecimal input) { setToBigDecimal(input); } public DecimalQuantity_DualStorageBCD(DecimalQuantity_DualStorageBCD other) { copyFrom(other); } public DecimalQuantity_DualStorageBCD(Number number) { // NOTE: Number type expansion happens both here // and in NumberFormat.java if (number instanceof Long) { setToLong(number.longValue()); } else if (number instanceof Integer) { setToInt(number.intValue()); } else if (number instanceof Float) { setToDouble(number.doubleValue()); } else if (number instanceof Double) { setToDouble(number.doubleValue()); } else if (number instanceof BigInteger) { setToBigInteger((BigInteger) number); } else if (number instanceof BigDecimal) { setToBigDecimal((BigDecimal) number); } else if (number instanceof com.ibm.icu.math.BigDecimal) { setToBigDecimal(((com.ibm.icu.math.BigDecimal) number).toBigDecimal()); } else { throw new IllegalArgumentException( "Number is of an unsupported type: " + number.getClass().getName()); } } @Override public DecimalQuantity createCopy() { return new DecimalQuantity_DualStorageBCD(this); } @Override protected byte getDigitPos(int position) { if (usingBytes) { if (position < 0 || position >= precision) return 0; return bcdBytes[position]; } else { if (position < 0 || position >= 16) return 0; return (byte) ((bcdLong >>> (position * 4)) & 0xf); } } @Override protected void setDigitPos(int position, byte value) { assert position >= 0; if (usingBytes) { ensureCapacity(position + 1); bcdBytes[position] = value; } else if (position >= 16) { switchStorage(); ensureCapacity(position + 1); bcdBytes[position] = value; } else { int shift = position * 4; bcdLong = bcdLong & ~(0xfL << shift) | ((long) value << shift); } } @Override protected void shiftLeft(int numDigits) { if (!usingBytes && precision + numDigits > 16) { switchStorage(); } if (usingBytes) { ensureCapacity(precision + numDigits); int i = precision + numDigits - 1; for (; i >= numDigits; i--) { bcdBytes[i] = bcdBytes[i - numDigits]; } for (; i >= 0; i--) { bcdBytes[i] = 0; } } else { bcdLong <<= (numDigits * 4); } scale -= numDigits; precision += numDigits; } @Override protected void shiftRight(int numDigits) { if (usingBytes) { int i = 0; for (; i < precision - numDigits; i++) { bcdBytes[i] = bcdBytes[i + numDigits]; } for (; i < precision; i++) { bcdBytes[i] = 0; } } else { bcdLong >>>= (numDigits * 4); } scale += numDigits; precision -= numDigits; } @Override protected void setBcdToZero() { if (usingBytes) { bcdBytes = null; usingBytes = false; } bcdLong = 0L; scale = 0; precision = 0; isApproximate = false; origDouble = 0; origDelta = 0; } @Override protected void readIntToBcd(int n) { assert n != 0; // ints always fit inside the long implementation. long result = 0L; int i = 16; for (; n != 0; n /= 10, i--) { result = (result >>> 4) + (((long) n % 10) << 60); } assert !usingBytes; bcdLong = result >>> (i * 4); scale = 0; precision = 16 - i; } @Override protected void readLongToBcd(long n) { assert n != 0; if (n >= 10000000000000000L) { ensureCapacity(); int i = 0; for (; n != 0L; n /= 10L, i++) { bcdBytes[i] = (byte) (n % 10); } assert usingBytes; scale = 0; precision = i; } else { long result = 0L; int i = 16; for (; n != 0L; n /= 10L, i--) { result = (result >>> 4) + ((n % 10) << 60); } assert i >= 0; assert !usingBytes; bcdLong = result >>> (i * 4); scale = 0; precision = 16 - i; } } @Override protected void readBigIntegerToBcd(BigInteger n) { assert n.signum() != 0; ensureCapacity(); // allocate initial byte array int i = 0; for (; n.signum() != 0; i++) { BigInteger[] temp = n.divideAndRemainder(BigInteger.TEN); ensureCapacity(i + 1); bcdBytes[i] = temp[1].byteValue(); n = temp[0]; } scale = 0; precision = i; } @Override protected BigDecimal bcdToBigDecimal() { if (usingBytes) { // Converting to a string here is faster than doing BigInteger/BigDecimal arithmetic. BigDecimal result = new BigDecimal(toNumberString()); if (isNegative()) { result = result.negate(); } return result; } else { long tempLong = 0L; for (int shift = (precision - 1); shift >= 0; shift--) { tempLong = tempLong * 10 + getDigitPos(shift); } BigDecimal result = BigDecimal.valueOf(tempLong); result = result.scaleByPowerOfTen(scale); if (isNegative()) result = result.negate(); return result; } } @Override protected void compact() { if (usingBytes) { int delta = 0; for (; delta < precision && bcdBytes[delta] == 0; delta++) ; if (delta == precision) { // Number is zero setBcdToZero(); return; } else { // Remove trailing zeros shiftRight(delta); } // Compute precision int leading = precision - 1; for (; leading >= 0 && bcdBytes[leading] == 0; leading--) ; precision = leading + 1; // Switch storage mechanism if possible if (precision <= 16) { switchStorage(); } } else { if (bcdLong == 0L) { // Number is zero setBcdToZero(); return; } // Compact the number (remove trailing zeros) int delta = Long.numberOfTrailingZeros(bcdLong) / 4; bcdLong >>>= delta * 4; scale += delta; // Compute precision precision = 16 - (Long.numberOfLeadingZeros(bcdLong) / 4); } } /** Ensure that a byte array of at least 40 digits is allocated. */ private void ensureCapacity() { ensureCapacity(40); } private void ensureCapacity(int capacity) { if (capacity == 0) return; int oldCapacity = usingBytes ? bcdBytes.length : 0; if (!usingBytes) { bcdBytes = new byte[capacity]; } else if (oldCapacity < capacity) { byte[] bcd1 = new byte[capacity * 2]; System.arraycopy(bcdBytes, 0, bcd1, 0, oldCapacity); bcdBytes = bcd1; } usingBytes = true; } /** Switches the internal storage mechanism between the 64-bit long and the byte array. */ private void switchStorage() { if (usingBytes) { // Change from bytes to long bcdLong = 0L; for (int i = precision - 1; i >= 0; i--) { bcdLong <<= 4; bcdLong |= bcdBytes[i]; } bcdBytes = null; usingBytes = false; } else { // Change from long to bytes ensureCapacity(); for (int i = 0; i < precision; i++) { bcdBytes[i] = (byte) (bcdLong & 0xf); bcdLong >>>= 4; } assert usingBytes; } } @Override protected void copyBcdFrom(DecimalQuantity _other) { DecimalQuantity_DualStorageBCD other = (DecimalQuantity_DualStorageBCD) _other; setBcdToZero(); if (other.usingBytes) { ensureCapacity(other.precision); System.arraycopy(other.bcdBytes, 0, bcdBytes, 0, other.precision); } else { bcdLong = other.bcdLong; } } /** * Checks whether the bytes stored in this instance are all valid. For internal unit testing only. * * @return An error message if this instance is invalid, or null if this instance is healthy. * @internal * @deprecated This API is for ICU internal use only. */ @Deprecated public String checkHealth() { if (usingBytes) { if (bcdLong != 0) return "Value in bcdLong but we are in byte mode"; if (precision == 0) return "Zero precision but we are in byte mode"; if (precision > bcdBytes.length) return "Precision exceeds length of byte array"; if (getDigitPos(precision - 1) == 0) return "Most significant digit is zero in byte mode"; if (getDigitPos(0) == 0) return "Least significant digit is zero in long mode"; for (int i = 0; i < precision; i++) { if (getDigitPos(i) >= 10) return "Digit exceeding 10 in byte array"; if (getDigitPos(i) < 0) return "Digit below 0 in byte array"; } for (int i = precision; i < bcdBytes.length; i++) { if (getDigitPos(i) != 0) return "Nonzero digits outside of range in byte array"; } } else { if (bcdBytes != null) { for (int i = 0; i < bcdBytes.length; i++) { if (bcdBytes[i] != 0) return "Nonzero digits in byte array but we are in long mode"; } } if (precision == 0 && bcdLong != 0) return "Value in bcdLong even though precision is zero"; if (precision > 16) return "Precision exceeds length of long"; if (precision != 0 && getDigitPos(precision - 1) == 0) return "Most significant digit is zero in long mode"; if (precision != 0 && getDigitPos(0) == 0) return "Least significant digit is zero in long mode"; for (int i = 0; i < precision; i++) { if (getDigitPos(i) >= 10) return "Digit exceeding 10 in long"; if (getDigitPos(i) < 0) return "Digit below 0 in long (?!)"; } for (int i = precision; i < 16; i++) { if (getDigitPos(i) != 0) return "Nonzero digits outside of range in long"; } } return null; } /** * Checks whether this {@link DecimalQuantity_DualStorageBCD} is using its internal byte array * storage mechanism. * * @return true if an internal byte array is being used; false if a long is being used. * @internal * @deprecated This API is ICU internal only. */ @Deprecated public boolean isUsingBytes() { return usingBytes; } @Override public String toString() { return String.format("<DecimalQuantity %s:%d:%d:%s %s %s%s>", (lOptPos > 1000 ? "999" : String.valueOf(lOptPos)), lReqPos, rReqPos, (rOptPos < -1000 ? "-999" : String.valueOf(rOptPos)), (usingBytes ? "bytes" : "long"), (isNegative() ? "-" : ""), toNumberString()); } private String toNumberString() { StringBuilder sb = new StringBuilder(); if (usingBytes) { if (precision == 0) { sb.append('0'); } for (int i = precision - 1; i >= 0; i--) { sb.append(bcdBytes[i]); } } else { sb.append(Long.toHexString(bcdLong)); } sb.append("E"); sb.append(scale); return sb.toString(); } }
./CrossVul/dataset_final_sorted/CWE-190/java/bad_434_4
crossvul-java_data_bad_434_5
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License /* ******************************************************************************* * Copyright (C) 2001-2016, International Business Machines Corporation and * others. All Rights Reserved. ******************************************************************************* */ /** * Port From: ICU4C v1.8.1 : format : NumberFormatTest * Source File: $ICU4oot/source/test/intltest/numfmtst.cpp **/ package com.ibm.icu.dev.test.format; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigInteger; import java.math.RoundingMode; import java.text.AttributedCharacterIterator; import java.text.FieldPosition; import java.text.Format; import java.text.ParseException; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.Set; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.ibm.icu.dev.test.TestFmwk; import com.ibm.icu.dev.test.TestUtil; import com.ibm.icu.dev.test.format.IntlTestDecimalFormatAPIC.FieldContainer; import com.ibm.icu.dev.text.DecimalFormat_ICU58; import com.ibm.icu.impl.ICUConfig; import com.ibm.icu.impl.LocaleUtility; import com.ibm.icu.impl.data.ResourceReader; import com.ibm.icu.impl.data.TokenIterator; import com.ibm.icu.math.BigDecimal; import com.ibm.icu.math.MathContext; import com.ibm.icu.text.CompactDecimalFormat; import com.ibm.icu.text.CurrencyPluralInfo; import com.ibm.icu.text.DecimalFormat; import com.ibm.icu.text.DecimalFormatSymbols; import com.ibm.icu.text.DisplayContext; import com.ibm.icu.text.MeasureFormat; import com.ibm.icu.text.NumberFormat; import com.ibm.icu.text.NumberFormat.NumberFormatFactory; import com.ibm.icu.text.NumberFormat.SimpleNumberFormatFactory; import com.ibm.icu.text.NumberingSystem; import com.ibm.icu.text.RuleBasedNumberFormat; import com.ibm.icu.text.UnicodeSet; import com.ibm.icu.util.Currency; import com.ibm.icu.util.Currency.CurrencyUsage; import com.ibm.icu.util.CurrencyAmount; import com.ibm.icu.util.ULocale; @RunWith(JUnit4.class) public class NumberFormatTest extends TestFmwk { @Test public void TestRoundingScientific10542() { DecimalFormat format = new DecimalFormat("0.00E0"); int[] roundingModes = { BigDecimal.ROUND_CEILING, BigDecimal.ROUND_DOWN, BigDecimal.ROUND_FLOOR, BigDecimal.ROUND_HALF_DOWN, BigDecimal.ROUND_HALF_EVEN, BigDecimal.ROUND_HALF_UP, BigDecimal.ROUND_UP}; String[] descriptions = { "Round Ceiling", "Round Down", "Round Floor", "Round half down", "Round half even", "Round half up", "Round up"}; double[] values = {-0.003006, -0.003005, -0.003004, 0.003014, 0.003015, 0.003016}; // The order of these expected values correspond to the order of roundingModes and the order of values. String[][] expected = { {"-3.00E-3", "-3.00E-3", "-3.00E-3", "3.02E-3", "3.02E-3", "3.02E-3"}, {"-3.00E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.01E-3", "3.01E-3"}, {"-3.01E-3", "-3.01E-3", "-3.01E-3", "3.01E-3", "3.01E-3", "3.01E-3"}, {"-3.01E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.01E-3", "3.02E-3"}, {"-3.01E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.02E-3", "3.02E-3"}, {"-3.01E-3", "-3.01E-3", "-3.00E-3", "3.01E-3", "3.02E-3", "3.02E-3"}, {"-3.01E-3", "-3.01E-3", "-3.01E-3", "3.02E-3", "3.02E-3", "3.02E-3"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{-3006.0, -3005, -3004, 3014, 3015, 3016}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"-3.00E3", "-3.00E3", "-3.00E3", "3.02E3", "3.02E3", "3.02E3"}, {"-3.00E3", "-3.00E3", "-3.00E3", "3.01E3", "3.01E3", "3.01E3"}, {"-3.01E3", "-3.01E3", "-3.01E3", "3.01E3", "3.01E3", "3.01E3"}, {"-3.01E3", "-3.00E3", "-3.00E3", "3.01E3", "3.01E3", "3.02E3"}, {"-3.01E3", "-3.00E3", "-3.00E3", "3.01E3", "3.02E3", "3.02E3"}, {"-3.01E3", "-3.01E3", "-3.00E3", "3.01E3", "3.02E3", "3.02E3"}, {"-3.01E3", "-3.01E3", "-3.01E3", "3.02E3", "3.02E3", "3.02E3"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{0.0, -0.0}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{1e25, 1e25 + 1e15, 1e25 - 1e15}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"1.00E25", "1.01E25", "1.00E25"}, {"1.00E25", "1.00E25", "9.99E24"}, {"1.00E25", "1.00E25", "9.99E24"}, {"1.00E25", "1.00E25", "1.00E25"}, {"1.00E25", "1.00E25", "1.00E25"}, {"1.00E25", "1.00E25", "1.00E25"}, {"1.00E25", "1.01E25", "1.00E25"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{-1e25, -1e25 + 1e15, -1e25 - 1e15}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"-1.00E25", "-9.99E24", "-1.00E25"}, {"-1.00E25", "-9.99E24", "-1.00E25"}, {"-1.00E25", "-1.00E25", "-1.01E25"}, {"-1.00E25", "-1.00E25", "-1.00E25"}, {"-1.00E25", "-1.00E25", "-1.00E25"}, {"-1.00E25", "-1.00E25", "-1.00E25"}, {"-1.00E25", "-1.00E25", "-1.01E25"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{1e-25, 1e-25 + 1e-35, 1e-25 - 1e-35}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"1.00E-25", "1.01E-25", "1.00E-25"}, {"1.00E-25", "1.00E-25", "9.99E-26"}, {"1.00E-25", "1.00E-25", "9.99E-26"}, {"1.00E-25", "1.00E-25", "1.00E-25"}, {"1.00E-25", "1.00E-25", "1.00E-25"}, {"1.00E-25", "1.00E-25", "1.00E-25"}, {"1.00E-25", "1.01E-25", "1.00E-25"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{-1e-25, -1e-25 + 1e-35, -1e-25 - 1e-35}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"-1.00E-25", "-9.99E-26", "-1.00E-25"}, {"-1.00E-25", "-9.99E-26", "-1.00E-25"}, {"-1.00E-25", "-1.00E-25", "-1.01E-25"}, {"-1.00E-25", "-1.00E-25", "-1.00E-25"}, {"-1.00E-25", "-1.00E-25", "-1.00E-25"}, {"-1.00E-25", "-1.00E-25", "-1.00E-25"}, {"-1.00E-25", "-1.00E-25", "-1.01E-25"}}; verifyRounding(format, values, expected, roundingModes, descriptions); } private void verifyRounding(DecimalFormat format, double[] values, String[][] expected, int[] roundingModes, String[] descriptions) { for (int i = 0; i < roundingModes.length; i++) { format.setRoundingMode(roundingModes[i]); for (int j = 0; j < values.length; j++) { assertEquals(descriptions[i]+" " +values[j], expected[i][j], format.format(values[j])); } } } @Test public void Test10419RoundingWith0FractionDigits() { Object[][] data = new Object[][]{ {BigDecimal.ROUND_CEILING, 1.488, "2"}, {BigDecimal.ROUND_DOWN, 1.588, "1"}, {BigDecimal.ROUND_FLOOR, 1.588, "1"}, {BigDecimal.ROUND_HALF_DOWN, 1.5, "1"}, {BigDecimal.ROUND_HALF_EVEN, 2.5, "2"}, {BigDecimal.ROUND_HALF_UP, 2.5, "3"}, {BigDecimal.ROUND_UP, 1.5, "2"}, }; NumberFormat nff = NumberFormat.getNumberInstance(ULocale.ENGLISH); nff.setMaximumFractionDigits(0); for (Object[] item : data) { nff.setRoundingMode(((Integer) item[0]).intValue()); assertEquals("Test10419", item[2], nff.format(item[1])); } } @Test public void TestParseNegativeWithFaLocale() { DecimalFormat parser = (DecimalFormat) NumberFormat.getInstance(new ULocale("fa")); try { double value = parser.parse("-0,5").doubleValue(); assertEquals("Expect -0.5", -0.5, value); } catch (ParseException e) { TestFmwk.errln("Parsing -0.5 should have succeeded."); } } @Test public void TestParseNegativeWithAlternativeMinusSign() { DecimalFormat parser = (DecimalFormat) NumberFormat.getInstance(new ULocale("en")); try { double value = parser.parse("\u208B0.5").doubleValue(); assertEquals("Expect -0.5", -0.5, value); } catch (ParseException e) { TestFmwk.errln("Parsing -0.5 should have succeeded."); } } // Test various patterns @Test public void TestPatterns() { DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); final String pat[] = { "#.#", "#.", ".#", "#" }; int pat_length = pat.length; final String newpat[] = { "0.#", "0.", "#.0", "0" }; final String num[] = { "0", "0.", ".0", "0" }; for (int i=0; i<pat_length; ++i) { DecimalFormat fmt = new DecimalFormat(pat[i], sym); String newp = fmt.toPattern(); if (!newp.equals(newpat[i])) errln("FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] + "; " + newp + " seen instead"); String s = ((NumberFormat)fmt).format(0); if (!s.equals(num[i])) { errln("FAIL: Pattern " + pat[i] + " should format zero as " + num[i] + "; " + s + " seen instead"); logln("Min integer digits = " + fmt.getMinimumIntegerDigits()); } // BigInteger 0 - ticket#4731 s = ((NumberFormat)fmt).format(BigInteger.ZERO); if (!s.equals(num[i])) { errln("FAIL: Pattern " + pat[i] + " should format BigInteger zero as " + num[i] + "; " + s + " seen instead"); logln("Min integer digits = " + fmt.getMinimumIntegerDigits()); } } } // Test exponential pattern @Test public void TestExponential() { DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); final String pat[] = { "0.####E0", "00.000E00", "##0.######E000", "0.###E0;[0.###E0]" }; int pat_length = pat.length; double val[] = { 0.01234, 123456789, 1.23e300, -3.141592653e-271 }; int val_length = val.length; final String valFormat[] = { // 0.####E0 "1.234E-2", "1.2346E8", "1.23E300", "-3.1416E-271", // 00.000E00 "12.340E-03", "12.346E07", "12.300E299", "-31.416E-272", // ##0.######E000 "12.34E-003", "123.4568E006", "1.23E300", "-314.1593E-273", // 0.###E0;[0.###E0] "1.234E-2", "1.235E8", "1.23E300", "[3.142E-271]" }; /*double valParse[] = { 0.01234, 123460000, 1.23E300, -3.1416E-271, 0.01234, 123460000, 1.23E300, -3.1416E-271, 0.01234, 123456800, 1.23E300, -3.141593E-271, 0.01234, 123500000, 1.23E300, -3.142E-271, };*/ //The variable is never used int lval[] = { 0, -1, 1, 123456789 }; int lval_length = lval.length; final String lvalFormat[] = { // 0.####E0 "0E0", "-1E0", "1E0", "1.2346E8", // 00.000E00 "00.000E00", "-10.000E-01", "10.000E-01", "12.346E07", // ##0.######E000 "0E000", "-1E000", "1E000", "123.4568E006", // 0.###E0;[0.###E0] "0E0", "[1E0]", "1E0", "1.235E8" }; int lvalParse[] = { 0, -1, 1, 123460000, 0, -1, 1, 123460000, 0, -1, 1, 123456800, 0, -1, 1, 123500000, }; int ival = 0, ilval = 0; for (int p = 0; p < pat_length; ++p) { DecimalFormat fmt = new DecimalFormat(pat[p], sym); logln("Pattern \"" + pat[p] + "\" -toPattern-> \"" + fmt.toPattern() + "\""); int v; for (v = 0; v < val_length; ++v) { String s; s = ((NumberFormat) fmt).format(val[v]); logln(" " + val[v] + " -format-> " + s); if (!s.equals(valFormat[v + ival])) errln("FAIL: Expected " + valFormat[v + ival]); ParsePosition pos = new ParsePosition(0); double a = fmt.parse(s, pos).doubleValue(); if (pos.getIndex() == s.length()) { logln(" -parse-> " + Double.toString(a)); // Use epsilon comparison as necessary } else errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); } for (v = 0; v < lval_length; ++v) { String s; s = ((NumberFormat) fmt).format(lval[v]); logln(" " + lval[v] + "L -format-> " + s); if (!s.equals(lvalFormat[v + ilval])) errln("ERROR: Expected " + lvalFormat[v + ilval] + " Got: " + s); ParsePosition pos = new ParsePosition(0); long a = 0; Number A = fmt.parse(s, pos); if (A != null) { a = A.longValue(); if (pos.getIndex() == s.length()) { logln(" -parse-> " + a); if (a != lvalParse[v + ilval]) errln("FAIL: Expected " + lvalParse[v + ilval]); } else errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + Long.toString(a)); } else { errln("Fail to parse the string: " + s); } } ival += val_length; ilval += lval_length; } } // Test the handling of quotes @Test public void TestQuotes() { StringBuffer pat; DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); pat = new StringBuffer("a'fo''o'b#"); DecimalFormat fmt = new DecimalFormat(pat.toString(), sym); String s = ((NumberFormat)fmt).format(123); logln("Pattern \"" + pat + "\""); logln(" Format 123 . " + s); if (!s.equals("afo'ob123")) errln("FAIL: Expected afo'ob123"); s =""; pat = new StringBuffer("a''b#"); fmt = new DecimalFormat(pat.toString(), sym); s = ((NumberFormat)fmt).format(123); logln("Pattern \"" + pat + "\""); logln(" Format 123 . " + s); if (!s.equals("a'b123")) errln("FAIL: Expected a'b123"); } @Test public void TestParseCurrencyTrailingSymbol() { // see sun bug 4709840 NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.GERMANY); float val = 12345.67f; String str = fmt.format(val); logln("val: " + val + " str: " + str); try { Number num = fmt.parse(str); logln("num: " + num); } catch (ParseException e) { errln("parse of '" + str + "' threw exception: " + e); } } /** * Test the handling of the currency symbol in patterns. **/ @Test public void TestCurrencySign() { DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); StringBuffer pat = new StringBuffer(""); char currency = 0x00A4; // "\xA4#,##0.00;-\xA4#,##0.00" pat.append(currency).append("#,##0.00;-").append(currency).append("#,##0.00"); DecimalFormat fmt = new DecimalFormat(pat.toString(), sym); String s = ((NumberFormat) fmt).format(1234.56); pat = new StringBuffer(); logln("Pattern \"" + fmt.toPattern() + "\""); logln(" Format " + 1234.56 + " . " + s); assertEquals("symbol, pos", "$1,234.56", s); s = ((NumberFormat) fmt).format(-1234.56); logln(" Format " + Double.toString(-1234.56) + " . " + s); assertEquals("symbol, neg", "-$1,234.56", s); pat.setLength(0); // "\xA4\xA4 #,##0.00;\xA4\xA4 -#,##0.00" pat.append(currency).append(currency).append(" #,##0.00;").append(currency).append(currency).append(" -#,##0.00"); fmt = new DecimalFormat(pat.toString(), sym); s = ((NumberFormat) fmt).format(1234.56); logln("Pattern \"" + fmt.toPattern() + "\""); logln(" Format " + Double.toString(1234.56) + " . " + s); assertEquals("name, pos", "USD 1,234.56", s); s = ((NumberFormat) fmt).format(-1234.56); logln(" Format " + Double.toString(-1234.56) + " . " + s); assertEquals("name, neg", "USD -1,234.56", s); } @Test public void TestSpaceParsing() { // the data are: // the string to be parsed, parsed position, parsed error index String[][] DATA = { {"$124", "4", "-1"}, {"$124 $124", "4", "-1"}, {"$124 ", "4", "-1"}, {"$124 ", "4", "-1"}, {"$ 124 ", "5", "-1"}, {"$\u00A0124 ", "5", "-1"}, {" $ 124 ", "6", "-1"}, {"124$", "4", "-1"}, {"124 $", "5", "-1"}, {"$124\u200A", "4", "-1"}, {"$\u200A124", "5", "-1"}, }; NumberFormat foo = NumberFormat.getCurrencyInstance(); for (int i = 0; i < DATA.length; ++i) { ParsePosition parsePosition = new ParsePosition(0); String stringToBeParsed = DATA[i][0]; int parsedPosition = Integer.parseInt(DATA[i][1]); int errorIndex = Integer.parseInt(DATA[i][2]); try { Number result = foo.parse(stringToBeParsed, parsePosition); if (parsePosition.getIndex() != parsedPosition || parsePosition.getErrorIndex() != errorIndex) { errln("FAILED parse " + stringToBeParsed + "; parse position: " + parsePosition.getIndex() + "; error position: " + parsePosition.getErrorIndex()); } if (parsePosition.getErrorIndex() == -1 && result.doubleValue() != 124) { errln("FAILED parse " + stringToBeParsed + "; value " + result.doubleValue()); } } catch (Exception e) { errln("FAILED " + e.toString()); } } } @Test public void TestSpaceParsingStrict() { // All trailing grouping separators should be ignored in strict mode, not just the first. Object[][] cases = { {"123 ", 3, -1}, {"123 ", 3, -1}, {"123 ,", 3, -1}, {"123,", 3, -1}, {"123, ", 3, -1}, {"123,,", 3, -1}, {"123,, ", 3, -1}, {"123,,456", 3, -1}, {"123 ,", 3, -1}, {"123, ", 3, -1}, {"123, 456", 3, -1}, {"123 456", 3, -1} }; DecimalFormat df = new DecimalFormat("#,###"); df.setParseStrict(true); for (Object[] cas : cases) { String input = (String) cas[0]; int expectedIndex = (Integer) cas[1]; int expectedErrorIndex = (Integer) cas[2]; ParsePosition ppos = new ParsePosition(0); df.parse(input, ppos); assertEquals("Failed on index: '" + input + "'", expectedIndex, ppos.getIndex()); assertEquals("Failed on error: '" + input + "'", expectedErrorIndex, ppos.getErrorIndex()); } } @Test public void TestMultiCurrencySign() { String[][] DATA = { // the fields in the following test are: // locale, // currency pattern (with negative pattern), // currency number to be formatted, // currency format using currency symbol name, such as "$" for USD, // currency format using currency ISO name, such as "USD", // currency format using plural name, such as "US dollars". // for US locale {"en_US", "\u00A4#,##0.00;-\u00A4#,##0.00", "1234.56", "$1,234.56", "USD 1,234.56", "US dollars 1,234.56"}, {"en_US", "\u00A4#,##0.00;-\u00A4#,##0.00", "-1234.56", "-$1,234.56", "-USD 1,234.56", "-US dollars 1,234.56"}, {"en_US", "\u00A4#,##0.00;-\u00A4#,##0.00", "1", "$1.00", "USD 1.00", "US dollars 1.00"}, // for CHINA locale {"zh_CN", "\u00A4#,##0.00;(\u00A4#,##0.00)", "1234.56", "\uFFE51,234.56", "CNY 1,234.56", "\u4EBA\u6C11\u5E01 1,234.56"}, {"zh_CN", "\u00A4#,##0.00;(\u00A4#,##0.00)", "-1234.56", "(\uFFE51,234.56)", "(CNY 1,234.56)", "(\u4EBA\u6C11\u5E01 1,234.56)"}, {"zh_CN", "\u00A4#,##0.00;(\u00A4#,##0.00)", "1", "\uFFE51.00", "CNY 1.00", "\u4EBA\u6C11\u5E01 1.00"} }; String doubleCurrencyStr = "\u00A4\u00A4"; String tripleCurrencyStr = "\u00A4\u00A4\u00A4"; for (int i=0; i<DATA.length; ++i) { String locale = DATA[i][0]; String pat = DATA[i][1]; Double numberToBeFormat = new Double(DATA[i][2]); DecimalFormatSymbols sym = new DecimalFormatSymbols(new ULocale(locale)); for (int j=1; j<=3; ++j) { // j represents the number of currency sign in the pattern. if (j == 2) { pat = pat.replaceAll("\u00A4", doubleCurrencyStr); } else if (j == 3) { pat = pat.replaceAll("\u00A4\u00A4", tripleCurrencyStr); } DecimalFormat fmt = new DecimalFormat(pat, sym); String s = ((NumberFormat) fmt).format(numberToBeFormat); // DATA[i][3] is the currency format result using a // single currency sign. // DATA[i][4] is the currency format result using // double currency sign. // DATA[i][5] is the currency format result using // triple currency sign. // DATA[i][j+2] is the currency format result using // 'j' number of currency sign. String currencyFormatResult = DATA[i][2+j]; if (!s.equals(currencyFormatResult)) { errln("FAIL format: Expected " + currencyFormatResult + " but got " + s); } try { // mix style parsing for (int k=3; k<=4; ++k) { // DATA[i][3] is the currency format result using a // single currency sign. // DATA[i][4] is the currency format result using // double currency sign. // DATA[i][5] is the currency format result using // triple currency sign. // ICU 59: long name parsing requires currency mode. String oneCurrencyFormat = DATA[i][k]; if (fmt.parse(oneCurrencyFormat).doubleValue() != numberToBeFormat.doubleValue()) { errln("FAILED parse " + oneCurrencyFormat); } } } catch (ParseException e) { errln("FAILED, DecimalFormat parse currency: " + e.toString()); } } } } @Test public void TestCurrencyFormatForMixParsing() { MeasureFormat curFmt = MeasureFormat.getCurrencyFormat(new ULocale("en_US")); String[] formats = { "$1,234.56", // string to be parsed "USD1,234.56", "US dollars1,234.56", "1,234.56 US dollars" }; try { for (int i = 0; i < formats.length; ++i) { String stringToBeParsed = formats[i]; CurrencyAmount parsedVal = (CurrencyAmount)curFmt.parseObject(stringToBeParsed); Number val = parsedVal.getNumber(); if (!val.equals(new BigDecimal("1234.56"))) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the number. val=" + val); } if (!parsedVal.getCurrency().equals(Currency.getInstance("USD"))) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the currency"); } } } catch (ParseException e) { errln("parse FAILED: " + e.toString()); } } /** Starting in ICU 62, strict mode is actually strict with currency formats. */ @Test public void TestMismatchedCurrencyFormatFail() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(ULocale.ENGLISH); assertEquals("Test assumes that currency sign is at the beginning", "\u00A4#,##0.00", df.toPattern()); // Should round-trip on the correct currency format: expect2(df, 1.23, "\u00A41.23"); df.setCurrency(Currency.getInstance("EUR")); expect2(df, 1.23, "\u20AC1.23"); // Should parse with currency in the wrong place in lenient mode df.setParseStrict(false); expect(df, "1.23\u20AC", 1.23); expectParseCurrency(df, Currency.getInstance("EUR"), "1.23\u20AC"); // Should NOT parse with currency in the wrong place in STRICT mode df.setParseStrict(true); { ParsePosition ppos = new ParsePosition(0); df.parse("1.23\u20AC", ppos); assertEquals("Should fail to parse", 0, ppos.getIndex()); } { ParsePosition ppos = new ParsePosition(0); df.parseCurrency("1.23\u20AC", ppos); assertEquals("Should fail to parse currency", 0, ppos.getIndex()); } } @Test public void TestDecimalFormatCurrencyParse() { // Locale.US DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); StringBuffer pat = new StringBuffer(""); char currency = 0x00A4; // "\xA4#,##0.00;-\xA4#,##0.00" pat.append(currency).append(currency).append(currency).append("#,##0.00;-").append(currency).append(currency).append(currency).append("#,##0.00"); DecimalFormat fmt = new DecimalFormat(pat.toString(), sym); String[][] DATA = { // the data are: // string to be parsed, the parsed result (number) {"$1.00", "1"}, {"USD1.00", "1"}, {"1.00 US dollar", "1"}, {"$1,234.56", "1234.56"}, {"USD1,234.56", "1234.56"}, {"1,234.56 US dollar", "1234.56"}, }; try { for (int i = 0; i < DATA.length; ++i) { String stringToBeParsed = DATA[i][0]; double parsedResult = Double.parseDouble(DATA[i][1]); Number num = fmt.parse(stringToBeParsed); if (num.doubleValue() != parsedResult) { errln("FAIL parse: Expected " + parsedResult); } } } catch (ParseException e) { errln("FAILED, DecimalFormat parse currency: " + e.toString()); } } /** * Test localized currency patterns. */ @Test public void TestCurrency() { String[] DATA = { "fr", "CA", "", "1,50\u00a0$", "de", "DE", "", "1,50\u00a0\u20AC", "de", "DE", "PREEURO", "1,50\u00a0DM", "fr", "FR", "", "1,50\u00a0\u20AC", "fr", "FR", "PREEURO", "1,50\u00a0F", }; for (int i=0; i<DATA.length; i+=4) { Locale locale = new Locale(DATA[i], DATA[i+1], DATA[i+2]); NumberFormat fmt = NumberFormat.getCurrencyInstance(locale); String s = fmt.format(1.50); if (s.equals(DATA[i+3])) { logln("Ok: 1.50 x " + locale + " => " + s); } else { logln("FAIL: 1.50 x " + locale + " => " + s + ", expected " + DATA[i+3]); } } // format currency with CurrencyAmount for (int i=0; i<DATA.length; i+=4) { Locale locale = new Locale(DATA[i], DATA[i+1], DATA[i+2]); Currency curr = Currency.getInstance(locale); logln("\nName of the currency is: " + curr.getName(locale, Currency.LONG_NAME, new boolean[] {false})); CurrencyAmount cAmt = new CurrencyAmount(1.5, curr); logln("CurrencyAmount object's hashCode is: " + cAmt.hashCode()); //cover hashCode NumberFormat fmt = NumberFormat.getCurrencyInstance(locale); String sCurr = fmt.format(cAmt); if (sCurr.equals(DATA[i+3])) { logln("Ok: 1.50 x " + locale + " => " + sCurr); } else { errln("FAIL: 1.50 x " + locale + " => " + sCurr + ", expected " + DATA[i+3]); } } //Cover MeasureFormat.getCurrencyFormat() ULocale save = ULocale.getDefault(); ULocale.setDefault(ULocale.US); MeasureFormat curFmt = MeasureFormat.getCurrencyFormat(); String strBuf = curFmt.format(new CurrencyAmount(new Float(1234.56), Currency.getInstance("USD"))); try { CurrencyAmount parsedVal = (CurrencyAmount)curFmt.parseObject(strBuf); Number val = parsedVal.getNumber(); if (!val.equals(new BigDecimal("1234.56"))) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the number. val=" + val); } if (!parsedVal.getCurrency().equals(Currency.getInstance("USD"))) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the currency"); } } catch (ParseException e) { errln("FAIL: " + e.getMessage()); } ULocale.setDefault(save); } @Test public void TestJavaCurrencyConversion() { java.util.Currency gbpJava = java.util.Currency.getInstance("GBP"); Currency gbpIcu = Currency.getInstance("GBP"); assertEquals("ICU should equal API value", gbpIcu, Currency.fromJavaCurrency(gbpJava)); assertEquals("Java should equal API value", gbpJava, gbpIcu.toJavaCurrency()); // Test CurrencyAmount constructors CurrencyAmount ca1 = new CurrencyAmount(123.45, gbpJava); CurrencyAmount ca2 = new CurrencyAmount(123.45, gbpIcu); assertEquals("CurrencyAmount from both Double constructors should be equal", ca1, ca2); // Coverage for the Number constructor ca1 = new CurrencyAmount(new BigDecimal("543.21"), gbpJava); ca2 = new CurrencyAmount(new BigDecimal("543.21"), gbpIcu); assertEquals("CurrencyAmount from both Number constructors should be equal", ca1, ca2); } @Test public void TestCurrencyIsoPluralFormat() { String[][] DATA = { // the data are: // locale, // currency amount to be formatted, // currency ISO code to be formatted, // format result using CURRENCYSTYLE, // format result using ISOCURRENCYSTYLE, // format result using PLURALCURRENCYSTYLE, {"en_US", "1", "USD", "$1.00", "USD 1.00", "1.00 US dollars"}, {"en_US", "1234.56", "USD", "$1,234.56", "USD 1,234.56", "1,234.56 US dollars"}, {"en_US", "-1234.56", "USD", "-$1,234.56", "-USD 1,234.56", "-1,234.56 US dollars"}, {"zh_CN", "1", "USD", "US$1.00", "USD 1.00", "1.00 美元"}, {"zh_CN", "1234.56", "USD", "US$1,234.56", "USD 1,234.56", "1,234.56 美元"}, {"zh_CN", "1", "CNY", "¥1.00", "CNY 1.00", "1.00 人民币"}, {"zh_CN", "1234.56", "CNY", "¥1,234.56", "CNY 1,234.56", "1,234.56 人民币"}, {"ru_RU", "1", "RUB", "1,00 \u20BD", "1,00 RUB", "1,00 российского рубля"}, {"ru_RU", "2", "RUB", "2,00 \u20BD", "2,00 RUB", "2,00 российского рубля"}, {"ru_RU", "5", "RUB", "5,00 \u20BD", "5,00 RUB", "5,00 российского рубля"}, // test locale without currency information {"root", "-1.23", "USD", "-US$ 1.23", "-USD 1.23", "-1.23 USD"}, {"root@numbers=latn", "-1.23", "USD", "-US$ 1.23", "-USD 1.23", "-1.23 USD"}, // ensure that the root locale is still used with modifiers {"root@numbers=arab", "-1.23", "USD", "\u061C-\u0661\u066B\u0662\u0663\u00A0US$", "\u061C-\u0661\u066B\u0662\u0663\u00A0USD", "\u061C-\u0661\u066B\u0662\u0663 USD"}, // ensure that the root locale is still used with modifiers {"es_AR", "1", "INR", "INR\u00A01,00", "INR\u00A01,00", "1,00 rupia india"}, {"ar_EG", "1", "USD", "١٫٠٠\u00A0US$", "١٫٠٠\u00A0USD", "١٫٠٠ دولار أمريكي"}, }; for (int i=0; i<DATA.length; ++i) { for (int k = NumberFormat.CURRENCYSTYLE; k <= NumberFormat.PLURALCURRENCYSTYLE; ++k) { // k represents currency format style. if ( k != NumberFormat.CURRENCYSTYLE && k != NumberFormat.ISOCURRENCYSTYLE && k != NumberFormat.PLURALCURRENCYSTYLE ) { continue; } String localeString = DATA[i][0]; Double numberToBeFormat = new Double(DATA[i][1]); String currencyISOCode = DATA[i][2]; ULocale locale = new ULocale(localeString); NumberFormat numFmt = NumberFormat.getInstance(locale, k); numFmt.setCurrency(Currency.getInstance(currencyISOCode)); String strBuf = numFmt.format(numberToBeFormat); int resultDataIndex = k-1; if ( k == NumberFormat.CURRENCYSTYLE ) { resultDataIndex = k+2; } // DATA[i][resultDataIndex] is the currency format result // using 'k' currency style. String formatResult = DATA[i][resultDataIndex]; if (!strBuf.equals(formatResult)) { errln("FAIL: localeID: " + localeString + ", expected(" + formatResult.length() + "): \"" + formatResult + "\", actual(" + strBuf.length() + "): \"" + strBuf + "\""); } // test parsing, and test parsing for all currency formats. for (int j = 3; j < 6; ++j) { // DATA[i][3] is the currency format result using // CURRENCYSTYLE formatter. // DATA[i][4] is the currency format result using // ISOCURRENCYSTYLE formatter. // DATA[i][5] is the currency format result using // PLURALCURRENCYSTYLE formatter. String oneCurrencyFormatResult = DATA[i][j]; CurrencyAmount val = numFmt.parseCurrency(oneCurrencyFormatResult, null); if (val.getNumber().doubleValue() != numberToBeFormat.doubleValue()) { errln("FAIL: getCurrencyFormat of locale " + localeString + " failed roundtripping the number. val=" + val + "; expected: " + numberToBeFormat); } } } } } @Test public void TestMiscCurrencyParsing() { String[][] DATA = { // each has: string to be parsed, parsed position, error position {"1.00 ", "4", "-1", "0", "4"}, {"1.00 UAE dirha", "4", "-1", "0", "4"}, {"1.00 us dollar", "14", "-1", "14", "-1"}, {"1.00 US DOLLAR", "14", "-1", "14", "-1"}, {"1.00 usd", "8", "-1", "8", "-1"}, {"1.00 USD", "8", "-1", "8", "-1"}, }; ULocale locale = new ULocale("en_US"); for (int i=0; i<DATA.length; ++i) { String stringToBeParsed = DATA[i][0]; int parsedPosition = Integer.parseInt(DATA[i][1]); int errorIndex = Integer.parseInt(DATA[i][2]); int currParsedPosition = Integer.parseInt(DATA[i][3]); int currErrorIndex = Integer.parseInt(DATA[i][4]); NumberFormat numFmt = NumberFormat.getInstance(locale, NumberFormat.CURRENCYSTYLE); ParsePosition parsePosition = new ParsePosition(0); Number val = numFmt.parse(stringToBeParsed, parsePosition); if (parsePosition.getIndex() != parsedPosition || parsePosition.getErrorIndex() != errorIndex) { errln("FAIL: parse failed on case "+i+". expected position: " + parsedPosition +"; actual: " + parsePosition.getIndex()); errln("FAIL: parse failed on case "+i+". expected error position: " + errorIndex + "; actual: " + parsePosition.getErrorIndex()); } if (parsePosition.getErrorIndex() == -1 && val.doubleValue() != 1.00) { errln("FAIL: parse failed. expected 1.00, actual:" + val); } parsePosition = new ParsePosition(0); CurrencyAmount amt = numFmt.parseCurrency(stringToBeParsed, parsePosition); if (parsePosition.getIndex() != currParsedPosition || parsePosition.getErrorIndex() != currErrorIndex) { errln("FAIL: parseCurrency failed on case "+i+". expected error position: " + currErrorIndex + "; actual: " + parsePosition.getErrorIndex()); errln("FAIL: parseCurrency failed on case "+i+". expected position: " + currParsedPosition +"; actual: " + parsePosition.getIndex()); } if (parsePosition.getErrorIndex() == -1 && amt.getNumber().doubleValue() != 1.00) { errln("FAIL: parseCurrency failed. expected 1.00, actual:" + val); } } } @Test public void TestParseCurrency() { class ParseCurrencyItem { private final String localeString; private final String descrip; private final String currStr; private final int doubExpectPos; private final int doubExpectVal; private final int curExpectPos; private final int curExpectVal; private final String curExpectCurr; ParseCurrencyItem(String locStr, String desc, String curr, int doubExPos, int doubExVal, int curExPos, int curExVal, String curExCurr) { localeString = locStr; descrip = desc; currStr = curr; doubExpectPos = doubExPos; doubExpectVal = doubExVal; curExpectPos = curExPos; curExpectVal = curExVal; curExpectCurr = curExCurr; } public String getLocaleString() { return localeString; } public String getDescrip() { return descrip; } public String getCurrStr() { return currStr; } public int getDoubExpectPos() { return doubExpectPos; } public int getDoubExpectVal() { return doubExpectVal; } public int getCurExpectPos() { return curExpectPos; } public int getCurExpectVal() { return curExpectVal; } public String getCurExpectCurr() { return curExpectCurr; } } // Note: In cases where the number occurs before the currency sign, non-currency mode will parse the number // and stop when it reaches the currency symbol. final ParseCurrencyItem[] parseCurrencyItems = { new ParseCurrencyItem( "en_US", "dollars2", "$2.00", 5, 2, 5, 2, "USD" ), new ParseCurrencyItem( "en_US", "dollars4", "$4", 2, 4, 2, 4, "USD" ), new ParseCurrencyItem( "en_US", "dollars9", "9\u00A0$", 3, 9, 3, 9, "USD" ), new ParseCurrencyItem( "en_US", "pounds3", "\u00A33.00", 0, 0, 5, 3, "GBP" ), new ParseCurrencyItem( "en_US", "pounds5", "\u00A35", 0, 0, 2, 5, "GBP" ), new ParseCurrencyItem( "en_US", "pounds7", "7\u00A0\u00A3", 1, 7, 3, 7, "GBP" ), new ParseCurrencyItem( "en_US", "euros8", "\u20AC8", 0, 0, 2, 8, "EUR" ), new ParseCurrencyItem( "en_GB", "pounds3", "\u00A33.00", 5, 3, 5, 3, "GBP" ), new ParseCurrencyItem( "en_GB", "pounds5", "\u00A35", 2, 5, 2, 5, "GBP" ), new ParseCurrencyItem( "en_GB", "pounds7", "7\u00A0\u00A3", 3, 7, 3, 7, "GBP" ), new ParseCurrencyItem( "en_GB", "euros4", "4,00\u00A0\u20AC", 4,400, 6,400, "EUR" ), new ParseCurrencyItem( "en_GB", "euros6", "6\u00A0\u20AC", 1, 6, 3, 6, "EUR" ), new ParseCurrencyItem( "en_GB", "euros8", "\u20AC8", 0, 0, 2, 8, "EUR" ), new ParseCurrencyItem( "en_GB", "dollars4", "US$4", 0, 0, 4, 4, "USD" ), new ParseCurrencyItem( "fr_FR", "euros4", "4,00\u00A0\u20AC", 6, 4, 6, 4, "EUR" ), new ParseCurrencyItem( "fr_FR", "euros6", "6\u00A0\u20AC", 3, 6, 3, 6, "EUR" ), new ParseCurrencyItem( "fr_FR", "euros8", "\u20AC8", 2, 8, 2, 8, "EUR" ), new ParseCurrencyItem( "fr_FR", "dollars2", "$2.00", 0, 0, 0, 0, "" ), new ParseCurrencyItem( "fr_FR", "dollars4", "$4", 0, 0, 0, 0, "" ), }; for (ParseCurrencyItem item: parseCurrencyItems) { String localeString = item.getLocaleString(); ULocale uloc = new ULocale(localeString); NumberFormat fmt = null; try { fmt = NumberFormat.getCurrencyInstance(uloc); } catch (Exception e) { errln("NumberFormat.getCurrencyInstance fails for locale " + localeString); continue; } String currStr = item.getCurrStr(); ParsePosition parsePos = new ParsePosition(0); Number numVal = fmt.parse(currStr, parsePos); if ( parsePos.getIndex() != item.getDoubExpectPos() || (numVal != null && numVal.intValue() != item.getDoubExpectVal()) ) { if (numVal != null) { errln("NumberFormat.getCurrencyInstance parse " + localeString + "/" + item.getDescrip() + ", expect pos/val " + item.getDoubExpectPos() + "/" + item.getDoubExpectVal() + ", get " + parsePos.getIndex() + "/" + numVal.intValue() ); } else { errln("NumberFormat.getCurrencyInstance parse " + localeString + "/" + item.getDescrip() + ", expect pos/val " + item.getDoubExpectPos() + "/" + item.getDoubExpectVal() + ", get " + parsePos.getIndex() + "/(NULL)" ); } } parsePos.setIndex(0); int curExpectPos = item.getCurExpectPos(); CurrencyAmount currAmt = fmt.parseCurrency(currStr, parsePos); if ( parsePos.getIndex() != curExpectPos || (currAmt != null && (currAmt.getNumber().intValue() != item.getCurExpectVal() || currAmt.getCurrency().getCurrencyCode().compareTo(item.getCurExpectCurr()) != 0)) ) { if (currAmt != null) { errln("NumberFormat.getCurrencyInstance parseCurrency " + localeString + "/" + item.getDescrip() + ", expect pos/val/curr " + curExpectPos + "/" + item.getCurExpectVal() + "/" + item.getCurExpectCurr() + ", get " + parsePos.getIndex() + "/" + currAmt.getNumber().intValue() + "/" + currAmt.getCurrency().getCurrencyCode() ); } else { errln("NumberFormat.getCurrencyInstance parseCurrency " + localeString + "/" + item.getDescrip() + ", expect pos/val/curr " + curExpectPos + "/" + item.getCurExpectVal() + "/" + item.getCurExpectCurr() + ", get " + parsePos.getIndex() + "/(NULL)" ); } } } } @Test public void TestParseCurrencyWithWhitespace() { DecimalFormat df = new DecimalFormat("#,##0.00 ¤¤"); ParsePosition ppos = new ParsePosition(0); df.parseCurrency("1.00 us denmark", ppos); assertEquals("Expected to fail on 'us denmark' string", 4, ppos.getErrorIndex()); } @Test public void TestParseCurrPatternWithDecStyle() { String currpat = "¤#,##0.00"; String parsetxt = "x0y$"; DecimalFormat decfmt = (DecimalFormat)NumberFormat.getInstance(new ULocale("en_US"), NumberFormat.NUMBERSTYLE); decfmt.applyPattern(currpat); ParsePosition ppos = new ParsePosition(0); Number value = decfmt.parse(parsetxt, ppos); if (ppos.getIndex() != 0) { errln("DecimalFormat.parse expected to fail but got ppos " + ppos.getIndex() + ", value " + value); } } /** * Test the Currency object handling, new as of ICU 2.2. */ @Test public void TestCurrencyObject() { NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US); expectCurrency(fmt, null, 1234.56, "$1,234.56"); expectCurrency(fmt, Currency.getInstance(Locale.FRANCE), 1234.56, "\u20AC1,234.56"); // Euro expectCurrency(fmt, Currency.getInstance(Locale.JAPAN), 1234.56, "\u00A51,235"); // Yen expectCurrency(fmt, Currency.getInstance(new Locale("fr", "CH", "")), 1234.56, "CHF 1,234.56"); // no more 0.05 rounding here, see cldrbug 5548 expectCurrency(fmt, Currency.getInstance(Locale.US), 1234.56, "$1,234.56"); fmt = NumberFormat.getCurrencyInstance(Locale.FRANCE); expectCurrency(fmt, null, 1234.56, "1\u202F234,56 \u20AC"); expectCurrency(fmt, Currency.getInstance(Locale.JAPAN), 1234.56, "1\u202F235 JPY"); // Yen expectCurrency(fmt, Currency.getInstance(new Locale("fr", "CH", "")), 1234.56, "1\u202F234,56 CHF"); // no more rounding here, see cldrbug 5548 expectCurrency(fmt, Currency.getInstance(Locale.US), 1234.56, "1\u202F234,56 $US"); expectCurrency(fmt, Currency.getInstance(Locale.FRANCE), 1234.56, "1\u202F234,56 \u20AC"); // Euro } @Test public void TestCompatibleCurrencies() { NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US); expectParseCurrency(fmt, Currency.getInstance(Locale.JAPAN), "\u00A51,235"); // Yen half-width expectParseCurrency(fmt, Currency.getInstance(Locale.JAPAN), "\uFFE51,235"); // Yen full-wdith } @Test public void TestCurrencyPatterns() { int i; Random rnd = new Random(2017); Locale[] locs = NumberFormat.getAvailableLocales(); for (i=0; i<locs.length; ++i) { if (rnd.nextDouble() < 0.9) { // Check a random subset for speed: // Otherwise, this test takes a large fraction of the entire time. continue; } NumberFormat nf = NumberFormat.getCurrencyInstance(locs[i]); // Make sure currency formats do not have a variable number // of fraction digits int min = nf.getMinimumFractionDigits(); int max = nf.getMaximumFractionDigits(); if (min != max) { String a = nf.format(1.0); String b = nf.format(1.125); errln("FAIL: " + locs[i] + " min fraction digits != max fraction digits; "+ "x 1.0 => " + a + "; x 1.125 => " + b); } // Make sure EURO currency formats have exactly 2 fraction digits if (nf instanceof DecimalFormat) { Currency curr = ((DecimalFormat) nf).getCurrency(); if (curr != null && "EUR".equals(curr.getCurrencyCode())) { if (min != 2 || max != 2) { String a = nf.format(1.0); errln("FAIL: " + locs[i] + " is a EURO format but it does not have 2 fraction digits; "+ "x 1.0 => " + a); } } } } } /** * Do rudimentary testing of parsing. */ @Test public void TestParse() { String arg = "0.0"; DecimalFormat format = new DecimalFormat("00"); double aNumber = 0l; try { aNumber = format.parse(arg).doubleValue(); } catch (ParseException e) { System.out.println(e); } logln("parse(" + arg + ") = " + aNumber); } /** * Test proper rounding by the format method. */ @Test public void TestRounding487() { NumberFormat nf = NumberFormat.getInstance(); roundingTest(nf, 0.00159999, 4, "0.0016"); roundingTest(nf, 0.00995, 4, "0.01"); roundingTest(nf, 12.3995, 3, "12.4"); roundingTest(nf, 12.4999, 0, "12"); roundingTest(nf, - 19.5, 0, "-20"); } /** * Test the functioning of the secondary grouping value. */ @Test public void TestSecondaryGrouping() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat f = new DecimalFormat("#,##,###", US); expect(f, 123456789L, "12,34,56,789"); expectPat(f, "#,##,##0"); f.applyPattern("#,###"); f.setSecondaryGroupingSize(4); expect(f, 123456789L, "12,3456,789"); expectPat(f, "#,####,##0"); NumberFormat g = NumberFormat.getInstance(new Locale("hi", "IN")); String out = ""; long l = 1876543210L; out = g.format(l); // expect "1,87,65,43,210", but with Hindi digits // 01234567890123 boolean ok = true; if (out.length() != 14) { ok = false; } else { for (int i = 0; i < out.length(); ++i) { boolean expectGroup = false; switch (i) { case 1 : case 4 : case 7 : case 10 : expectGroup = true; break; } // Later -- fix this to get the actual grouping // character from the resource bundle. boolean isGroup = (out.charAt(i) == 0x002C); if (isGroup != expectGroup) { ok = false; break; } } } if (!ok) { errln("FAIL Expected "+ l + " x hi_IN . \"1,87,65,43,210\" (with Hindi digits), got \"" + out + "\""); } else { logln("Ok " + l + " x hi_IN . \"" + out + "\""); } } /* * Internal test utility. */ private void roundingTest(NumberFormat nf, double x, int maxFractionDigits, final String expected) { nf.setMaximumFractionDigits(maxFractionDigits); String out = nf.format(x); logln(x + " formats with " + maxFractionDigits + " fractional digits to " + out); if (!out.equals(expected)) errln("FAIL: Expected " + expected); } /** * Upgrade to alphaWorks */ @Test public void TestExponent() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt1 = new DecimalFormat("0.###E0", US); DecimalFormat fmt2 = new DecimalFormat("0.###E+0", US); int n = 1234; expect2(fmt1, n, "1.234E3"); expect2(fmt2, n, "1.234E+3"); expect(fmt1, "1.234E+3", n); // Either format should parse "E+3" } /** * Upgrade to alphaWorks */ @Test public void TestScientific() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); // Test pattern round-trip final String PAT[] = { "#E0", "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" }; int PAT_length = PAT.length; int DIGITS[] = { // min int, max int, min frac, max frac 0, 1, 0, 0, // "#E0" 1, 1, 0, 4, // "0.####E0" 2, 2, 3, 3, // "00.000E00" 1, 3, 0, 4, // "##0.####E000" 1, 1, 0, 3, // "0.###E0;[0.###E0]" }; for (int i = 0; i < PAT_length; ++i) { String pat = PAT[i]; DecimalFormat df = new DecimalFormat(pat, US); String pat2 = df.toPattern(); if (pat.equals(pat2)) { logln("Ok Pattern rt \"" + pat + "\" . \"" + pat2 + "\""); } else { errln("FAIL Pattern rt \"" + pat + "\" . \"" + pat2 + "\""); } // Make sure digit counts match what we expect if (i == 0) continue; // outputs to 1,1,0,0 since at least one min digit is required. if (df.getMinimumIntegerDigits() != DIGITS[4 * i] || df.getMaximumIntegerDigits() != DIGITS[4 * i + 1] || df.getMinimumFractionDigits() != DIGITS[4 * i + 2] || df.getMaximumFractionDigits() != DIGITS[4 * i + 3]) { errln("FAIL \""+ pat+ "\" min/max int; min/max frac = " + df.getMinimumIntegerDigits() + "/" + df.getMaximumIntegerDigits() + ";" + df.getMinimumFractionDigits() + "/" + df.getMaximumFractionDigits() + ", expect " + DIGITS[4 * i] + "/" + DIGITS[4 * i + 1] + ";" + DIGITS[4 * i + 2] + "/" + DIGITS[4 * i + 3]); } } expect2(new DecimalFormat("#E0", US), 12345.0, "1.2345E4"); expect(new DecimalFormat("0E0", US), 12345.0, "1E4"); // pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0" // so result = 1.234568E4 not 1.2345678901E4 //when the pattern problem is finalized, delete comment mark'//' //of the following code expect2(NumberFormat.getScientificInstance(Locale.US), 12345.678901, "1.2345678901E4"); logln("Testing NumberFormat.getScientificInstance(ULocale) ..."); expect2(NumberFormat.getScientificInstance(ULocale.US), 12345.678901, "1.2345678901E4"); expect(new DecimalFormat("##0.###E0", US), 12345.0, "12.34E3"); expect(new DecimalFormat("##0.###E0", US), 12345.00001, "12.35E3"); expect2(new DecimalFormat("##0.####E0", US), 12345, "12.345E3"); // pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0" // so result = 1.234568E4 not 1.2345678901E4 expect2(NumberFormat.getScientificInstance(Locale.FRANCE), 12345.678901, "1,2345678901E4"); logln("Testing NumberFormat.getScientificInstance(ULocale) ..."); expect2(NumberFormat.getScientificInstance(ULocale.FRANCE), 12345.678901, "1,2345678901E4"); expect(new DecimalFormat("##0.####E0", US), 789.12345e-9, "789.12E-9"); expect2(new DecimalFormat("##0.####E0", US), 780.e-9, "780E-9"); expect(new DecimalFormat(".###E0", US), 45678.0, ".457E5"); expect2(new DecimalFormat(".###E0", US), 0, ".0E0"); /* expect(new DecimalFormat[] { new DecimalFormat("#E0", US), new DecimalFormat("##E0", US), new DecimalFormat("####E0", US), new DecimalFormat("0E0", US), new DecimalFormat("00E0", US), new DecimalFormat("000E0", US), }, new Long(45678000), new String[] { "4.5678E7", "45.678E6", "4567.8E4", "5E7", "46E6", "457E5", } ); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("#E0", US), 45678000, "4.5678E7"); expect2(new DecimalFormat("##E0", US), 45678000, "45.678E6"); expect2(new DecimalFormat("####E0", US), 45678000, "4567.8E4"); expect(new DecimalFormat("0E0", US), 45678000, "5E7"); expect(new DecimalFormat("00E0", US), 45678000, "46E6"); expect(new DecimalFormat("000E0", US), 45678000, "457E5"); /* expect(new DecimalFormat("###E0", US, status), new Object[] { new Double(0.0000123), "12.3E-6", new Double(0.000123), "123E-6", new Double(0.00123), "1.23E-3", new Double(0.0123), "12.3E-3", new Double(0.123), "123E-3", new Double(1.23), "1.23E0", new Double(12.3), "12.3E0", new Double(123), "123E0", new Double(1230), "1.23E3", }); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("###E0", US), 0.0000123, "12.3E-6"); expect2(new DecimalFormat("###E0", US), 0.000123, "123E-6"); expect2(new DecimalFormat("###E0", US), 0.00123, "1.23E-3"); expect2(new DecimalFormat("###E0", US), 0.0123, "12.3E-3"); expect2(new DecimalFormat("###E0", US), 0.123, "123E-3"); expect2(new DecimalFormat("###E0", US), 1.23, "1.23E0"); expect2(new DecimalFormat("###E0", US), 12.3, "12.3E0"); expect2(new DecimalFormat("###E0", US), 123.0, "123E0"); expect2(new DecimalFormat("###E0", US), 1230.0, "1.23E3"); /* expect(new DecimalFormat("0.#E+00", US, status), new Object[] { new Double(0.00012), "1.2E-04", new Long(12000), "1.2E+04", }); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("0.#E+00", US), 0.00012, "1.2E-04"); expect2(new DecimalFormat("0.#E+00", US), 12000, "1.2E+04"); } /** * Upgrade to alphaWorks */ @Test public void TestPad() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); expect2(new DecimalFormat("*^##.##", US), 0, "^^^^0"); expect2(new DecimalFormat("*^##.##", US), -1.3, "^-1.3"); expect2( new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US), 0, "0.0E0______ g-m/s^2"); expect( new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US), 1.0 / 3, "333.333E-3_ g-m/s^2"); expect2(new DecimalFormat("##0.0####*_ 'g-m/s^2'", US), 0, "0.0______ g-m/s^2"); expect( new DecimalFormat("##0.0####*_ 'g-m/s^2'", US), 1.0 / 3, "0.33333__ g-m/s^2"); // Test padding before a sign final String formatStr = "*x#,###,###,##0.0#;*x(###,###,##0.0#)"; expect2(new DecimalFormat(formatStr, US), -10, "xxxxxxxxxx(10.0)"); expect2(new DecimalFormat(formatStr, US), -1000, "xxxxxxx(1,000.0)"); expect2(new DecimalFormat(formatStr, US), -1000000, "xxx(1,000,000.0)"); expect2(new DecimalFormat(formatStr, US), -100.37, "xxxxxxxx(100.37)"); expect2(new DecimalFormat(formatStr, US), -10456.37, "xxxxx(10,456.37)"); expect2(new DecimalFormat(formatStr, US), -1120456.37, "xx(1,120,456.37)"); expect2(new DecimalFormat(formatStr, US), -112045600.37, "(112,045,600.37)"); expect2(new DecimalFormat(formatStr, US), -1252045600.37, "(1,252,045,600.37)"); expect2(new DecimalFormat(formatStr, US), 10, "xxxxxxxxxxxx10.0"); expect2(new DecimalFormat(formatStr, US), 1000, "xxxxxxxxx1,000.0"); expect2(new DecimalFormat(formatStr, US), 1000000, "xxxxx1,000,000.0"); expect2(new DecimalFormat(formatStr, US), 100.37, "xxxxxxxxxx100.37"); expect2(new DecimalFormat(formatStr, US), 10456.37, "xxxxxxx10,456.37"); expect2(new DecimalFormat(formatStr, US), 1120456.37, "xxxx1,120,456.37"); expect2(new DecimalFormat(formatStr, US), 112045600.37, "xx112,045,600.37"); expect2(new DecimalFormat(formatStr, US), 10252045600.37, "10,252,045,600.37"); // Test padding between a sign and a number final String formatStr2 = "#,###,###,##0.0#*x;(###,###,##0.0#*x)"; expect2(new DecimalFormat(formatStr2, US), -10, "(10.0xxxxxxxxxx)"); expect2(new DecimalFormat(formatStr2, US), -1000, "(1,000.0xxxxxxx)"); expect2(new DecimalFormat(formatStr2, US), -1000000, "(1,000,000.0xxx)"); expect2(new DecimalFormat(formatStr2, US), -100.37, "(100.37xxxxxxxx)"); expect2(new DecimalFormat(formatStr2, US), -10456.37, "(10,456.37xxxxx)"); expect2(new DecimalFormat(formatStr2, US), -1120456.37, "(1,120,456.37xx)"); expect2(new DecimalFormat(formatStr2, US), -112045600.37, "(112,045,600.37)"); expect2(new DecimalFormat(formatStr2, US), -1252045600.37, "(1,252,045,600.37)"); expect2(new DecimalFormat(formatStr2, US), 10, "10.0xxxxxxxxxxxx"); expect2(new DecimalFormat(formatStr2, US), 1000, "1,000.0xxxxxxxxx"); expect2(new DecimalFormat(formatStr2, US), 1000000, "1,000,000.0xxxxx"); expect2(new DecimalFormat(formatStr2, US), 100.37, "100.37xxxxxxxxxx"); expect2(new DecimalFormat(formatStr2, US), 10456.37, "10,456.37xxxxxxx"); expect2(new DecimalFormat(formatStr2, US), 1120456.37, "1,120,456.37xxxx"); expect2(new DecimalFormat(formatStr2, US), 112045600.37, "112,045,600.37xx"); expect2(new DecimalFormat(formatStr2, US), 10252045600.37, "10,252,045,600.37"); //testing the setPadCharacter(UnicodeString) and getPadCharacterString() DecimalFormat fmt = new DecimalFormat("#", US); char padString = 'P'; fmt.setPadCharacter(padString); expectPad(fmt, "*P##.##", DecimalFormat.PAD_BEFORE_PREFIX, 5, padString); fmt.setPadCharacter('^'); expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, '^'); //commented untill implementation is complete /* fmt.setPadCharacter((UnicodeString)"^^^"); expectPad(fmt, "*^^^#", DecimalFormat.kPadBeforePrefix, 3, (UnicodeString)"^^^"); padString.remove(); padString.append((UChar)0x0061); padString.append((UChar)0x0302); fmt.setPadCharacter(padString); UChar patternChars[]={0x002a, 0x0061, 0x0302, 0x0061, 0x0302, 0x0023, 0x0000}; UnicodeString pattern(patternChars); expectPad(fmt, pattern , DecimalFormat.kPadBeforePrefix, 4, padString); */ // Test multi-char padding sequence specified via pattern expect2(new DecimalFormat("*'😃'####.00", US), 1.1, "😃😃😃1.10"); } /** * Upgrade to alphaWorks */ @Test public void TestPatterns2() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt = new DecimalFormat("#", US); char hat = 0x005E; /*^*/ expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, hat); expectPad(fmt, "$*^#", DecimalFormat.PAD_AFTER_PREFIX, 2, hat); expectPad(fmt, "#*^", DecimalFormat.PAD_BEFORE_SUFFIX, 1, hat); expectPad(fmt, "#$*^", DecimalFormat.PAD_AFTER_SUFFIX, 2, hat); expectPad(fmt, "$*^$#", -1); expectPad(fmt, "#$*^$", -1); expectPad(fmt, "'pre'#,##0*x'post'", DecimalFormat.PAD_BEFORE_SUFFIX, 12, (char) 0x0078 /*x*/); expectPad(fmt, "''#0*x", DecimalFormat.PAD_BEFORE_SUFFIX, 3, (char) 0x0078 /*x*/); expectPad(fmt, "'I''ll'*a###.##", DecimalFormat.PAD_AFTER_PREFIX, 10, (char) 0x0061 /*a*/); fmt.applyPattern("AA#,##0.00ZZ"); fmt.setPadCharacter(hat); fmt.setFormatWidth(10); fmt.setPadPosition(DecimalFormat.PAD_BEFORE_PREFIX); expectPat(fmt, "*^AA#,##0.00ZZ"); fmt.setPadPosition(DecimalFormat.PAD_BEFORE_SUFFIX); expectPat(fmt, "AA#,##0.00*^ZZ"); fmt.setPadPosition(DecimalFormat.PAD_AFTER_SUFFIX); expectPat(fmt, "AA#,##0.00ZZ*^"); // 12 3456789012 String exp = "AA*^#,##0.00ZZ"; fmt.setFormatWidth(12); fmt.setPadPosition(DecimalFormat.PAD_AFTER_PREFIX); expectPat(fmt, exp); fmt.setFormatWidth(13); // 12 34567890123 expectPat(fmt, "AA*^##,##0.00ZZ"); fmt.setFormatWidth(14); // 12 345678901234 expectPat(fmt, "AA*^###,##0.00ZZ"); fmt.setFormatWidth(15); // 12 3456789012345 expectPat(fmt, "AA*^####,##0.00ZZ"); // This is the interesting case // The new implementation produces "AA*^#####,##0.00ZZ", which is functionally equivalent // to what the old implementation produced, "AA*^#,###,##0.00ZZ" fmt.setFormatWidth(16); // 12 34567890123456 //expectPat(fmt, "AA*^#,###,##0.00ZZ"); expectPat(fmt, "AA*^#####,##0.00ZZ"); } @Test public void TestRegistration() { final ULocale SRC_LOC = ULocale.FRANCE; final ULocale SWAP_LOC = ULocale.US; class TestFactory extends SimpleNumberFormatFactory { NumberFormat currencyStyle; TestFactory() { super(SRC_LOC, true); currencyStyle = NumberFormat.getIntegerInstance(SWAP_LOC); } @Override public NumberFormat createFormat(ULocale loc, int formatType) { if (formatType == FORMAT_CURRENCY) { return currencyStyle; } return null; } } NumberFormat f0 = NumberFormat.getIntegerInstance(SWAP_LOC); NumberFormat f1 = NumberFormat.getIntegerInstance(SRC_LOC); NumberFormat f2 = NumberFormat.getCurrencyInstance(SRC_LOC); Object key = NumberFormat.registerFactory(new TestFactory()); NumberFormat f3 = NumberFormat.getCurrencyInstance(SRC_LOC); NumberFormat f4 = NumberFormat.getIntegerInstance(SRC_LOC); NumberFormat.unregister(key); // restore for other tests NumberFormat f5 = NumberFormat.getCurrencyInstance(SRC_LOC); float n = 1234.567f; logln("f0 swap int: " + f0.format(n)); logln("f1 src int: " + f1.format(n)); logln("f2 src cur: " + f2.format(n)); logln("f3 reg cur: " + f3.format(n)); logln("f4 reg int: " + f4.format(n)); logln("f5 unreg cur: " + f5.format(n)); if (!f3.format(n).equals(f0.format(n))) { errln("registered service did not match"); } if (!f4.format(n).equals(f1.format(n))) { errln("registered service did not inherit"); } if (!f5.format(n).equals(f2.format(n))) { errln("unregistered service did not match original"); } } @Test public void TestScientific2() { // jb 2552 DecimalFormat fmt = (DecimalFormat)NumberFormat.getCurrencyInstance(); Number num = new Double(12.34); expect(fmt, num, "$12.34"); fmt.setScientificNotation(true); expect(fmt, num, "$1.23E1"); fmt.setScientificNotation(false); expect(fmt, num, "$12.34"); } @Test public void TestScientificGrouping() { // jb 2552 DecimalFormat fmt = new DecimalFormat("###.##E0"); expect(fmt, .01234, "12.3E-3"); expect(fmt, .1234, "123E-3"); expect(fmt, 1.234, "1.23E0"); expect(fmt, 12.34, "12.3E0"); expect(fmt, 123.4, "123E0"); expect(fmt, 1234, "1.23E3"); } // additional coverage tests // sigh, can't have static inner classes, why not? static final class PI extends Number { /** * For serialization */ private static final long serialVersionUID = -305601227915602172L; private PI() {} @Override public int intValue() { return (int)Math.PI; } @Override public long longValue() { return (long)Math.PI; } @Override public float floatValue() { return (float)Math.PI; } @Override public double doubleValue() { return Math.PI; } @Override public byte byteValue() { return (byte)Math.PI; } @Override public short shortValue() { return (short)Math.PI; } public static final Number INSTANCE = new PI(); } @Test public void TestCoverage() { NumberFormat fmt = NumberFormat.getNumberInstance(); // default locale logln(fmt.format(new BigInteger("1234567890987654321234567890987654321", 10))); fmt = NumberFormat.getScientificInstance(); // default locale logln(fmt.format(PI.INSTANCE)); try { logln(fmt.format("12345")); errln("numberformat of string did not throw exception"); } catch (Exception e) { logln("PASS: numberformat of string failed as expected"); } int hash = fmt.hashCode(); logln("hash code " + hash); logln("compare to string returns: " + fmt.equals("")); // For ICU 2.6 - alan DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat df = new DecimalFormat("'*&'' '\u00A4' ''&*' #,##0.00", US); df.setCurrency(Currency.getInstance("INR")); expect2(df, 1.0, "*&' \u20B9 '&* 1.00"); expect2(df, -2.0, "-*&' \u20B9 '&* 2.00"); df.applyPattern("#,##0.00 '*&'' '\u00A4' ''&*'"); expect2(df, 2.0, "2.00 *&' \u20B9 '&*"); expect2(df, -1.0, "-1.00 *&' \u20B9 '&*"); java.math.BigDecimal r; r = df.getRoundingIncrement(); if (r != null) { errln("FAIL: rounding = " + r + ", expect null"); } if (df.isScientificNotation()) { errln("FAIL: isScientificNotation = true, expect false"); } // Create a new instance to flush out currency info df = new DecimalFormat("0.00000", US); df.setScientificNotation(true); if (!df.isScientificNotation()) { errln("FAIL: isScientificNotation = false, expect true"); } df.setMinimumExponentDigits((byte)2); if (df.getMinimumExponentDigits() != 2) { errln("FAIL: getMinimumExponentDigits = " + df.getMinimumExponentDigits() + ", expect 2"); } df.setExponentSignAlwaysShown(true); if (!df.isExponentSignAlwaysShown()) { errln("FAIL: isExponentSignAlwaysShown = false, expect true"); } df.setSecondaryGroupingSize(0); if (df.getSecondaryGroupingSize() != 0) { errln("FAIL: getSecondaryGroupingSize = " + df.getSecondaryGroupingSize() + ", expect 0"); } expect2(df, 3.14159, "3.14159E+00"); // DecimalFormatSymbols#getInstance DecimalFormatSymbols decsym1 = DecimalFormatSymbols.getInstance(); DecimalFormatSymbols decsym2 = new DecimalFormatSymbols(); if (!decsym1.equals(decsym2)) { errln("FAIL: DecimalFormatSymbols returned by getInstance()" + "does not match new DecimalFormatSymbols()."); } decsym1 = DecimalFormatSymbols.getInstance(Locale.JAPAN); decsym2 = DecimalFormatSymbols.getInstance(ULocale.JAPAN); if (!decsym1.equals(decsym2)) { errln("FAIL: DecimalFormatSymbols returned by getInstance(Locale.JAPAN)" + "does not match the one returned by getInstance(ULocale.JAPAN)."); } // DecimalFormatSymbols#getAvailableLocales/#getAvailableULocales Locale[] allLocales = DecimalFormatSymbols.getAvailableLocales(); if (allLocales.length == 0) { errln("FAIL: Got a empty list for DecimalFormatSymbols.getAvailableLocales"); } else { logln("PASS: " + allLocales.length + " available locales returned by DecimalFormatSymbols.getAvailableLocales"); } ULocale[] allULocales = DecimalFormatSymbols.getAvailableULocales(); if (allULocales.length == 0) { errln("FAIL: Got a empty list for DecimalFormatSymbols.getAvailableLocales"); } else { logln("PASS: " + allULocales.length + " available locales returned by DecimalFormatSymbols.getAvailableULocales"); } } @Test public void TestLocalizedPatternSymbolCoverage() { String[] standardPatterns = { "#,##0.05+%;#,##0.05-%", "* @@@E0‰" }; String[] standardPatterns58 = { "#,##0.05+%;#,##0.05-%", "* @@@E0‰;* -@@@E0‰" }; String[] localizedPatterns = { "▰⁖▰▰໐⁘໐໕†⁜⁙▰⁖▰▰໐⁘໐໕‡⁜", "⁂ ⁕⁕⁕⁑⁑໐‱" }; String[] localizedPatterns58 = { "▰⁖▰▰໐⁘໐໕+⁜⁙▰⁖▰▰໐⁘໐໕‡⁜", "⁂ ⁕⁕⁕⁑⁑໐‱⁙⁂ ‡⁕⁕⁕⁑⁑໐‱" }; DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setGroupingSeparator('⁖'); dfs.setDecimalSeparator('⁘'); dfs.setPatternSeparator('⁙'); dfs.setDigit('▰'); dfs.setZeroDigit('໐'); dfs.setSignificantDigit('⁕'); dfs.setPlusSign('†'); dfs.setMinusSign('‡'); dfs.setPercent('⁜'); dfs.setPerMill('‱'); dfs.setExponentSeparator("⁑⁑"); // tests multi-char sequence dfs.setPadEscape('⁂'); for (int i=0; i<2; i++) { String standardPattern = standardPatterns[i]; String standardPattern58 = standardPatterns58[i]; String localizedPattern = localizedPatterns[i]; String localizedPattern58 = localizedPatterns58[i]; DecimalFormat df1 = new DecimalFormat("#", dfs); df1.applyPattern(standardPattern); DecimalFormat df2 = new DecimalFormat("#", dfs); df2.applyLocalizedPattern(localizedPattern); assertEquals("DecimalFormat instances should be equal", df1, df2); assertEquals("toPattern should match on localizedPattern instance", standardPattern, df2.toPattern()); assertEquals("toLocalizedPattern should match on standardPattern instance", localizedPattern, df1.toLocalizedPattern()); // Android can't access DecimalFormat_ICU58 for testing (ticket #13283). if (TestUtil.getJavaVendor() == TestUtil.JavaVendor.Android) continue; // Note: ICU 58 does not support plus signs in patterns // Note: ICU 58 always prints the negative part of scientific notation patterns, // even when the negative part is not necessary DecimalFormat_ICU58 df3 = new DecimalFormat_ICU58("#", dfs); df3.applyPattern(standardPattern); // Reading standardPattern is OK DecimalFormat_ICU58 df4 = new DecimalFormat_ICU58("#", dfs); df4.applyLocalizedPattern(localizedPattern58); // Note: DecimalFormat#equals() is broken on ICU 58 assertEquals("toPattern should match on ICU58 localizedPattern instance", standardPattern58, df4.toPattern()); assertEquals("toLocalizedPattern should match on ICU58 standardPattern instance", localizedPattern58, df3.toLocalizedPattern()); } } @Test public void TestParseNull() throws ParseException { DecimalFormat df = new DecimalFormat(); try { df.parse(null); fail("df.parse(null) didn't throw an exception"); } catch (IllegalArgumentException e){} try { df.parse(null, null); fail("df.parse(null) didn't throw an exception"); } catch (IllegalArgumentException e){} try { df.parseCurrency(null, null); fail("df.parse(null) didn't throw an exception"); } catch (IllegalArgumentException e){} } @Test public void TestWhiteSpaceParsing() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt = new DecimalFormat("a b#0c ", US); int n = 1234; expect(fmt, "a b1234c ", n); expect(fmt, "a b1234c ", n); expect(fmt, "ab1234", n); fmt.applyPattern("a b #"); expect(fmt, "ab1234", n); expect(fmt, "ab 1234", n); expect(fmt, "a b1234", n); expect(fmt, "a b1234", n); expect(fmt, " a b 1234", n); // Horizontal whitespace is allowed, but not vertical whitespace. expect(fmt, "\ta\u00A0b\u20001234", n); expect(fmt, "a \u200A b1234", n); expectParseException(fmt, "\nab1234", n); expectParseException(fmt, "a \n b1234", n); expectParseException(fmt, "a \u0085 b1234", n); expectParseException(fmt, "a \u2028 b1234", n); // Test all characters in the UTS 18 "blank" set stated in the API docstring. UnicodeSet blanks = new UnicodeSet("[[:Zs:][\\u0009]]").freeze(); for (String space : blanks) { String str = "a " + space + " b1234c "; expect(fmt, str, n); } // Arbitrary whitespace is not accepted in strict mode. fmt.setParseStrict(true); for (String space : blanks) { String str = "a " + space + " b1234c "; expectParseException(fmt, str, n); } // Test default ignorable characters. These should work in both lenient and strict. UnicodeSet defaultIgnorables = new UnicodeSet("[[:Bidi_Control:]]").freeze(); fmt.setParseStrict(false); for (String ignorable : defaultIgnorables) { String str = "a b " + ignorable + "1234c "; expect(fmt, str, n); } fmt.setParseStrict(true); for (String ignorable : defaultIgnorables) { String str = "a b " + ignorable + "1234c "; expect(fmt, str, n); } // Test that other whitespace characters do not work fmt.setParseStrict(false); UnicodeSet otherWhitespace = new UnicodeSet("[[:whitespace:]]").removeAll(blanks).freeze(); for (String space : otherWhitespace) { String str = "a " + space + " b1234"; expectParseException(fmt, str, n); } } /** * Test currencies whose display name is a ChoiceFormat. */ @Test public void TestComplexCurrency() { // CLDR No Longer uses complex currency symbols. // Skipping this test. // Locale loc = new Locale("kn", "IN", ""); // NumberFormat fmt = NumberFormat.getCurrencyInstance(loc); // expect2(fmt, 1.0, "Re.\u00a01.00"); // expect(fmt, 1.001, "Re.\u00a01.00"); // tricky // expect2(fmt, 12345678.0, "Rs.\u00a01,23,45,678.00"); // expect2(fmt, 0.5, "Rs.\u00a00.50"); // expect2(fmt, -1.0, "-Re.\u00a01.00"); // expect2(fmt, -10.0, "-Rs.\u00a010.00"); } @Test public void TestCurrencyKeyword() { ULocale locale = new ULocale("th_TH@currency=QQQ"); NumberFormat format = NumberFormat.getCurrencyInstance(locale); String result = format.format(12.34f); if (!"QQQ 12.34".equals(result)) { errln("got unexpected currency: " + result); } } /** * Test alternate numbering systems */ @Test public void TestNumberingSystems() { class TestNumberingSystemItem { private final String localeName; private final double value; private final boolean isRBNF; private final String expectedResult; TestNumberingSystemItem(String loc, double val, boolean rbnf, String exp) { localeName = loc; value = val; isRBNF = rbnf; expectedResult = exp; } } final TestNumberingSystemItem[] DATA = { new TestNumberingSystemItem( "en_US@numbers=thai", 1234.567, false, "\u0e51,\u0e52\u0e53\u0e54.\u0e55\u0e56\u0e57" ), new TestNumberingSystemItem( "en_US@numbers=thai", 1234.567, false, "\u0E51,\u0E52\u0E53\u0E54.\u0E55\u0E56\u0E57" ), new TestNumberingSystemItem( "en_US@numbers=hebr", 5678.0, true, "\u05D4\u05F3\u05EA\u05E8\u05E2\u05F4\u05D7" ), new TestNumberingSystemItem( "en_US@numbers=arabext", 1234.567, false, "\u06F1\u066c\u06F2\u06F3\u06F4\u066b\u06F5\u06F6\u06F7" ), new TestNumberingSystemItem( "de_DE@numbers=foobar", 1234.567, false, "1.234,567" ), new TestNumberingSystemItem( "ar_EG", 1234.567, false, "\u0661\u066c\u0662\u0663\u0664\u066b\u0665\u0666\u0667" ), new TestNumberingSystemItem( "th_TH@numbers=traditional", 1234.567, false, "\u0E51,\u0E52\u0E53\u0E54.\u0E55\u0E56\u0E57" ), // fall back to native per TR35 new TestNumberingSystemItem( "ar_MA", 1234.567, false, "1.234,567" ), new TestNumberingSystemItem( "en_US@numbers=hanidec", 1234.567, false, "\u4e00,\u4e8c\u4e09\u56db.\u4e94\u516d\u4e03" ), new TestNumberingSystemItem( "ta_IN@numbers=native", 1234.567, false, "\u0BE7,\u0BE8\u0BE9\u0BEA.\u0BEB\u0BEC\u0BED" ), new TestNumberingSystemItem( "ta_IN@numbers=traditional", 1235.0, true, "\u0BF2\u0BE8\u0BF1\u0BE9\u0BF0\u0BEB" ), new TestNumberingSystemItem( "ta_IN@numbers=finance", 1234.567, false, "1,234.567" ), // fall back to default per TR35 new TestNumberingSystemItem( "zh_TW@numbers=native", 1234.567, false, "\u4e00,\u4e8c\u4e09\u56db.\u4e94\u516d\u4e03" ), new TestNumberingSystemItem( "zh_TW@numbers=traditional", 1234.567, true, "\u4E00\u5343\u4E8C\u767E\u4E09\u5341\u56DB\u9EDE\u4E94\u516D\u4E03" ), new TestNumberingSystemItem( "zh_TW@numbers=finance", 1234.567, true, "\u58F9\u4EDF\u8CB3\u4F70\u53C3\u62FE\u8086\u9EDE\u4F0D\u9678\u67D2" ), new TestNumberingSystemItem( "en_US@numbers=mathsanb", 1234.567, false, "𝟭,𝟮𝟯𝟰.𝟱𝟲𝟳" ), // ticket #13286 }; for (TestNumberingSystemItem item : DATA) { ULocale loc = new ULocale(item.localeName); NumberFormat fmt = NumberFormat.getInstance(loc); if (item.isRBNF) { expect3(fmt,item.value,item.expectedResult); } else { expect2(fmt,item.value,item.expectedResult); } } } // Coverage tests for methods not being called otherwise. @Test public void TestNumberingSystemCoverage() { // Test getAvaliableNames String[] availableNames = NumberingSystem.getAvailableNames(); if (availableNames == null || availableNames.length <= 0) { errln("ERROR: NumberingSystem.getAvailableNames() returned a null or empty array."); } else { boolean latnFound = false; for (String name : availableNames){ if ("latn".equals(name)) { latnFound = true; break; } } if (!latnFound) { errln("ERROR: 'latn' numbering system not found on NumberingSystem.getAvailableNames()."); } } // Test NumberingSystem.getInstance() NumberingSystem ns1 = NumberingSystem.getInstance(); if (ns1 == null || ns1.isAlgorithmic()) { errln("ERROR: NumberingSystem.getInstance() returned a null or invalid NumberingSystem"); } // Test NumberingSystem.getInstance(int,boolean,String) /* Parameters used: the ones used in the default constructor * radix = 10; * algorithmic = false; * desc = "0123456789"; */ NumberingSystem ns2 = NumberingSystem.getInstance(10, false, "0123456789"); if (ns2 == null || ns2.isAlgorithmic()) { errln("ERROR: NumberingSystem.getInstance(int,boolean,String) returned a null or invalid NumberingSystem"); } // Test NumberingSystem.getInstance(Locale) NumberingSystem ns3 = NumberingSystem.getInstance(Locale.ENGLISH); if (ns3 == null || ns3.isAlgorithmic()) { errln("ERROR: NumberingSystem.getInstance(Locale) returned a null or invalid NumberingSystem"); } } @Test public void Test6816() { Currency cur1 = Currency.getInstance(new Locale("und", "PH")); NumberFormat nfmt = NumberFormat.getCurrencyInstance(new Locale("und", "PH")); DecimalFormatSymbols decsym = ((DecimalFormat)nfmt).getDecimalFormatSymbols(); Currency cur2 = decsym.getCurrency(); if ( !cur1.getCurrencyCode().equals("PHP") || !cur2.getCurrencyCode().equals("PHP")) { errln("FAIL: Currencies should match PHP: cur1 = "+cur1.getCurrencyCode()+"; cur2 = "+cur2.getCurrencyCode()); } } @Test public void TestThreadedFormat() { class FormatTask implements Runnable { DecimalFormat fmt; StringBuffer buf; boolean inc; float num; FormatTask(DecimalFormat fmt, int index) { this.fmt = fmt; this.buf = new StringBuffer(); this.inc = (index & 0x1) == 0; this.num = inc ? 0 : 10000; } @Override public void run() { if (inc) { while (num < 10000) { buf.append(fmt.format(num) + "\n"); num += 3.14159; } } else { while (num > 0) { buf.append(fmt.format(num) + "\n"); num -= 3.14159; } } } String result() { return buf.toString(); } } DecimalFormat fmt = new DecimalFormat("0.####"); FormatTask[] tasks = new FormatTask[8]; for (int i = 0; i < tasks.length; ++i) { tasks[i] = new FormatTask(fmt, i); } TestUtil.runUntilDone(tasks); for (int i = 2; i < tasks.length; i++) { String str1 = tasks[i].result(); String str2 = tasks[i-2].result(); if (!str1.equals(str2)) { System.out.println("mismatch at " + i); System.out.println(str1); System.out.println(str2); errln("decimal format thread mismatch"); break; } str1 = str2; } } @Test public void TestPerMill() { DecimalFormat fmt = new DecimalFormat("###.###\u2030"); assertEquals("0.4857 x ###.###\u2030", "485.7\u2030", fmt.format(0.4857)); DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.ENGLISH); sym.setPerMill('m'); DecimalFormat fmt2 = new DecimalFormat("", sym); fmt2.applyLocalizedPattern("###.###m"); assertEquals("0.4857 x ###.###m", "485.7m", fmt2.format(0.4857)); } @Test public void TestIllegalPatterns() { // Test cases: // Prefix with "-:" for illegal patterns // Prefix with "+:" for legal patterns String DATA[] = { // Unquoted special characters in the suffix are illegal "-:000.000|###", "+:000.000'|###'", }; for (int i=0; i<DATA.length; ++i) { String pat=DATA[i]; boolean valid = pat.charAt(0) == '+'; pat = pat.substring(2); Exception e = null; try { // locale doesn't matter here new DecimalFormat(pat); } catch (IllegalArgumentException e1) { e = e1; } catch (IndexOutOfBoundsException e1) { e = e1; } String msg = (e==null) ? "success" : e.getMessage(); if ((e==null) == valid) { logln("Ok: pattern \"" + pat + "\": " + msg); } else { errln("FAIL: pattern \"" + pat + "\" should have " + (valid?"succeeded":"failed") + "; got " + msg); } } } /** * Parse a CurrencyAmount using the given NumberFormat, with * the 'delim' character separating the number and the currency. */ private static CurrencyAmount parseCurrencyAmount(String str, NumberFormat fmt, char delim) throws ParseException { int i = str.indexOf(delim); return new CurrencyAmount(fmt.parse(str.substring(0,i)), Currency.getInstance(str.substring(i+1))); } /** * Return an integer representing the next token from this * iterator. The integer will be an index into the given list, or * -1 if there are no more tokens, or -2 if the token is not on * the list. */ private static int keywordIndex(String tok) { for (int i=0; i<KEYWORDS.length; ++i) { if (tok.equals(KEYWORDS[i])) { return i; } } return -1; } private static final String KEYWORDS[] = { /*0*/ "ref=", // <reference pattern to parse numbers> /*1*/ "loc=", // <locale for formats> /*2*/ "f:", // <pattern or '-'> <number> <exp. string> /*3*/ "fp:", // <pattern or '-'> <number> <exp. string> <exp. number> /*4*/ "rt:", // <pattern or '-'> <(exp.) number> <(exp.) string> /*5*/ "p:", // <pattern or '-'> <string> <exp. number> /*6*/ "perr:", // <pattern or '-'> <invalid string> /*7*/ "pat:", // <pattern or '-'> <exp. toPattern or '-' or 'err'> /*8*/ "fpc:", // <loc or '-'> <curr.amt> <exp. string> <exp. curr.amt> /*9*/ "strict=", // true or false }; @SuppressWarnings("resource") // InputStream is will be closed by the ResourceReader. @Test public void TestCases() { String caseFileName = "NumberFormatTestCases.txt"; java.io.InputStream is = NumberFormatTest.class.getResourceAsStream(caseFileName); ResourceReader reader = new ResourceReader(is, caseFileName, "utf-8"); TokenIterator tokens = new TokenIterator(reader); Locale loc = new Locale("en", "US", ""); DecimalFormat ref = null, fmt = null; MeasureFormat mfmt = null; String pat = null, str = null, mloc = null; boolean strict = false; try { for (;;) { String tok = tokens.next(); if (tok == null) { break; } String where = "(" + tokens.getLineNumber() + ") "; int cmd = keywordIndex(tok); switch (cmd) { case 0: // ref= <reference pattern> ref = new DecimalFormat(tokens.next(), new DecimalFormatSymbols(Locale.US)); ref.setParseStrict(strict); logln("Setting reference pattern to:\t" + ref); break; case 1: // loc= <locale> loc = LocaleUtility.getLocaleFromName(tokens.next()); pat = ((DecimalFormat) NumberFormat.getInstance(loc)).toPattern(); logln("Setting locale to:\t" + loc + ", \tand pattern to:\t" + pat); break; case 2: // f: case 3: // fp: case 4: // rt: case 5: // p: tok = tokens.next(); if (!tok.equals("-")) { pat = tok; } try { fmt = new DecimalFormat(pat, new DecimalFormatSymbols(loc)); fmt.setParseStrict(strict); } catch (IllegalArgumentException iae) { errln(where + "Pattern \"" + pat + '"'); iae.printStackTrace(); tokens.next(); // consume remaining tokens //tokens.next(); if (cmd == 3) tokens.next(); continue; } str = null; try { if (cmd == 2 || cmd == 3 || cmd == 4) { // f: <pattern or '-'> <number> <exp. string> // fp: <pattern or '-'> <number> <exp. string> <exp. number> // rt: <pattern or '-'> <number> <string> String num = tokens.next(); str = tokens.next(); Number n = ref.parse(num); assertEquals(where + '"' + pat + "\".format(" + num + ")", str, fmt.format(n)); if (cmd == 3) { // fp: n = ref.parse(tokens.next()); } if (cmd != 2) { // != f: assertEquals(where + '"' + pat + "\".parse(\"" + str + "\")", n, fmt.parse(str)); } } // p: <pattern or '-'> <string to parse> <exp. number> else { str = tokens.next(); String expstr = tokens.next(); Number parsed = fmt.parse(str); Number exp = ref.parse(expstr); assertEquals(where + '"' + pat + "\".parse(\"" + str + "\")", exp, parsed); } } catch (ParseException e) { errln(where + '"' + pat + "\".parse(\"" + str + "\") threw an exception"); e.printStackTrace(); } break; case 6: // perr: <pattern or '-'> <invalid string> errln("Under construction"); return; case 7: // pat: <pattern> <exp. toPattern, or '-' or 'err'> String testpat = tokens.next(); String exppat = tokens.next(); boolean err = exppat.equals("err"); if (testpat.equals("-")) { if (err) { errln("Invalid command \"pat: - err\" at " + tokens.describePosition()); continue; } testpat = pat; } if (exppat.equals("-")) exppat = testpat; try { DecimalFormat f = null; if (testpat == pat) { // [sic] f = fmt; } else { f = new DecimalFormat(testpat); f.setParseStrict(strict); } if (err) { errln(where + "Invalid pattern \"" + testpat + "\" was accepted"); } else { assertEquals(where + '"' + testpat + "\".toPattern()", exppat, f.toPattern()); } } catch (IllegalArgumentException iae2) { if (err) { logln("Ok: " + where + "Invalid pattern \"" + testpat + "\" threw an exception"); } else { errln(where + "Valid pattern \"" + testpat + "\" threw an exception"); iae2.printStackTrace(); } } break; case 8: // fpc: tok = tokens.next(); if (!tok.equals("-")) { mloc = tok; ULocale l = new ULocale(mloc); try { mfmt = MeasureFormat.getCurrencyFormat(l); } catch (IllegalArgumentException iae) { errln(where + "Loc \"" + tok + '"'); iae.printStackTrace(); tokens.next(); // consume remaining tokens tokens.next(); tokens.next(); continue; } } str = null; try { // fpc: <loc or '-'> <curr.amt> <exp. string> <exp. curr.amt> String currAmt = tokens.next(); str = tokens.next(); CurrencyAmount target = parseCurrencyAmount(currAmt, ref, '/'); String formatResult = mfmt.format(target); assertEquals(where + "getCurrencyFormat(" + mloc + ").format(" + currAmt + ")", str, formatResult); target = parseCurrencyAmount(tokens.next(), ref, '/'); CurrencyAmount parseResult = (CurrencyAmount) mfmt.parseObject(str); assertEquals(where + "getCurrencyFormat(" + mloc + ").parse(\"" + str + "\")", target, parseResult); } catch (ParseException e) { errln(where + '"' + pat + "\".parse(\"" + str + "\") threw an exception"); e.printStackTrace(); } break; case 9: // strict= true or false strict = "true".equalsIgnoreCase(tokens.next()); logln("Setting strict to:\t" + strict); break; case -1: errln("Unknown command \"" + tok + "\" at " + tokens.describePosition()); return; } } } catch (java.io.IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException ignored) { } } } @Test public void TestFieldPositionDecimal() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); nf.setPositivePrefix("FOO"); nf.setPositiveSuffix("BA"); StringBuffer buffer = new StringBuffer(); FieldPosition fp = new FieldPosition(NumberFormat.Field.DECIMAL_SEPARATOR); nf.format(35.47, buffer, fp); assertEquals("35.47", "FOO35.47BA", buffer.toString()); assertEquals("fp begin", 5, fp.getBeginIndex()); assertEquals("fp end", 6, fp.getEndIndex()); } @Test public void TestFieldPositionInteger() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); nf.setPositivePrefix("FOO"); nf.setPositiveSuffix("BA"); StringBuffer buffer = new StringBuffer(); FieldPosition fp = new FieldPosition(NumberFormat.Field.INTEGER); nf.format(35.47, buffer, fp); assertEquals("35.47", "FOO35.47BA", buffer.toString()); assertEquals("fp begin", 3, fp.getBeginIndex()); assertEquals("fp end", 5, fp.getEndIndex()); } @Test public void TestFieldPositionFractionButInteger() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); nf.setPositivePrefix("FOO"); nf.setPositiveSuffix("BA"); StringBuffer buffer = new StringBuffer(); FieldPosition fp = new FieldPosition(NumberFormat.Field.FRACTION); nf.format(35, buffer, fp); assertEquals("35", "FOO35BA", buffer.toString()); assertEquals("fp begin", 5, fp.getBeginIndex()); assertEquals("fp end", 5, fp.getEndIndex()); } @Test public void TestFieldPositionFraction() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); nf.setPositivePrefix("FOO"); nf.setPositiveSuffix("BA"); StringBuffer buffer = new StringBuffer(); FieldPosition fp = new FieldPosition(NumberFormat.Field.FRACTION); nf.format(35.47, buffer, fp); assertEquals("35.47", "FOO35.47BA", buffer.toString()); assertEquals("fp begin", 6, fp.getBeginIndex()); assertEquals("fp end", 8, fp.getEndIndex()); } @Test public void TestFieldPositionCurrency() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getCurrencyInstance(Locale.US); double amount = 35.47; double negAmount = -34.567; FieldPosition cp = new FieldPosition(NumberFormat.Field.CURRENCY); StringBuffer buffer0 = new StringBuffer(); nf.format(amount, buffer0, cp); assertEquals("$35.47", "$35.47", buffer0.toString()); assertEquals("cp begin", 0, cp.getBeginIndex()); assertEquals("cp end", 1, cp.getEndIndex()); StringBuffer buffer01 = new StringBuffer(); nf.format(negAmount, buffer01, cp); assertEquals("-$34.57", "-$34.57", buffer01.toString()); assertEquals("cp begin", 1, cp.getBeginIndex()); assertEquals("cp end", 2, cp.getEndIndex()); nf.setCurrency(Currency.getInstance(Locale.FRANCE)); StringBuffer buffer1 = new StringBuffer(); nf.format(amount, buffer1, cp); assertEquals("€35.47", "€35.47", buffer1.toString()); assertEquals("cp begin", 0, cp.getBeginIndex()); assertEquals("cp end", 1, cp.getEndIndex()); nf.setCurrency(Currency.getInstance(new Locale("fr", "ch", ""))); StringBuffer buffer2 = new StringBuffer(); nf.format(amount, buffer2, cp); assertEquals("CHF 35.47", "CHF 35.47", buffer2.toString()); assertEquals("cp begin", 0, cp.getBeginIndex()); assertEquals("cp end", 3, cp.getEndIndex()); StringBuffer buffer20 = new StringBuffer(); nf.format(negAmount, buffer20, cp); assertEquals("-CHF 34.57", "-CHF 34.57", buffer20.toString()); assertEquals("cp begin", 1, cp.getBeginIndex()); assertEquals("cp end", 4, cp.getEndIndex()); nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getCurrencyInstance(Locale.FRANCE); StringBuffer buffer3 = new StringBuffer(); nf.format(amount, buffer3, cp); assertEquals("35,47 €", "35,47 €", buffer3.toString()); assertEquals("cp begin", 6, cp.getBeginIndex()); assertEquals("cp end", 7, cp.getEndIndex()); StringBuffer buffer4 = new StringBuffer(); nf.format(negAmount, buffer4, cp); assertEquals("-34,57 €", "-34,57 €", buffer4.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 8, cp.getEndIndex()); nf.setCurrency(Currency.getInstance(new Locale("fr", "ch"))); StringBuffer buffer5 = new StringBuffer(); nf.format(negAmount, buffer5, cp); assertEquals("-34,57 CHF", "-34,57 CHF", buffer5.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 10, cp.getEndIndex()); NumberFormat plCurrencyFmt = NumberFormat.getInstance(new Locale("fr", "ch"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer6 = new StringBuffer(); plCurrencyFmt.format(negAmount, buffer6, cp); assertEquals("-34.57 francs suisses", "-34.57 francs suisses", buffer6.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 21, cp.getEndIndex()); // Positive value with PLURALCURRENCYSTYLE. plCurrencyFmt = NumberFormat.getInstance(new Locale("ja", "ch"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer7 = new StringBuffer(); plCurrencyFmt.format(amount, buffer7, cp); assertEquals("35.47 スイス フラン", "35.47 スイス フラン", buffer7.toString()); assertEquals("cp begin", 6, cp.getBeginIndex()); assertEquals("cp end", 13, cp.getEndIndex()); // PLURALCURRENCYSTYLE for non-ASCII. plCurrencyFmt = NumberFormat.getInstance(new Locale("ja", "de"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer8 = new StringBuffer(); plCurrencyFmt.format(negAmount, buffer8, cp); assertEquals("-34.57 ユーロ", "-34.57 ユーロ", buffer8.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 10, cp.getEndIndex()); nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getCurrencyInstance(Locale.JAPAN); nf.setCurrency(Currency.getInstance(new Locale("ja", "jp"))); StringBuffer buffer9 = new StringBuffer(); nf.format(negAmount, buffer9, cp); assertEquals("-¥35", "-¥35", buffer9.toString()); assertEquals("cp begin", 1, cp.getBeginIndex()); assertEquals("cp end", 2, cp.getEndIndex()); // Negative value with PLURALCURRENCYSTYLE. plCurrencyFmt = NumberFormat.getInstance(new Locale("ja", "ch"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer10 = new StringBuffer(); plCurrencyFmt.format(negAmount, buffer10, cp); assertEquals("-34.57 スイス フラン", "-34.57 スイス フラン", buffer10.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 14, cp.getEndIndex()); // Nagative value with PLURALCURRENCYSTYLE, Arabic digits. nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("ar", "eg")); plCurrencyFmt = NumberFormat.getInstance(new Locale("ar", "eg"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer11 = new StringBuffer(); plCurrencyFmt.format(negAmount, buffer11, cp); assertEquals("؜-٣٤٫٥٧ جنيه مصري", "؜-٣٤٫٥٧ جنيه مصري", buffer11.toString()); assertEquals("cp begin", 8, cp.getBeginIndex()); assertEquals("cp end", 17, cp.getEndIndex()); } @Test public void TestRounding() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); if (false) { // for debugging specific value nf.setRoundingMode(BigDecimal.ROUND_HALF_UP); checkRounding(nf, new BigDecimal("300.0300000000"), 0, new BigDecimal("0.020000000")); } // full tests int[] roundingIncrements = {1, 2, 5, 20, 50, 100}; int[] testValues = {0, 300}; for (int j = 0; j < testValues.length; ++j) { for (int mode = BigDecimal.ROUND_UP; mode < BigDecimal.ROUND_HALF_EVEN; ++mode) { nf.setRoundingMode(mode); for (int increment = 0; increment < roundingIncrements.length; ++increment) { BigDecimal base = new BigDecimal(testValues[j]); BigDecimal rInc = new BigDecimal(roundingIncrements[increment]); checkRounding(nf, base, 20, rInc); rInc = new BigDecimal("1.000000000").divide(rInc); checkRounding(nf, base, 20, rInc); } } } } @Test public void TestRoundingPattern() { class TestRoundingPatternItem { String pattern; BigDecimal roundingIncrement; double testCase; String expected; TestRoundingPatternItem(String pattern, BigDecimal roundingIncrement, double testCase, String expected) { this.pattern = pattern; this.roundingIncrement = roundingIncrement; this.testCase = testCase; this.expected = expected; } }; TestRoundingPatternItem []tests = { new TestRoundingPatternItem("##0.65", new BigDecimal("0.65"), 1.234, "1.30"), new TestRoundingPatternItem("#50", new BigDecimal("50"), 1230, "1250") }; DecimalFormat df = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); String result; for (int i = 0; i < tests.length; i++) { df.applyPattern(tests[i].pattern); result = df.format(tests[i].testCase); if (!tests[i].expected.equals(result)) { errln("String Pattern Rounding Test Failed: Pattern: \"" + tests[i].pattern + "\" Number: " + tests[i].testCase + " - Got: " + result + " Expected: " + tests[i].expected); } df.setRoundingIncrement(tests[i].roundingIncrement); result = df.format(tests[i].testCase); if (!tests[i].expected.equals(result)) { errln("BigDecimal Rounding Test Failed: Pattern: \"" + tests[i].pattern + "\" Number: " + tests[i].testCase + " - Got: " + result + " Expected: " + tests[i].expected); } } } @Test public void TestBigDecimalRounding() { String figure = "50.000000004"; Double dbl = new Double(figure); BigDecimal dec = new BigDecimal(figure); DecimalFormat f = (DecimalFormat) NumberFormat.getInstance(); f.applyPattern("00.00######"); assertEquals("double format", "50.00", f.format(dbl)); assertEquals("bigdec format", "50.00", f.format(dec)); int maxFracDigits = f.getMaximumFractionDigits(); BigDecimal roundingIncrement = new BigDecimal("1").movePointLeft(maxFracDigits); f.setRoundingIncrement(roundingIncrement); f.setRoundingMode(BigDecimal.ROUND_DOWN); assertEquals("Rounding down", f.format(dbl), f.format(dec)); f.setRoundingIncrement(roundingIncrement); f.setRoundingMode(BigDecimal.ROUND_HALF_UP); assertEquals("Rounding half up", f.format(dbl), f.format(dec)); } void checkRounding(DecimalFormat nf, BigDecimal base, int iterations, BigDecimal increment) { nf.setRoundingIncrement(increment.toBigDecimal()); BigDecimal lastParsed = new BigDecimal(Integer.MIN_VALUE); // used to make sure that rounding is monotonic for (int i = -iterations; i <= iterations; ++i) { BigDecimal iValue = base.add(increment.multiply(new BigDecimal(i)).movePointLeft(1)); BigDecimal smallIncrement = new BigDecimal("0.00000001"); if (iValue.signum() != 0) { smallIncrement.multiply(iValue); // scale unless zero } // we not only test the value, but some values in a small range around it. lastParsed = checkRound(nf, iValue.subtract(smallIncrement), lastParsed); lastParsed = checkRound(nf, iValue, lastParsed); lastParsed = checkRound(nf, iValue.add(smallIncrement), lastParsed); } } private BigDecimal checkRound(DecimalFormat nf, BigDecimal iValue, BigDecimal lastParsed) { String formatedBigDecimal = nf.format(iValue); String formattedDouble = nf.format(iValue.doubleValue()); if (!equalButForTrailingZeros(formatedBigDecimal, formattedDouble)) { errln("Failure at: " + iValue + " (" + iValue.doubleValue() + ")" + ",\tRounding-mode: " + roundingModeNames[nf.getRoundingMode()] + ",\tRounding-increment: " + nf.getRoundingIncrement() + ",\tdouble: " + formattedDouble + ",\tBigDecimal: " + formatedBigDecimal); } else { logln("Value: " + iValue + ",\tRounding-mode: " + roundingModeNames[nf.getRoundingMode()] + ",\tRounding-increment: " + nf.getRoundingIncrement() + ",\tdouble: " + formattedDouble + ",\tBigDecimal: " + formatedBigDecimal); } try { // Number should have compareTo(...) BigDecimal parsed = toBigDecimal(nf.parse(formatedBigDecimal)); if (lastParsed.compareTo(parsed) > 0) { errln("Rounding wrong direction!: " + lastParsed + " > " + parsed); } lastParsed = parsed; } catch (ParseException e) { errln("Parse Failure with: " + formatedBigDecimal); } return lastParsed; } static BigDecimal toBigDecimal(Number number) { return number instanceof BigDecimal ? (BigDecimal) number : number instanceof BigInteger ? new BigDecimal((BigInteger)number) : number instanceof java.math.BigDecimal ? new BigDecimal((java.math.BigDecimal)number) : number instanceof Double ? new BigDecimal(number.doubleValue()) : number instanceof Float ? new BigDecimal(number.floatValue()) : new BigDecimal(number.longValue()); } static String[] roundingModeNames = { "ROUND_UP", "ROUND_DOWN", "ROUND_CEILING", "ROUND_FLOOR", "ROUND_HALF_UP", "ROUND_HALF_DOWN", "ROUND_HALF_EVEN", "ROUND_UNNECESSARY" }; private static boolean equalButForTrailingZeros(String formatted1, String formatted2) { if (formatted1.length() == formatted2.length()) return formatted1.equals(formatted2); return stripFinalZeros(formatted1).equals(stripFinalZeros(formatted2)); } private static String stripFinalZeros(String formatted) { int len1 = formatted.length(); char ch; while (len1 > 0 && ((ch = formatted.charAt(len1-1)) == '0' || ch == '.')) --len1; if (len1==1 && ((ch = formatted.charAt(len1-1)) == '-')) --len1; return formatted.substring(0,len1); } //------------------------------------------------------------------ // Support methods //------------------------------------------------------------------ /** Format-Parse test */ public void expect2(NumberFormat fmt, Number n, String exp) { // Don't round-trip format test, since we explicitly do it expect(fmt, n, exp, false); expect(fmt, exp, n); } /** Format-Parse test */ public void expect3(NumberFormat fmt, Number n, String exp) { // Don't round-trip format test, since we explicitly do it expect_rbnf(fmt, n, exp, false); expect_rbnf(fmt, exp, n); } /** Format-Parse test (convenience) */ public void expect2(NumberFormat fmt, double n, String exp) { expect2(fmt, new Double(n), exp); } /** RBNF Format-Parse test (convenience) */ public void expect3(NumberFormat fmt, double n, String exp) { expect3(fmt, new Double(n), exp); } /** Format-Parse test (convenience) */ public void expect2(NumberFormat fmt, long n, String exp) { expect2(fmt, new Long(n), exp); } /** RBNF Format-Parse test (convenience) */ public void expect3(NumberFormat fmt, long n, String exp) { expect3(fmt, new Long(n), exp); } /** Format test */ public void expect(NumberFormat fmt, Number n, String exp, boolean rt) { StringBuffer saw = new StringBuffer(); FieldPosition pos = new FieldPosition(0); fmt.format(n, saw, pos); String pat = ((DecimalFormat)fmt).toPattern(); if (saw.toString().equals(exp)) { logln("Ok " + n + " x " + pat + " = \"" + saw + "\""); // We should be able to round-trip the formatted string => // number => string (but not the other way around: number // => string => number2, might have number2 != number): if (rt) { try { Number n2 = fmt.parse(exp); StringBuffer saw2 = new StringBuffer(); fmt.format(n2, saw2, pos); if (!saw2.toString().equals(exp)) { errln("expect() format test rt, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL \"" + exp + "\" => " + n2 + " => \"" + saw2 + '"'); } } catch (ParseException e) { errln("expect() format test rt, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", " + e.getMessage()); return; } } } else { errln("expect() format test, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL " + n + " x " + pat + " = \"" + saw + "\", expected \"" + exp + "\""); } } /** RBNF format test */ public void expect_rbnf(NumberFormat fmt, Number n, String exp, boolean rt) { StringBuffer saw = new StringBuffer(); FieldPosition pos = new FieldPosition(0); fmt.format(n, saw, pos); if (saw.toString().equals(exp)) { logln("Ok " + n + " = \"" + saw + "\""); // We should be able to round-trip the formatted string => // number => string (but not the other way around: number // => string => number2, might have number2 != number): if (rt) { try { Number n2 = fmt.parse(exp); StringBuffer saw2 = new StringBuffer(); fmt.format(n2, saw2, pos); if (!saw2.toString().equals(exp)) { errln("expect_rbnf() format test rt, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL \"" + exp + "\" => " + n2 + " => \"" + saw2 + '"'); } } catch (ParseException e) { errln("expect_rbnf() format test rt, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", " + e.getMessage()); return; } } } else { errln("expect_rbnf() format test, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL " + n + " = \"" + saw + "\", expected \"" + exp + "\""); } } /** Format test (convenience) */ public void expect(NumberFormat fmt, Number n, String exp) { expect(fmt, n, exp, true); } /** Format test (convenience) */ public void expect(NumberFormat fmt, double n, String exp) { expect(fmt, new Double(n), exp); } /** Format test (convenience) */ public void expect(NumberFormat fmt, long n, String exp) { expect(fmt, new Long(n), exp); } /** Parse test */ public void expect(NumberFormat fmt, String str, Number n) { Number num = null; try { num = fmt.parse(str); } catch (ParseException e) { errln(e.getMessage()); return; } String pat = ((DecimalFormat)fmt).toPattern(); // A little tricky here -- make sure Double(12345.0) and // Long(12345) match. if (num.equals(n) || num.doubleValue() == n.doubleValue()) { logln("Ok \"" + str + "\" x " + pat + " = " + num); } else { errln("expect() parse test, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL \"" + str + "\" x " + pat + " = " + num + ", expected " + n); } } /** RBNF Parse test */ public void expect_rbnf(NumberFormat fmt, String str, Number n) { Number num = null; try { num = fmt.parse(str); } catch (ParseException e) { errln(e.getMessage()); return; } // A little tricky here -- make sure Double(12345.0) and // Long(12345) match. if (num.equals(n) || num.doubleValue() == n.doubleValue()) { logln("Ok \"" + str + " = " + num); } else { errln("expect_rbnf() parse test, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL \"" + str + " = " + num + ", expected " + n); } } /** Parse test (convenience) */ public void expect(NumberFormat fmt, String str, double n) { expect(fmt, str, new Double(n)); } /** Parse test (convenience) */ public void expect(NumberFormat fmt, String str, long n) { expect(fmt, str, new Long(n)); } /** Parse test */ public void expectParseException(DecimalFormat fmt, String str, Number n) { Number num = null; try { num = fmt.parse(str); errln("Expected failure, but passed: " + n + " on " + fmt.toPattern() + " -> " + num); } catch (ParseException e) { } } private void expectCurrency(NumberFormat nf, Currency curr, double value, String string) { DecimalFormat fmt = (DecimalFormat) nf; if (curr != null) { fmt.setCurrency(curr); } String s = fmt.format(value).replace('\u00A0', ' '); if (s.equals(string)) { logln("Ok: " + value + " x " + curr + " => " + s); } else { errln("FAIL: " + value + " x " + curr + " => " + s + ", expected " + string); } } public void expectPad(DecimalFormat fmt, String pat, int pos) { expectPad(fmt, pat, pos, 0, (char)0); } public void expectPad(DecimalFormat fmt, final String pat, int pos, int width, final char pad) { int apos = 0, awidth = 0; char apadStr; try { fmt.applyPattern(pat); apos = fmt.getPadPosition(); awidth = fmt.getFormatWidth(); apadStr = fmt.getPadCharacter(); } catch (Exception e) { apos = -1; awidth = width; apadStr = pad; } if (apos == pos && awidth == width && apadStr == pad) { logln("Ok \"" + pat + "\" pos=" + apos + ((pos == -1) ? "" : " width=" + awidth + " pad=" + apadStr)); } else { errln("FAIL \"" + pat + "\" pos=" + apos + " width=" + awidth + " pad=" + apadStr + ", expected " + pos + " " + width + " " + pad); } } public void expectPat(DecimalFormat fmt, final String exp) { String pat = fmt.toPattern(); if (pat.equals(exp)) { logln("Ok \"" + pat + "\""); } else { errln("FAIL \"" + pat + "\", expected \"" + exp + "\""); } } private void expectParseCurrency(NumberFormat fmt, Currency expected, String text) { ParsePosition pos = new ParsePosition(0); CurrencyAmount currencyAmount = fmt.parseCurrency(text, pos); assertTrue("Parse of " + text + " should have succeeded.", pos.getIndex() > 0); assertEquals("Currency should be correct.", expected, currencyAmount.getCurrency()); } @Test public void TestJB3832(){ ULocale locale = new ULocale("pt_PT@currency=PTE"); NumberFormat format = NumberFormat.getCurrencyInstance(locale); Currency curr = Currency.getInstance(locale); logln("\nName of the currency is: " + curr.getName(locale, Currency.LONG_NAME, new boolean[] {false})); CurrencyAmount cAmt = new CurrencyAmount(1150.50, curr); logln("CurrencyAmount object's hashCode is: " + cAmt.hashCode()); //cover hashCode String str = format.format(cAmt); String expected = "1,150$50\u00a0\u200b"; if(!expected.equals(str)){ errln("Did not get the expected output Expected: "+expected+" Got: "+ str); } } @Test public void TestScientificWithGrouping() { // Grouping separators are not allowed in the pattern, but we can enable them via the API. DecimalFormat df = new DecimalFormat("###0.000E0"); df.setGroupingUsed(true); df.setGroupingSize(3); expect2(df, 123, "123.0E0"); expect2(df, 1234, "1,234E0"); expect2(df, 12340, "1.234E4"); } @Test public void TestStrictParse() { // Pass both strict and lenient: String[] pass = { "0", // single zero before end of text is not leading "0 ", // single zero at end of number is not leading "0.", // single zero before period (or decimal, it's ambiguous) is not leading "0,", // single zero before comma (not group separator) is not leading "0.0", // single zero before decimal followed by digit is not leading "0. ", // same as above before period (or decimal) is not leading "0.100,5", // comma stops parse of decimal (no grouping) "0.100,,5", // two commas also stops parse ".00", // leading decimal is ok, even with zeros "1234567", // group separators are not required "12345, ", // comma not followed by digit is not a group separator, but end of number "1,234, ", // if group separator is present, group sizes must be appropriate "1,234,567", // ...secondary too "0E", // an exponent not followed by zero or digits is not an exponent "00", // leading zero before zero - used to be error - see ticket #7913 "012", // leading zero before digit - used to be error - see ticket #7913 "0,456", // leading zero before group separator - used to be error - see ticket #7913 "999,999", // see ticket #6863 "-99,999", // see ticket #6863 "-999,999", // see ticket #6863 "-9,999,999", // see ticket #6863 }; // Pass lenient, fail strict: String[] fail = { "1,2", // wrong number of digits after group separator ",.02", // leading group separator before decimal "1,.02", // group separator before decimal ",0", // leading group separator before a single digit ",1", // leading group separator before a single digit "1,45", // wrong number of digits in primary group "1,45 that", // wrong number of digits in primary group "1,45.34", // wrong number of digits in primary group "1234,567", // wrong number of digits in secondary group "12,34,567", // wrong number of digits in secondary group "1,23,456,7890", // wrong number of digits in primary and secondary groups }; // Fail both lenient and strict: String[] failBoth = { }; DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); runStrictParseBatch(nf, pass, fail, failBoth); String[] scientificPass = { "0E2", // single zero before exponent is ok "1234E2", // any number of digits before exponent is ok "1,234E", // an exponent string not followed by zero or digits is not an exponent "00E2", // leading zeroes now allowed in strict mode - see ticket # }; String[] scientificFail = { }; String[] scientificFailBoth = { }; nf = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); runStrictParseBatch(nf, scientificPass, scientificFail, scientificFailBoth); String[] mixedPass = { "12,34,567", "12,34,567,", "12,34,567, that", "12,34,567 that", }; String[] mixedFail = { "12,34,56", "12,34,56,", "12,34,56, that ", "12,34,56 that", }; String[] mixedFailBoth = { }; nf = new DecimalFormat("#,##,##0.#"); runStrictParseBatch(nf, mixedPass, mixedFail, mixedFailBoth); } void runStrictParseBatch(DecimalFormat nf, String[] pass, String[] fail, String[] failBoth) { nf.setParseStrict(false); runStrictParseTests("should pass", nf, pass, true); runStrictParseTests("should also pass", nf, fail, true); runStrictParseTests("should fail", nf, failBoth, false); nf.setParseStrict(true); runStrictParseTests("should still pass", nf, pass, true); runStrictParseTests("should fail", nf, fail, false); runStrictParseTests("should still fail", nf, failBoth, false); } void runStrictParseTests(String msg, DecimalFormat nf, String[] tests, boolean pass) { logln(""); logln("pattern: '" + nf.toPattern() + "'"); logln(msg); for (int i = 0; i < tests.length; ++i) { String str = tests[i]; ParsePosition pp = new ParsePosition(0); Number n = nf.parse(str, pp); String formatted = n != null ? nf.format(n) : "null"; String err = pp.getErrorIndex() == -1 ? "" : "(error at " + pp.getErrorIndex() + ")"; if ((err.length() == 0) != pass) { errln("'" + str + "' parsed '" + str.substring(0, pp.getIndex()) + "' returned " + n + " formats to '" + formatted + "' " + err); } else { if (err.length() > 0) { err = "got expected " + err; } logln("'" + str + "' parsed '" + str.substring(0, pp.getIndex()) + "' returned " + n + " formats to '" + formatted + "' " + err); } } } @Test public void TestJB5251(){ //save default locale ULocale defaultLocale = ULocale.getDefault(); ULocale.setDefault(new ULocale("qr_QR")); try { NumberFormat.getInstance(); } catch (Exception e) { errln("Numberformat threw exception for non-existent locale. It should use the default."); } //reset default locale ULocale.setDefault(defaultLocale); } @Test public void TestParseReturnType() { String[] defaultLong = { "123", "123.0", "0.0", "-9223372036854775808", // Min Long "9223372036854775807" // Max Long }; String[] defaultNonLong = { "12345678901234567890", "9223372036854775808", "-9223372036854775809" }; String[] doubles = { "-0.0", "NaN", "\u221E" // Infinity }; DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); DecimalFormat nf = new DecimalFormat("#.#", sym); if (nf.isParseBigDecimal()) { errln("FAIL: isParseDecimal() must return false by default"); } // isParseBigDecimal() is false for (int i = 0; i < defaultLong.length; i++) { try { Number n = nf.parse(defaultLong[i]); if (!(n instanceof Long)) { errln("FAIL: parse does not return Long instance"); } } catch (ParseException e) { errln("parse of '" + defaultLong[i] + "' threw exception: " + e); } } for (int i = 0; i < defaultNonLong.length; i++) { try { Number n = nf.parse(defaultNonLong[i]); if (n instanceof Long) { errln("FAIL: parse returned a Long"); } } catch (ParseException e) { errln("parse of '" + defaultNonLong[i] + "' threw exception: " + e); } } // parse results for doubls must be always Double for (int i = 0; i < doubles.length; i++) { try { Number n = nf.parse(doubles[i]); if (!(n instanceof Double)) { errln("FAIL: parse does not return Double instance"); } } catch (ParseException e) { errln("parse of '" + doubles[i] + "' threw exception: " + e); } } // force this DecimalFormat to return BigDecimal nf.setParseBigDecimal(true); if (!nf.isParseBigDecimal()) { errln("FAIL: isParseBigDecimal() must return true"); } // isParseBigDecimal() is true for (int i = 0; i < defaultLong.length + defaultNonLong.length; i++) { String input = (i < defaultLong.length) ? defaultLong[i] : defaultNonLong[i - defaultLong.length]; try { Number n = nf.parse(input); if (!(n instanceof BigDecimal)) { errln("FAIL: parse does not return BigDecimal instance"); } } catch (ParseException e) { errln("parse of '" + input + "' threw exception: " + e); } } // parse results for doubls must be always Double for (int i = 0; i < doubles.length; i++) { try { Number n = nf.parse(doubles[i]); if (!(n instanceof Double)) { errln("FAIL: parse does not return Double instance"); } } catch (ParseException e) { errln("parse of '" + doubles[i] + "' threw exception: " + e); } } } @Test public void TestNonpositiveMultiplier() { DecimalFormat df = new DecimalFormat("0"); // test zero multiplier try { df.setMultiplier(0); // bad errln("DecimalFormat.setMultiplier(0) did not throw an IllegalArgumentException"); } catch (IllegalArgumentException ex) { // good } // test negative multiplier try { df.setMultiplier(-1); if (df.getMultiplier() != -1) { errln("DecimalFormat.setMultiplier(-1) did not change the multiplier to -1"); return; } // good } catch (IllegalArgumentException ex) { // bad errln("DecimalFormat.setMultiplier(-1) threw an IllegalArgumentException"); return; } expect(df, "1122.123", -1122.123); expect(df, "-1122.123", 1122.123); expect(df, "1.2", -1.2); expect(df, "-1.2", 1.2); expect2(df, Long.MAX_VALUE, BigInteger.valueOf(Long.MAX_VALUE).negate().toString()); expect2(df, Long.MIN_VALUE, BigInteger.valueOf(Long.MIN_VALUE).negate().toString()); expect2(df, Long.MAX_VALUE / 2, BigInteger.valueOf(Long.MAX_VALUE / 2).negate().toString()); expect2(df, Long.MIN_VALUE / 2, BigInteger.valueOf(Long.MIN_VALUE / 2).negate().toString()); expect2(df, BigDecimal.valueOf(Long.MAX_VALUE), BigDecimal.valueOf(Long.MAX_VALUE).negate().toString()); expect2(df, BigDecimal.valueOf(Long.MIN_VALUE), BigDecimal.valueOf(Long.MIN_VALUE).negate().toString()); expect2(df, java.math.BigDecimal.valueOf(Long.MAX_VALUE), java.math.BigDecimal.valueOf(Long.MAX_VALUE).negate().toString()); expect2(df, java.math.BigDecimal.valueOf(Long.MIN_VALUE), java.math.BigDecimal.valueOf(Long.MIN_VALUE).negate().toString()); } @Test public void TestJB5358() { int numThreads = 10; String numstr = "12345"; double expected = 12345; DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt = new DecimalFormat("#.#", sym); ArrayList errors = new ArrayList(); ParseThreadJB5358[] threads = new ParseThreadJB5358[numThreads]; for (int i = 0; i < numThreads; i++) { threads[i] = new ParseThreadJB5358((DecimalFormat)fmt.clone(), numstr, expected, errors); threads[i].start(); } for (int i = 0; i < numThreads; i++) { try { threads[i].join(); } catch (InterruptedException ie) { ie.printStackTrace(); } } if (errors.size() != 0) { StringBuffer errBuf = new StringBuffer(); for (int i = 0; i < errors.size(); i++) { errBuf.append((String)errors.get(i)); errBuf.append("\n"); } errln("FAIL: " + errBuf); } } static private class ParseThreadJB5358 extends Thread { private final DecimalFormat decfmt; private final String numstr; private final double expect; private final ArrayList errors; public ParseThreadJB5358(DecimalFormat decfmt, String numstr, double expect, ArrayList errors) { this.decfmt = decfmt; this.numstr = numstr; this.expect = expect; this.errors = errors; } @Override public void run() { for (int i = 0; i < 10000; i++) { try { Number n = decfmt.parse(numstr); if (n.doubleValue() != expect) { synchronized(errors) { errors.add(new String("Bad parse result - expected:" + expect + " actual:" + n.doubleValue())); } } } catch (Throwable t) { synchronized(errors) { errors.add(new String(t.getClass().getName() + " - " + t.getMessage())); } } } } } @Test public void TestSetCurrency() { DecimalFormatSymbols decf1 = DecimalFormatSymbols.getInstance(ULocale.US); DecimalFormatSymbols decf2 = DecimalFormatSymbols.getInstance(ULocale.US); decf2.setCurrencySymbol("UKD"); DecimalFormat format1 = new DecimalFormat("000.000", decf1); DecimalFormat format2 = new DecimalFormat("000.000", decf2); Currency euro = Currency.getInstance("EUR"); format1.setCurrency(euro); format2.setCurrency(euro); assertEquals("Reset with currency symbol", format1, format2); } /* * Testing the method public StringBuffer format(Object number, ...) */ @Test public void TestFormat() { NumberFormat nf = NumberFormat.getInstance(); StringBuffer sb = new StringBuffer("dummy"); FieldPosition fp = new FieldPosition(0); // Tests when "if (number instanceof Long)" is true try { nf.format(new Long("0"), sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a Long object. Error: " + e); } // Tests when "else if (number instanceof BigInteger)" is true try { nf.format((Object)new BigInteger("0"), sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a BigInteger object. Error: " + e); } // Tests when "else if (number instanceof java.math.BigDecimal)" is true try { nf.format((Object)new java.math.BigDecimal("0"), sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a java.math.BigDecimal object. Error: " + e); } // Tests when "else if (number instanceof com.ibm.icu.math.BigDecimal)" is true try { nf.format((Object)new com.ibm.icu.math.BigDecimal("0"), sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a com.ibm.icu.math.BigDecimal object. Error: " + e); } // Tests when "else if (number instanceof CurrencyAmount)" is true try { CurrencyAmount ca = new CurrencyAmount(0.0, Currency.getInstance(new ULocale("en_US"))); nf.format((Object)ca, sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a CurrencyAmount object. Error: " + e); } // Tests when "else if (number instanceof Number)" is true try { nf.format(0.0, sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "to return an exception for a Number object. Error: " + e); } // Tests when "else" is true try { nf.format(new Object(), sb, fp); errln("NumberFormat.format(Object number, ...) was suppose to " + "return an exception for an invalid object."); } catch (Exception e) { } try { nf.format(new String("dummy"), sb, fp); errln("NumberFormat.format(Object number, ...) was suppose to " + "return an exception for an invalid object."); } catch (Exception e) { } } /* * Coverage tests for the implementation of abstract format methods not being called otherwise */ @Test public void TestFormatAbstractImplCoverage() { NumberFormat df = DecimalFormat.getInstance(Locale.ENGLISH); NumberFormat cdf = CompactDecimalFormat.getInstance(Locale.ENGLISH, CompactDecimalFormat.CompactStyle.SHORT); NumberFormat rbf = new RuleBasedNumberFormat(ULocale.ENGLISH, RuleBasedNumberFormat.SPELLOUT); /* * Test NumberFormat.format(BigDecimal,StringBuffer,FieldPosition) */ StringBuffer sb = new StringBuffer(); String result = df.format(new BigDecimal(2000.43), sb, new FieldPosition(0)).toString(); if (!"2,000.43".equals(result)) { errln("DecimalFormat failed. Expected: 2,000.43 - Actual: " + result); } sb.delete(0, sb.length()); result = cdf.format(new BigDecimal(2000.43), sb, new FieldPosition(0)).toString(); if (!"2K".equals(result)) { errln("DecimalFormat failed. Expected: 2K - Actual: " + result); } sb.delete(0, sb.length()); result = rbf.format(new BigDecimal(2000.43), sb, new FieldPosition(0)).toString(); if (!"two thousand point four three".equals(result)) { errln("DecimalFormat failed. Expected: 'two thousand point four three' - Actual: '" + result + "'"); } } /* * Tests the method public final static NumberFormat getInstance(int style) public static NumberFormat * getInstance(Locale inLocale, int style) public static NumberFormat getInstance(ULocale desiredLocale, int choice) */ @Test public void TestGetInstance() { // Tests "public final static NumberFormat getInstance(int style)" int maxStyle = NumberFormat.STANDARDCURRENCYSTYLE; int[] invalid_cases = { NumberFormat.NUMBERSTYLE - 1, NumberFormat.NUMBERSTYLE - 2, maxStyle + 1, maxStyle + 2 }; for (int i = NumberFormat.NUMBERSTYLE; i < maxStyle; i++) { try { NumberFormat.getInstance(i); } catch (Exception e) { errln("NumberFormat.getInstance(int style) was not suppose to " + "return an exception for passing value of " + i); } } for (int i = 0; i < invalid_cases.length; i++) { try { NumberFormat.getInstance(invalid_cases[i]); errln("NumberFormat.getInstance(int style) was suppose to " + "return an exception for passing value of " + invalid_cases[i]); } catch (Exception e) { } } // Tests "public static NumberFormat getInstance(Locale inLocale, int style)" String[] localeCases = { "en_US", "fr_FR", "de_DE", "jp_JP" }; for (int i = NumberFormat.NUMBERSTYLE; i < maxStyle; i++) { for (int j = 0; j < localeCases.length; j++) { try { NumberFormat.getInstance(new Locale(localeCases[j]), i); } catch (Exception e) { errln("NumberFormat.getInstance(Locale inLocale, int style) was not suppose to " + "return an exception for passing value of " + localeCases[j] + ", " + i); } } } // Tests "public static NumberFormat getInstance(ULocale desiredLocale, int choice)" // Tests when "if (choice < NUMBERSTYLE || choice > PLURALCURRENCYSTYLE)" is true for (int i = 0; i < invalid_cases.length; i++) { try { NumberFormat.getInstance((ULocale) null, invalid_cases[i]); errln("NumberFormat.getInstance(ULocale inLocale, int choice) was not suppose to " + "return an exception for passing value of " + invalid_cases[i]); } catch (Exception e) { } } } /* * Tests the class public static abstract class NumberFormatFactory */ @Test public void TestNumberFormatFactory() { /* * The following class allows the method public NumberFormat createFormat(Locale loc, int formatType) to be * tested. */ class TestFactory extends NumberFormatFactory { @Override public Set<String> getSupportedLocaleNames() { return null; } @Override public NumberFormat createFormat(ULocale loc, int formatType) { return null; } } /* * The following class allows the method public NumberFormat createFormat(ULocale loc, int formatType) to be * tested. */ class TestFactory1 extends NumberFormatFactory { @Override public Set<String> getSupportedLocaleNames() { return null; } @Override public NumberFormat createFormat(Locale loc, int formatType) { return null; } } TestFactory tf = new TestFactory(); TestFactory1 tf1 = new TestFactory1(); /* * Tests the method public boolean visible() */ if (tf.visible() != true) { errln("NumberFormatFactory.visible() was suppose to return true."); } /* * Tests the method public NumberFormat createFormat(Locale loc, int formatType) */ if (tf.createFormat(new Locale(""), 0) != null) { errln("NumberFormatFactory.createFormat(Locale loc, int formatType) " + "was suppose to return null"); } /* * Tests the method public NumberFormat createFormat(ULocale loc, int formatType) */ if (tf1.createFormat(new ULocale(""), 0) != null) { errln("NumberFormatFactory.createFormat(ULocale loc, int formatType) " + "was suppose to return null"); } } /* * Tests the class public static abstract class SimpleNumberFormatFactory extends NumberFormatFactory */ @Test public void TestSimpleNumberFormatFactory() { class TestSimpleNumberFormatFactory extends SimpleNumberFormatFactory { /* * Tests the method public SimpleNumberFormatFactory(Locale locale) */ TestSimpleNumberFormatFactory() { super(new Locale("")); } } @SuppressWarnings("unused") TestSimpleNumberFormatFactory tsnff = new TestSimpleNumberFormatFactory(); } /* * Tests the method public static ULocale[] getAvailableLocales() */ @SuppressWarnings("static-access") @Test public void TestGetAvailableLocales() { // Tests when "if (shim == null)" is true @SuppressWarnings("serial") class TestGetAvailableLocales extends NumberFormat { @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(java.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public Number parse(String text, ParsePosition parsePosition) { return null; } } try { TestGetAvailableLocales test = new TestGetAvailableLocales(); test.getAvailableLocales(); } catch (Exception e) { errln("NumberFormat.getAvailableLocales() was not suppose to " + "return an exception when getting getting available locales."); } } /* * Tests the method public void setMinimumIntegerDigits(int newValue) */ @Test public void TestSetMinimumIntegerDigits() { NumberFormat nf = NumberFormat.getInstance(); // For valid array, it is displayed as {min value, max value} // Tests when "if (minimumIntegerDigits > maximumIntegerDigits)" is true int[][] cases = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 2, 0 }, { 2, 1 }, { 10, 0 } }; int[] expectedMax = { 1, 1, 0, 0, 1, 0 }; if (cases.length != expectedMax.length) { errln("Can't continue test case method TestSetMinimumIntegerDigits " + "since the test case arrays are unequal."); } else { for (int i = 0; i < cases.length; i++) { nf.setMinimumIntegerDigits(cases[i][0]); nf.setMaximumIntegerDigits(cases[i][1]); if (nf.getMaximumIntegerDigits() != expectedMax[i]) { errln("NumberFormat.setMinimumIntegerDigits(int newValue " + "did not return an expected result for parameter " + cases[i][0] + " and " + cases[i][1] + " and expected " + expectedMax[i] + " but got " + nf.getMaximumIntegerDigits()); } } } } /* * Tests the method public int getRoundingMode() public void setRoundingMode(int roundingMode) */ @Test public void TestRoundingMode() { @SuppressWarnings("serial") class TestRoundingMode extends NumberFormat { @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(java.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public Number parse(String text, ParsePosition parsePosition) { return null; } } TestRoundingMode tgrm = new TestRoundingMode(); // Tests the function 'public void setRoundingMode(int roundingMode)' try { tgrm.setRoundingMode(0); errln("NumberFormat.setRoundingMode(int) was suppose to return an exception"); } catch (Exception e) { } // Tests the function 'public int getRoundingMode()' try { tgrm.getRoundingMode(); errln("NumberFormat.getRoundingMode() was suppose to return an exception"); } catch (Exception e) { } } /* * Testing lenient decimal/grouping separator parsing */ @Test public void TestLenientSymbolParsing() { DecimalFormat fmt = new DecimalFormat(); DecimalFormatSymbols sym = new DecimalFormatSymbols(); expect(fmt, "12\u300234", 12.34); // Ticket#7345 - case 1 // Even strict parsing, the decimal separator set in the symbols // should be successfully parsed. sym.setDecimalSeparator('\u3002'); // non-strict fmt.setDecimalFormatSymbols(sym); // strict - failed before the fix for #7345 fmt.setParseStrict(true); expect(fmt, "23\u300245", 23.45); fmt.setParseStrict(false); // Ticket#7345 - case 2 // Decimal separator variants other than DecimalFormatSymbols.decimalSeparator // should not hide the grouping separator DecimalFormatSymbols.groupingSeparator. sym.setDecimalSeparator('.'); sym.setGroupingSeparator(','); fmt.setDecimalFormatSymbols(sym); expect(fmt, "1,234.56", 1234.56); sym.setGroupingSeparator('\uFF61'); fmt.setDecimalFormatSymbols(sym); expect(fmt, "2\uFF61345.67", 2345.67); // Ticket#7128 // sym.setGroupingSeparator(','); fmt.setDecimalFormatSymbols(sym); String skipExtSepParse = ICUConfig.get("com.ibm.icu.text.DecimalFormat.SkipExtendedSeparatorParsing", "false"); if (skipExtSepParse.equals("true")) { // When the property SkipExtendedSeparatorParsing is true, // DecimalFormat does not use the extended equivalent separator // data and only uses the one in DecimalFormatSymbols. expect(fmt, "23 456", 23); } else { // Lenient separator parsing is enabled by default. // A space character below is interpreted as a // group separator, even ',' is used as grouping // separator in the symbols. expect(fmt, "12 345", 12345); } } /* * Testing currency driven max/min fraction digits problem * reported by ticket#7282 */ @Test public void TestCurrencyFractionDigits() { double value = 99.12345; // Create currency instance NumberFormat cfmt = NumberFormat.getCurrencyInstance(new ULocale("ja_JP")); String text1 = cfmt.format(value); // Reset the same currency and format the test value again cfmt.setCurrency(cfmt.getCurrency()); String text2 = cfmt.format(value); // output1 and output2 must be identical if (!text1.equals(text2)) { errln("NumberFormat.format() should return the same result - text1=" + text1 + " text2=" + text2); } } /* * Testing rounding to negative zero problem * reported by ticket#7609 */ @Test public void TestNegZeroRounding() { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(); df.setRoundingMode(MathContext.ROUND_HALF_UP); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(1); String text1 = df.format(-0.01); df.setRoundingIncrement(0.1); String text2 = df.format(-0.01); // output1 and output2 must be identical if (!text1.equals(text2)) { errln("NumberFormat.format() should return the same result - text1=" + text1 + " text2=" + text2); } } @Test public void TestCurrencyAmountCoverage() { CurrencyAmount ca, cb; try { ca = new CurrencyAmount(null, (Currency) null); errln("NullPointerException should have been thrown."); } catch (NullPointerException ex) { } try { ca = new CurrencyAmount(new Integer(0), (Currency) null); errln("NullPointerException should have been thrown."); } catch (NullPointerException ex) { } ca = new CurrencyAmount(new Integer(0), Currency.getInstance(new ULocale("ja_JP"))); cb = new CurrencyAmount(new Integer(1), Currency.getInstance(new ULocale("ja_JP"))); if (ca.equals(null)) { errln("Comparison should return false."); } if (!ca.equals(ca)) { errln("Comparision should return true."); } if (ca.equals(cb)) { errln("Comparison should return false."); } } @Test public void TestExponentParse() { ParsePosition parsePos = new ParsePosition(0); DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt = new DecimalFormat("#####", symbols); Number result = fmt.parse("5.06e-27", parsePos); if ( result.doubleValue() != 5.06E-27 || parsePos.getIndex() != 8) { errln("ERROR: ERROR: parse failed - expected 5.06E-27, 8; got " + result.doubleValue() + ", " + parsePos.getIndex()); } } @Test public void TestExplicitParents() { // We use these for testing because decimal and grouping separators will be inherited from es_419 // starting with CLDR 2.0 String[] DATA = { "es", "CO", "", "1.250,75", "es", "ES", "", "1.250,75", "es", "GQ", "", "1.250,75", "es", "MX", "", "1,250.75", "es", "US", "", "1,250.75", "es", "VE", "", "1.250,75", }; for (int i=0; i<DATA.length; i+=4) { Locale locale = new Locale(DATA[i], DATA[i+1], DATA[i+2]); NumberFormat fmt = NumberFormat.getInstance(locale); String s = fmt.format(1250.75); if (s.equals(DATA[i+3])) { logln("Ok: 1250.75 x " + locale + " => " + s); } else { errln("FAIL: 1250.75 x " + locale + " => " + s + ", expected " + DATA[i+3]); } } } /* * Test case for #9240 * ICU4J 49.1 DecimalFormat did not clone the internal object holding * formatted text attribute information properly. Therefore, DecimalFormat * created by cloning may return incorrect results or may throw an exception * when formatToCharacterIterator is invoked from multiple threads. */ @Test public void TestFormatToCharacterIteratorThread() { final int COUNT = 10; DecimalFormat fmt1 = new DecimalFormat("#0"); DecimalFormat fmt2 = (DecimalFormat)fmt1.clone(); int[] res1 = new int[COUNT]; int[] res2 = new int[COUNT]; Thread t1 = new Thread(new FormatCharItrTestThread(fmt1, 1, res1)); Thread t2 = new Thread(new FormatCharItrTestThread(fmt2, 100, res2)); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { //TODO } int val1 = res1[0]; int val2 = res2[0]; for (int i = 0; i < COUNT; i++) { if (res1[i] != val1) { errln("Inconsistent first run limit in test thread 1"); } if (res2[i] != val2) { errln("Inconsistent first run limit in test thread 2"); } } } /* * This feature had to do with a limitation in DigitList.java that no longer exists in the * new implementation. * @Test public void TestParseMaxDigits() { DecimalFormat fmt = new DecimalFormat(); String number = "100000000000"; int newParseMax = number.length() - 1; fmt.setParseMaxDigits(-1); // Default value is 1000 if (fmt.getParseMaxDigits() != 1000) { errln("Fail valid value checking in setParseMaxDigits."); } try { if (fmt.parse(number).doubleValue() == Float.POSITIVE_INFINITY) { errln("Got Infinity but should NOT when parsing number: " + number); } fmt.setParseMaxDigits(newParseMax); if (fmt.parse(number).doubleValue() != Float.POSITIVE_INFINITY) { errln("Did not get Infinity but should when parsing number: " + number); } } catch (ParseException ex) { } } */ private static class FormatCharItrTestThread implements Runnable { private final NumberFormat fmt; private final int num; private final int[] result; FormatCharItrTestThread(NumberFormat fmt, int num, int[] result) { this.fmt = fmt; this.num = num; this.result = result; } @Override public void run() { for (int i = 0; i < result.length; i++) { AttributedCharacterIterator acitr = fmt.formatToCharacterIterator(num); acitr.first(); result[i] = acitr.getRunLimit(); } } } @Test public void TestRoundingBehavior() { final Object[][] TEST_CASES = { { ULocale.US, // ULocale - null for default locale "#.##", // Pattern Integer.valueOf(BigDecimal.ROUND_DOWN), // Rounding Mode or null (implicit) Double.valueOf(0.0d), // Rounding increment, Double or BigDecimal, or null (implicit) Double.valueOf(123.4567d), // Input value, Long, Double, BigInteger or BigDecimal "123.45" // Expected result, null for exception }, { ULocale.US, "#.##", null, Double.valueOf(0.1d), Double.valueOf(123.4567d), "123.5" }, { ULocale.US, "#.##", Integer.valueOf(BigDecimal.ROUND_DOWN), Double.valueOf(0.1d), Double.valueOf(123.4567d), "123.4" }, { ULocale.US, "#.##", Integer.valueOf(BigDecimal.ROUND_UNNECESSARY), null, Double.valueOf(123.4567d), null }, { ULocale.US, "#.##", Integer.valueOf(BigDecimal.ROUND_DOWN), null, Long.valueOf(1234), "1234" }, }; int testNum = 1; for (Object[] testCase : TEST_CASES) { // 0: locale // 1: pattern ULocale locale = testCase[0] == null ? ULocale.getDefault() : (ULocale)testCase[0]; String pattern = (String)testCase[1]; DecimalFormat fmt = new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(locale)); // 2: rounding mode Integer roundingMode = null; if (testCase[2] != null) { roundingMode = (Integer)testCase[2]; fmt.setRoundingMode(roundingMode); } // 3: rounding increment if (testCase[3] != null) { if (testCase[3] instanceof Double) { fmt.setRoundingIncrement((Double)testCase[3]); } else if (testCase[3] instanceof BigDecimal) { fmt.setRoundingIncrement((BigDecimal)testCase[3]); } else if (testCase[3] instanceof java.math.BigDecimal) { fmt.setRoundingIncrement((java.math.BigDecimal)testCase[3]); } } // 4: input number String s = null; boolean bException = false; try { s = fmt.format(testCase[4]); } catch (ArithmeticException e) { bException = true; } if (bException) { if (testCase[5] != null) { errln("Test case #" + testNum + ": ArithmeticException was thrown."); } } else { if (testCase[5] == null) { errln("Test case #" + testNum + ": ArithmeticException must be thrown, but got formatted result: " + s); } else { assertEquals("Test case #" + testNum, testCase[5], s); } } testNum++; } } @Test public void TestSignificantDigits() { double input[] = { 0, 0, 123, -123, 12345, -12345, 123.45, -123.45, 123.44501, -123.44501, 0.001234, -0.001234, 0.00000000123, -0.00000000123, 0.0000000000000000000123, -0.0000000000000000000123, 1.2, -1.2, 0.0000000012344501, -0.0000000012344501, 123445.01, -123445.01, 12344501000000000000000000000000000.0, -12344501000000000000000000000000000.0, }; String[] expected = { "0.00", "0.00", "123", "-123", "12345", "-12345", "123.45", "-123.45", "123.45", "-123.45", "0.001234", "-0.001234", "0.00000000123", "-0.00000000123", "0.0000000000000000000123", "-0.0000000000000000000123", "1.20", "-1.20", "0.0000000012345", "-0.0000000012345", "123450", "-123450", "12345000000000000000000000000000000", "-12345000000000000000000000000000000", }; DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(ULocale.US); numberFormat.setSignificantDigitsUsed(true); numberFormat.setMinimumSignificantDigits(3); numberFormat.setMaximumSignificantDigits(5); numberFormat.setGroupingUsed(false); for (int i = 0; i < input.length; i++) { assertEquals("TestSignificantDigits", expected[i], numberFormat.format(input[i])); } // Test for ICU-20063 { DecimalFormat df = new DecimalFormat("0.######", DecimalFormatSymbols.getInstance(ULocale.US)); df.setSignificantDigitsUsed(true); expect(df, 9.87654321, "9.87654"); df.setMaximumSignificantDigits(3); expect(df, 9.87654321, "9.88"); // setSignificantDigitsUsed with maxSig only df.setSignificantDigitsUsed(true); expect(df, 9.87654321, "9.88"); df.setMinimumSignificantDigits(2); expect(df, 9, "9.0"); // setSignificantDigitsUsed with both minSig and maxSig df.setSignificantDigitsUsed(true); expect(df, 9, "9.0"); // setSignificantDigitsUsed to false: should revert to fraction rounding df.setSignificantDigitsUsed(false); expect(df, 9.87654321, "9.876543"); expect(df, 9, "9"); df.setSignificantDigitsUsed(true); df.setMinimumSignificantDigits(2); expect(df, 9.87654321, "9.87654"); expect(df, 9, "9.0"); // setSignificantDigitsUsed with minSig only df.setSignificantDigitsUsed(true); expect(df, 9.87654321, "9.87654"); expect(df, 9, "9.0"); } } @Test public void TestBug9936() { DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(ULocale.US); assertFalse("", numberFormat.areSignificantDigitsUsed()); numberFormat.setSignificantDigitsUsed(true); assertTrue("", numberFormat.areSignificantDigitsUsed()); numberFormat.setSignificantDigitsUsed(false); assertFalse("", numberFormat.areSignificantDigitsUsed()); numberFormat.setMinimumSignificantDigits(3); assertTrue("", numberFormat.areSignificantDigitsUsed()); numberFormat.setSignificantDigitsUsed(false); numberFormat.setMaximumSignificantDigits(6); assertTrue("", numberFormat.areSignificantDigitsUsed()); } @Test public void TestShowZero() { DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(ULocale.US); numberFormat.setSignificantDigitsUsed(true); numberFormat.setMaximumSignificantDigits(3); assertEquals("TestShowZero", "0", numberFormat.format(0.0)); } @Test public void TestCurrencyPlurals() { String[][] tests = { {"en", "USD", "1", "1 US dollar"}, {"en", "USD", "1.0", "1.0 US dollars"}, {"en", "USD", "1.00", "1.00 US dollars"}, {"en", "USD", "1.99", "1.99 US dollars"}, {"en", "AUD", "1", "1 Australian dollar"}, {"en", "AUD", "1.00", "1.00 Australian dollars"}, {"sl", "USD", "1", "1 ameri\u0161ki dolar"}, {"sl", "USD", "2", "2 ameri\u0161ka dolarja"}, {"sl", "USD", "3", "3 ameri\u0161ki dolarji"}, {"sl", "USD", "5", "5 ameriških dolarjev"}, {"fr", "USD", "1.99", "1,99 dollar des États-Unis"}, {"ru", "RUB", "1", "1 \u0440\u043E\u0441\u0441\u0438\u0439\u0441\u043A\u0438\u0439 \u0440\u0443\u0431\u043B\u044C"}, {"ru", "RUB", "2", "2 \u0440\u043E\u0441\u0441\u0438\u0439\u0441\u043A\u0438\u0445 \u0440\u0443\u0431\u043B\u044F"}, {"ru", "RUB", "5", "5 \u0440\u043E\u0441\u0441\u0438\u0439\u0441\u043A\u0438\u0445 \u0440\u0443\u0431\u043B\u0435\u0439"}, }; for (String test[] : tests) { DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getInstance(new ULocale(test[0]), NumberFormat.PLURALCURRENCYSTYLE); numberFormat.setCurrency(Currency.getInstance(test[1])); double number = Double.parseDouble(test[2]); int dotPos = test[2].indexOf('.'); int decimals = dotPos < 0 ? 0 : test[2].length() - dotPos - 1; int digits = dotPos < 0 ? test[2].length() : test[2].length() - 1; numberFormat.setMaximumFractionDigits(decimals); numberFormat.setMinimumFractionDigits(decimals); String actual = numberFormat.format(number); assertEquals(test[0] + "\t" + test[1] + "\t" + test[2], test[3], actual); numberFormat.setMaximumSignificantDigits(digits); numberFormat.setMinimumSignificantDigits(digits); actual = numberFormat.format(number); assertEquals(test[0] + "\t" + test[1] + "\t" + test[2], test[3], actual); } } @Test public void TestCustomCurrencySignAndSeparator() { DecimalFormatSymbols custom = new DecimalFormatSymbols(ULocale.US); custom.setCurrencySymbol("*"); custom.setMonetaryGroupingSeparator('^'); custom.setMonetaryDecimalSeparator(':'); DecimalFormat fmt = new DecimalFormat("\u00A4 #,##0.00", custom); final String numstr = "* 1^234:56"; expect2(fmt, 1234.56, numstr); } @Test public void TestParseSignsAndMarks() { class SignsAndMarksItem { public String locale; public boolean lenient; public String numString; public double value; // Simple constructor public SignsAndMarksItem(String loc, boolean lnt, String numStr, double val) { locale = loc; lenient = lnt; numString = numStr; value = val; } }; final SignsAndMarksItem[] items = { // *** Note, ICU4J lenient number parsing does not handle arbitrary whitespace, but can // treat some whitespace as a grouping separator. The cases marked *** below depend // on isGroupingUsed() being set for the locale, which in turn depends on grouping // separators being present in the decimalFormat pattern for the locale (& num sys). // // locale lenient numString value new SignsAndMarksItem("en", false, "12", 12 ), new SignsAndMarksItem("en", true, "12", 12 ), new SignsAndMarksItem("en", false, "-23", -23 ), new SignsAndMarksItem("en", true, "-23", -23 ), new SignsAndMarksItem("en", true, "- 23", -23 ), // *** new SignsAndMarksItem("en", false, "\u200E-23", -23 ), new SignsAndMarksItem("en", true, "\u200E-23", -23 ), new SignsAndMarksItem("en", true, "\u200E- 23", -23 ), // *** new SignsAndMarksItem("en@numbers=arab", false, "\u0663\u0664", 34 ), new SignsAndMarksItem("en@numbers=arab", true, "\u0663\u0664", 34 ), new SignsAndMarksItem("en@numbers=arab", false, "-\u0664\u0665", -45 ), new SignsAndMarksItem("en@numbers=arab", true, "-\u0664\u0665", -45 ), new SignsAndMarksItem("en@numbers=arab", true, "- \u0664\u0665", -45 ), // *** new SignsAndMarksItem("en@numbers=arab", false, "\u200F-\u0664\u0665", -45 ), new SignsAndMarksItem("en@numbers=arab", true, "\u200F-\u0664\u0665", -45 ), new SignsAndMarksItem("en@numbers=arab", true, "\u200F- \u0664\u0665", -45 ), // *** new SignsAndMarksItem("en@numbers=arabext", false, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("en@numbers=arabext", true, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("en@numbers=arabext", false, "-\u06F6\u06F7", -67 ), new SignsAndMarksItem("en@numbers=arabext", true, "-\u06F6\u06F7", -67 ), new SignsAndMarksItem("en@numbers=arabext", true, "- \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("en@numbers=arabext", false, "\u200E-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("en@numbers=arabext", true, "\u200E-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("en@numbers=arabext", true, "\u200E-\u200E \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("he", false, "12", 12 ), new SignsAndMarksItem("he", true, "12", 12 ), new SignsAndMarksItem("he", false, "-23", -23 ), new SignsAndMarksItem("he", true, "-23", -23 ), new SignsAndMarksItem("he", true, "- 23", -23 ), // *** new SignsAndMarksItem("he", false, "\u200E-23", -23 ), new SignsAndMarksItem("he", true, "\u200E-23", -23 ), new SignsAndMarksItem("he", true, "\u200E- 23", -23 ), // *** new SignsAndMarksItem("ar", false, "\u0663\u0664", 34 ), new SignsAndMarksItem("ar", true, "\u0663\u0664", 34 ), new SignsAndMarksItem("ar", false, "-\u0664\u0665", -45 ), new SignsAndMarksItem("ar", true, "-\u0664\u0665", -45 ), new SignsAndMarksItem("ar", true, "- \u0664\u0665", -45 ), // *** new SignsAndMarksItem("ar", false, "\u200F-\u0664\u0665", -45 ), new SignsAndMarksItem("ar", true, "\u200F-\u0664\u0665", -45 ), new SignsAndMarksItem("ar", true, "\u200F- \u0664\u0665", -45 ), // *** new SignsAndMarksItem("ar_MA", false, "12", 12 ), new SignsAndMarksItem("ar_MA", true, "12", 12 ), new SignsAndMarksItem("ar_MA", false, "-23", -23 ), new SignsAndMarksItem("ar_MA", true, "-23", -23 ), new SignsAndMarksItem("ar_MA", true, "- 23", -23 ), // *** new SignsAndMarksItem("ar_MA", false, "\u200E-23", -23 ), new SignsAndMarksItem("ar_MA", true, "\u200E-23", -23 ), new SignsAndMarksItem("ar_MA", true, "\u200E- 23", -23 ), // *** new SignsAndMarksItem("fa", false, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("fa", true, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("fa", false, "\u2212\u06F6\u06F7", -67 ), new SignsAndMarksItem("fa", true, "\u2212\u06F6\u06F7", -67 ), new SignsAndMarksItem("fa", true, "\u2212 \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("fa", false, "\u200E\u2212\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("fa", true, "\u200E\u2212\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("fa", true, "\u200E\u2212\u200E \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("ps", false, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("ps", true, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("ps", false, "-\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "-\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "- \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("ps", false, "\u200E-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "\u200E-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "\u200E-\u200E \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("ps", false, "-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "-\u200E \u06F6\u06F7", -67 ), // *** }; for (SignsAndMarksItem item: items) { ULocale locale = new ULocale(item.locale); NumberFormat numfmt = NumberFormat.getInstance(locale); if (numfmt != null) { numfmt.setParseStrict(!item.lenient); ParsePosition ppos = new ParsePosition(0); Number num = numfmt.parse(item.numString, ppos); if (num != null && ppos.getIndex() == item.numString.length()) { double parsedValue = num.doubleValue(); if (parsedValue != item.value) { errln("FAIL: locale " + item.locale + ", lenient " + item.lenient + ", parse of \"" + item.numString + "\" gives value " + parsedValue); } } else { errln("FAIL: locale " + item.locale + ", lenient " + item.lenient + ", parse of \"" + item.numString + "\" gives position " + ppos.getIndex()); } } else { errln("FAIL: NumberFormat.getInstance for locale " + item.locale); } } } @Test public void TestContext() { // just a minimal sanity check for now NumberFormat nfmt = NumberFormat.getInstance(); DisplayContext context = nfmt.getContext(DisplayContext.Type.CAPITALIZATION); if (context != DisplayContext.CAPITALIZATION_NONE) { errln("FAIL: Initial NumberFormat.getContext() is not CAPITALIZATION_NONE"); } nfmt.setContext(DisplayContext.CAPITALIZATION_FOR_STANDALONE); context = nfmt.getContext(DisplayContext.Type.CAPITALIZATION); if (context != DisplayContext.CAPITALIZATION_FOR_STANDALONE) { errln("FAIL: NumberFormat.getContext() does not return the value set, CAPITALIZATION_FOR_STANDALONE"); } } @Test public void TestAccountingCurrency() { String[][] tests = { //locale num curr fmt per loc curr std fmt curr acct fmt rt {"en_US", "1234.5", "$1,234.50", "$1,234.50", "$1,234.50", "true"}, {"en_US@cf=account", "1234.5", "$1,234.50", "$1,234.50", "$1,234.50", "true"}, {"en_US", "-1234.5", "-$1,234.50", "-$1,234.50", "($1,234.50)", "true"}, {"en_US@cf=standard", "-1234.5", "-$1,234.50", "-$1,234.50", "($1,234.50)", "true"}, {"en_US@cf=account", "-1234.5", "($1,234.50)", "-$1,234.50", "($1,234.50)", "true"}, {"en_US", "0", "$0.00", "$0.00", "$0.00", "true"}, {"en_US", "-0.2", "-$0.20", "-$0.20", "($0.20)", "true"}, {"en_US@cf=standard", "-0.2", "-$0.20", "-$0.20", "($0.20)", "true"}, {"en_US@cf=account", "-0.2", "($0.20)", "-$0.20", "($0.20)", "true"}, {"ja_JP", "10000", "¥10,000", "¥10,000", "¥10,000", "true" }, {"ja_JP", "-1000.5", "-¥1,000", "-¥1,000", "(¥1,000)", "false"}, {"ja_JP@cf=account", "-1000.5", "(¥1,000)", "-¥1,000", "(¥1,000)", "false"}, {"de_DE", "-23456.7", "-23.456,70\u00A0€", "-23.456,70\u00A0€", "-23.456,70\u00A0€", "true" }, }; for (String[] data : tests) { ULocale loc = new ULocale(data[0]); double num = Double.parseDouble(data[1]); String fmtPerLocExpected = data[2]; String fmtStandardExpected = data[3]; String fmtAccountExpected = data[4]; boolean rt = Boolean.parseBoolean(data[5]); NumberFormat fmtPerLoc = NumberFormat.getInstance(loc, NumberFormat.CURRENCYSTYLE); expect(fmtPerLoc, num, fmtPerLocExpected, rt); NumberFormat fmtStandard = NumberFormat.getInstance(loc, NumberFormat.STANDARDCURRENCYSTYLE); expect(fmtStandard, num, fmtStandardExpected, rt); NumberFormat fmtAccount = NumberFormat.getInstance(loc, NumberFormat.ACCOUNTINGCURRENCYSTYLE); expect(fmtAccount, num, fmtAccountExpected, rt); } } @Test public void TestCurrencyUsage() { // the 1st one is checking setter/getter, while the 2nd one checks for getInstance // compare the Currency and Currency Cash Digits // Note that as of CLDR 26: // * TWD and PKR switched from 0 decimals to 2; ISK still has 0, so change test to that // * CAD rounds to .05 in the cash style only. for (int i = 0; i < 2; i++) { String original_expected = "ISK 124"; DecimalFormat custom = null; if (i == 0) { custom = (DecimalFormat) DecimalFormat.getInstance(new ULocale("en_US@currency=ISK"), DecimalFormat.CURRENCYSTYLE); String original = custom.format(123.567); assertEquals("Test Currency Context", original_expected, original); // test the getter assertEquals("Test Currency Context Purpose", custom.getCurrencyUsage(), Currency.CurrencyUsage.STANDARD); custom.setCurrencyUsage(Currency.CurrencyUsage.CASH); assertEquals("Test Currency Context Purpose", custom.getCurrencyUsage(), Currency.CurrencyUsage.CASH); } else { custom = (DecimalFormat) DecimalFormat.getInstance(new ULocale("en_US@currency=ISK"), DecimalFormat.CASHCURRENCYSTYLE); // test the getter assertEquals("Test Currency Context Purpose", custom.getCurrencyUsage(), Currency.CurrencyUsage.CASH); } String cash_currency = custom.format(123.567); String cash_currency_expected = "ISK 124"; assertEquals("Test Currency Context", cash_currency_expected, cash_currency); } // the 1st one is checking setter/getter, while the 2nd one checks for getInstance // compare the Currency and Currency Cash Rounding for (int i = 0; i < 2; i++) { String original_rounding_expected = "CA$123.57"; DecimalFormat fmt = null; if (i == 0) { fmt = (DecimalFormat) DecimalFormat.getInstance(new ULocale("en_US@currency=CAD"), DecimalFormat.CURRENCYSTYLE); String original_rounding = fmt.format(123.566); assertEquals("Test Currency Context", original_rounding_expected, original_rounding); fmt.setCurrencyUsage(Currency.CurrencyUsage.CASH); } else { fmt = (DecimalFormat) DecimalFormat.getInstance(new ULocale("en_US@currency=CAD"), DecimalFormat.CASHCURRENCYSTYLE); } String cash_rounding_currency = fmt.format(123.567); String cash__rounding_currency_expected = "CA$123.55"; assertEquals("Test Currency Context", cash__rounding_currency_expected, cash_rounding_currency); } // the 1st one is checking setter/getter, while the 2nd one checks for getInstance // Test the currency change for (int i = 0; i < 2; i++) { DecimalFormat fmt2 = null; if (i == 1) { fmt2 = (DecimalFormat) NumberFormat.getInstance(new ULocale("en_US@currency=JPY"), NumberFormat.CURRENCYSTYLE); fmt2.setCurrencyUsage(Currency.CurrencyUsage.CASH); } else { fmt2 = (DecimalFormat) NumberFormat.getInstance(new ULocale("en_US@currency=JPY"), NumberFormat.CASHCURRENCYSTYLE); } fmt2.setCurrency(Currency.getInstance("PKR")); String PKR_changed = fmt2.format(123.567); String PKR_changed_expected = "PKR 124"; assertEquals("Test Currency Context", PKR_changed_expected, PKR_changed); } } @Test public void TestCurrencyWithMinMaxFractionDigits() { DecimalFormat df = new DecimalFormat(); df.applyPattern("¤#,##0.00"); df.setCurrency(Currency.getInstance("USD")); assertEquals("Basic currency format fails", "$1.23", df.format(1.234)); df.setMaximumFractionDigits(4); assertEquals("Currency with max fraction == 4", "$1.234", df.format(1.234)); df.setMinimumFractionDigits(4); assertEquals("Currency with min fraction == 4", "$1.2340", df.format(1.234)); } @Test public void TestParseRequiredDecimalPoint() { String[] testPattern = { "00.####", "00.0", "00" }; String value2Parse = "99"; String value2ParseWithDecimal = "99.9"; double parseValue = 99; double parseValueWithDecimal = 99.9; DecimalFormat parser = new DecimalFormat(); double result; boolean hasDecimalPoint; for (int i = 0; i < testPattern.length; i++) { parser.applyPattern(testPattern[i]); hasDecimalPoint = testPattern[i].contains("."); parser.setDecimalPatternMatchRequired(false); try { result = parser.parse(value2Parse).doubleValue(); assertEquals("wrong parsed value", parseValue, result); } catch (ParseException e) { TestFmwk.errln("Parsing " + value2Parse + " should have succeeded with " + testPattern[i] + " and isDecimalPointMatchRequired set to: " + parser.isDecimalPatternMatchRequired()); } try { result = parser.parse(value2ParseWithDecimal).doubleValue(); assertEquals("wrong parsed value", parseValueWithDecimal, result); } catch (ParseException e) { TestFmwk.errln("Parsing " + value2ParseWithDecimal + " should have succeeded with " + testPattern[i] + " and isDecimalPointMatchRequired set to: " + parser.isDecimalPatternMatchRequired()); } parser.setDecimalPatternMatchRequired(true); try { result = parser.parse(value2Parse).doubleValue(); if(hasDecimalPoint){ TestFmwk.errln("Parsing " + value2Parse + " should NOT have succeeded with " + testPattern[i] + " and isDecimalPointMatchRequired set to: " + parser.isDecimalPatternMatchRequired()); } } catch (ParseException e) { // OK, should fail } try { result = parser.parse(value2ParseWithDecimal).doubleValue(); if(!hasDecimalPoint){ TestFmwk.errln("Parsing " + value2ParseWithDecimal + " should NOT have succeeded with " + testPattern[i] + " and isDecimalPointMatchRequired set to: " + parser.isDecimalPatternMatchRequired() + " (got: " + result + ")"); } } catch (ParseException e) { // OK, should fail } } } @Test public void TestCurrFmtNegSameAsPositive() { DecimalFormatSymbols decfmtsym = DecimalFormatSymbols.getInstance(Locale.US); decfmtsym.setMinusSign('\u200B'); // ZERO WIDTH SPACE, in ICU4J cannot set to empty string DecimalFormat decfmt = new DecimalFormat("\u00A4#,##0.00;-\u00A4#,##0.00", decfmtsym); String currFmtResult = decfmt.format(-100.0); if (!currFmtResult.equals("\u200B$100.00")) { errln("decfmt.toPattern results wrong, expected \u200B$100.00, got " + currFmtResult); } } @Test public void TestNumberFormatTestDataToString() { new DataDrivenNumberFormatTestData().toString(); } // Testing for Issue 11805. @Test public void TestFormatToCharacterIteratorIssue11805 () { final double number = -350.76; DecimalFormat dfUS = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.US); String strUS = dfUS.format(number); Set<AttributedCharacterIterator.Attribute> resultUS = dfUS.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative US Results: " + strUS, 5, resultUS.size()); // For each test, add assert that all the fields are present and in the right spot. // TODO: Add tests for identify and position of each field, as in IntlTestDecimalFormatAPIC. DecimalFormat dfDE = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.GERMANY); String strDE = dfDE.format(number); Set<AttributedCharacterIterator.Attribute> resultDE = dfDE.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative DE Results: " + strDE, 5, resultDE.size()); DecimalFormat dfIN = (DecimalFormat) DecimalFormat.getCurrencyInstance(new Locale("hi", "in")); String strIN = dfIN.format(number); Set<AttributedCharacterIterator.Attribute> resultIN = dfIN.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative IN Results: " + strIN, 5, resultIN.size()); DecimalFormat dfJP = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.JAPAN); String strJP = dfJP.format(number); Set<AttributedCharacterIterator.Attribute> resultJP = dfJP.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative JA Results: " + strJP, 3, resultJP.size()); DecimalFormat dfGB = (DecimalFormat) DecimalFormat.getCurrencyInstance(new Locale("en", "gb")); String strGB = dfGB.format(number); Set<AttributedCharacterIterator.Attribute> resultGB = dfGB.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative GB Results: " + strGB , 5, resultGB.size()); DecimalFormat dfPlural = (DecimalFormat) NumberFormat.getInstance(new Locale("en", "gb"), NumberFormat.PLURALCURRENCYSTYLE); strGB = dfPlural.format(number); resultGB = dfPlural.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative GB Results: " + strGB , 5, resultGB.size()); strGB = dfPlural.format(1); resultGB = dfPlural.formatToCharacterIterator(1).getAllAttributeKeys(); assertEquals("Negative GB Results: " + strGB , 4, resultGB.size()); // Test output with unit value. DecimalFormat auPlural = (DecimalFormat) NumberFormat.getInstance(new Locale("en", "au"), NumberFormat.PLURALCURRENCYSTYLE); String strAU = auPlural.format(1L); Set<AttributedCharacterIterator.Attribute> resultAU = auPlural.formatToCharacterIterator(1L).getAllAttributeKeys(); assertEquals("Unit AU Result: " + strAU , 4, resultAU.size()); // Verify Permille fields. DecimalFormatSymbols sym = new DecimalFormatSymbols(new Locale("en", "gb")); DecimalFormat dfPermille = new DecimalFormat("####0.##\u2030", sym); strGB = dfPermille.format(number); resultGB = dfPermille.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative GB Permille Results: " + strGB , 3, resultGB.size()); } // Testing for Issue 11808. @Test public void TestRoundUnnecessarytIssue11808 () { DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(); StringBuffer result = new StringBuffer(""); df.setRoundingMode(BigDecimal.ROUND_UNNECESSARY); df.applyPattern("00.0#E0"); try { df.format(99999.0, result, new FieldPosition(0)); fail("Missing ArithmeticException for double: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } try { result = df.format(99999, result, new FieldPosition(0)); fail("Missing ArithmeticException for int: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } try { result = df.format(new BigInteger("999999"), result, new FieldPosition(0)); fail("Missing ArithmeticException for BigInteger: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } try { result = df.format(new BigDecimal("99999"), result, new FieldPosition(0)); fail("Missing ArithmeticException for BigDecimal: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } try { result = df.format(new BigDecimal("-99999"), result, new FieldPosition(0)); fail("Missing ArithmeticException for BigDecimal: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } } // Testing for Issue 11735. @Test public void TestNPEIssue11735() { DecimalFormat fmt = new DecimalFormat("0", new DecimalFormatSymbols(new ULocale("en"))); ParsePosition ppos = new ParsePosition(0); assertEquals("Currency symbol missing in parse. Expect null result.", fmt.parseCurrency("53.45", ppos), null); } private void CompareAttributedCharacterFormatOutput(AttributedCharacterIterator iterator, List<FieldContainer> expected, String formattedOutput) { List<FieldContainer> result = new ArrayList<>(); while (iterator.getIndex() != iterator.getEndIndex()) { int start = iterator.getRunStart(); int end = iterator.getRunLimit(); Iterator it = iterator.getAttributes().keySet().iterator(); AttributedCharacterIterator.Attribute attribute = (AttributedCharacterIterator.Attribute) it.next(); // For positions with both INTEGER and GROUPING attributes, we want the GROUPING attribute. if (it.hasNext() && attribute.equals(NumberFormat.Field.INTEGER)) { attribute = (AttributedCharacterIterator.Attribute) it.next(); } Object value = iterator.getAttribute(attribute); result.add(new FieldContainer(start, end, attribute, value)); iterator.setIndex(end); } assertEquals("Comparing vector length for " + formattedOutput, expected.size(), result.size()); if (!expected.containsAll(result)) { // Print information on the differences. for (int i = 0; i < expected.size(); i++) { System.out.println(" expected[" + i + "] =" + expected.get(i).start + " " + expected.get(i).end + " " + expected.get(i).attribute + " " + expected.get(i).value); System.out.println(" result[" + i + "] =" + result.get(i).start + " " + result.get(i).end + " " + result.get(i).attribute + " " + result.get(i).value); } } assertTrue("Comparing vector results for " + formattedOutput, expected.containsAll(result)); } // Testing for Issue 11914, missing FieldPositions for some field types. @Test public void TestNPEIssue11914() { // First test: Double value with grouping separators. List<FieldContainer> v1 = new ArrayList<>(7); v1.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER)); v1.add(new FieldContainer(3, 4, NumberFormat.Field.GROUPING_SEPARATOR)); v1.add(new FieldContainer(4, 7, NumberFormat.Field.INTEGER)); v1.add(new FieldContainer(7, 8, NumberFormat.Field.GROUPING_SEPARATOR)); v1.add(new FieldContainer(8, 11, NumberFormat.Field.INTEGER)); v1.add(new FieldContainer(11, 12, NumberFormat.Field.DECIMAL_SEPARATOR)); v1.add(new FieldContainer(12, 15, NumberFormat.Field.FRACTION)); Number number = new Double(123456789.9753); ULocale usLoc = new ULocale("en-US"); DecimalFormatSymbols US = new DecimalFormatSymbols(usLoc); NumberFormat outFmt = NumberFormat.getNumberInstance(usLoc); String numFmtted = outFmt.format(number); AttributedCharacterIterator iterator = outFmt.formatToCharacterIterator(number); CompareAttributedCharacterFormatOutput(iterator, v1, numFmtted); // Second test: Double with scientific notation formatting. List<FieldContainer> v2 = new ArrayList<>(7); v2.add(new FieldContainer(0, 1, NumberFormat.Field.INTEGER)); v2.add(new FieldContainer(1, 2, NumberFormat.Field.DECIMAL_SEPARATOR)); v2.add(new FieldContainer(2, 5, NumberFormat.Field.FRACTION)); v2.add(new FieldContainer(5, 6, NumberFormat.Field.EXPONENT_SYMBOL)); v2.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT_SIGN)); v2.add(new FieldContainer(7, 8, NumberFormat.Field.EXPONENT)); DecimalFormat fmt2 = new DecimalFormat("0.###E+0", US); numFmtted = fmt2.format(number); iterator = fmt2.formatToCharacterIterator(number); CompareAttributedCharacterFormatOutput(iterator, v2, numFmtted); // Third test. BigInteger with grouping separators. List<FieldContainer> v3 = new ArrayList<>(7); v3.add(new FieldContainer(0, 1, NumberFormat.Field.SIGN)); v3.add(new FieldContainer(1, 2, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(2, 3, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(3, 6, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(6, 7, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(7, 10, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(10, 11, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(11, 14, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(14, 15, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(15, 18, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(18, 19, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(19, 22, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(22, 23, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(23, 26, NumberFormat.Field.INTEGER)); BigInteger bigNumberInt = new BigInteger("-1234567890246813579"); String fmtNumberBigInt = outFmt.format(bigNumberInt); iterator = outFmt.formatToCharacterIterator(bigNumberInt); CompareAttributedCharacterFormatOutput(iterator, v3, fmtNumberBigInt); // Fourth test: BigDecimal with exponential formatting. List<FieldContainer> v4 = new ArrayList<>(7); v4.add(new FieldContainer(0, 1, NumberFormat.Field.SIGN)); v4.add(new FieldContainer(1, 2, NumberFormat.Field.INTEGER)); v4.add(new FieldContainer(2, 3, NumberFormat.Field.DECIMAL_SEPARATOR)); v4.add(new FieldContainer(3, 6, NumberFormat.Field.FRACTION)); v4.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT_SYMBOL)); v4.add(new FieldContainer(7, 8, NumberFormat.Field.EXPONENT_SIGN)); v4.add(new FieldContainer(8, 9, NumberFormat.Field.EXPONENT)); java.math.BigDecimal numberBigD = new java.math.BigDecimal(-123456789); String fmtNumberBigDExp = fmt2.format(numberBigD); iterator = fmt2.formatToCharacterIterator(numberBigD); CompareAttributedCharacterFormatOutput(iterator, v4, fmtNumberBigDExp); } // Test that the decimal is shown even when there are no fractional digits @Test public void Test11621() throws Exception { String pat = "0.##E0"; DecimalFormatSymbols icuSym = new DecimalFormatSymbols(Locale.US); DecimalFormat icuFmt = new DecimalFormat(pat, icuSym); icuFmt.setDecimalSeparatorAlwaysShown(true); String icu = ((NumberFormat)icuFmt).format(299792458); java.text.DecimalFormatSymbols jdkSym = new java.text.DecimalFormatSymbols(Locale.US); java.text.DecimalFormat jdkFmt = new java.text.DecimalFormat(pat,jdkSym); jdkFmt.setDecimalSeparatorAlwaysShown(true); String jdk = ((java.text.NumberFormat)jdkFmt).format(299792458); assertEquals("ICU and JDK placement of decimal in exponent", jdk, icu); } private void checkFormatWithField(String testInfo, Format format, Object object, String expected, Format.Field field, int begin, int end) { StringBuffer buffer = new StringBuffer(); FieldPosition pos = new FieldPosition(field); format.format(object, buffer, pos); assertEquals("Test " + testInfo + ": incorrect formatted text", expected, buffer.toString()); if (begin != pos.getBeginIndex() || end != pos.getEndIndex()) { assertEquals("Index mismatch", field + " " + begin + ".." + end, pos.getFieldAttribute() + " " + pos.getBeginIndex() + ".." + pos.getEndIndex()); } } @Test public void TestMissingFieldPositionsCurrency() { DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(ULocale.US); Number number = new Double(92314587.66); String result = "$92,314,587.66"; checkFormatWithField("currency", formatter, number, result, NumberFormat.Field.CURRENCY, 0, 1); checkFormatWithField("integer", formatter, number, result, NumberFormat.Field.INTEGER, 1, 11); checkFormatWithField("grouping separator", formatter, number, result, NumberFormat.Field.GROUPING_SEPARATOR, 3, 4); checkFormatWithField("decimal separator", formatter, number, result, NumberFormat.Field.DECIMAL_SEPARATOR, 11, 12); checkFormatWithField("fraction", formatter, number, result, NumberFormat.Field.FRACTION, 12, 14); } @Test public void TestMissingFieldPositionsNegativeDouble() { // test for exponential fields with double DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); Number number = new Double(-12345678.90123); DecimalFormat formatter = new DecimalFormat("0.#####E+00", us_symbols); String numFmtted = formatter.format(number); checkFormatWithField("sign", formatter, number, numFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", formatter, number, numFmtted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", formatter, number, numFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("exponent symbol", formatter, number, numFmtted, NumberFormat.Field.EXPONENT_SYMBOL, 8, 9); checkFormatWithField("exponent sign", formatter, number, numFmtted, NumberFormat.Field.EXPONENT_SIGN, 9, 10); checkFormatWithField("exponent", formatter, number, numFmtted, NumberFormat.Field.EXPONENT, 10, 12); } @Test public void TestMissingFieldPositionsPerCent() { // Check PERCENT DecimalFormat percentFormat = (DecimalFormat) NumberFormat.getPercentInstance(ULocale.US); Number number = new Double(-0.986); String numberFormatted = percentFormat.format(number); checkFormatWithField("sign", percentFormat, number, numberFormatted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", percentFormat, number, numberFormatted, NumberFormat.Field.INTEGER, 1, 3); checkFormatWithField("percent", percentFormat, number, numberFormatted, NumberFormat.Field.PERCENT, 3, 4); } @Test public void TestMissingFieldPositionsPerCentPattern() { // Check PERCENT with more digits DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat fmtPercent = new DecimalFormat("0.#####%", us_symbols); Number number = new Double(-0.986); String numFmtted = fmtPercent.format(number); checkFormatWithField("sign", fmtPercent, number, numFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", fmtPercent, number, numFmtted, NumberFormat.Field.INTEGER, 1, 3); checkFormatWithField("decimal separator", fmtPercent, number, numFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 3, 4); checkFormatWithField("fraction", fmtPercent, number, numFmtted, NumberFormat.Field.FRACTION, 4, 5); checkFormatWithField("percent", fmtPercent, number, numFmtted, NumberFormat.Field.PERCENT, 5, 6); } @Test public void TestMissingFieldPositionsPerMille() { // Check PERMILLE DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat fmtPerMille = new DecimalFormat("0.######‰", us_symbols); Number numberPermille = new Double(-0.98654); String numFmtted = fmtPerMille.format(numberPermille); checkFormatWithField("sign", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.INTEGER, 1, 4); checkFormatWithField("decimal separator", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 4, 5); checkFormatWithField("fraction", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.FRACTION, 5, 7); checkFormatWithField("permille", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.PERMILLE, 7, 8); } @Test public void TestMissingFieldPositionsNegativeBigInt() { DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat formatter = new DecimalFormat("0.#####E+0", us_symbols); Number number = new BigDecimal("-123456789987654321"); String bigDecFmtted = formatter.format(number); checkFormatWithField("sign", formatter, number, bigDecFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", formatter, number, bigDecFmtted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", formatter, number, bigDecFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("exponent symbol", formatter, number, bigDecFmtted, NumberFormat.Field.EXPONENT_SYMBOL, 8, 9); checkFormatWithField("exponent sign", formatter, number, bigDecFmtted, NumberFormat.Field.EXPONENT_SIGN, 9, 10); checkFormatWithField("exponent", formatter, number, bigDecFmtted, NumberFormat.Field.EXPONENT, 10, 12); } @Test public void TestMissingFieldPositionsNegativeLong() { Number number = new Long("-123456789987654321"); DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat formatter = new DecimalFormat("0.#####E+0", us_symbols); String longFmtted = formatter.format(number); checkFormatWithField("sign", formatter, number, longFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", formatter, number, longFmtted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", formatter, number, longFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("exponent symbol", formatter, number, longFmtted, NumberFormat.Field.EXPONENT_SYMBOL, 8, 9); checkFormatWithField("exponent sign", formatter, number, longFmtted, NumberFormat.Field.EXPONENT_SIGN, 9, 10); checkFormatWithField("exponent", formatter, number, longFmtted, NumberFormat.Field.EXPONENT, 10, 12); } @Test public void TestMissingFieldPositionsPositiveBigDec() { // Check complex positive;negative pattern. DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat fmtPosNegSign = new DecimalFormat("+0.####E+00;-0.#######E+0", us_symbols); Number positiveExp = new Double("9876543210"); String posExpFormatted = fmtPosNegSign.format(positiveExp); checkFormatWithField("sign", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("fraction", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.FRACTION, 3, 7); checkFormatWithField("exponent symbol", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.EXPONENT_SYMBOL, 7, 8); checkFormatWithField("exponent sign", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.EXPONENT_SIGN, 8, 9); checkFormatWithField("exponent", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.EXPONENT, 9, 11); } @Test public void TestMissingFieldPositionsNegativeBigDec() { // Check complex positive;negative pattern. DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat fmtPosNegSign = new DecimalFormat("+0.####E+00;-0.#######E+0", us_symbols); Number negativeExp = new BigDecimal("-0.000000987654321083"); String negExpFormatted = fmtPosNegSign.format(negativeExp); checkFormatWithField("sign", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("fraction", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.FRACTION, 3, 7); checkFormatWithField("exponent symbol", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.EXPONENT_SYMBOL, 7, 8); checkFormatWithField("exponent sign", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.EXPONENT_SIGN, 8, 9); checkFormatWithField("exponent", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.EXPONENT, 9, 11); } @Test public void TestStringSymbols() { DecimalFormatSymbols symbols = new DecimalFormatSymbols(ULocale.US); // Attempt digits with multiple code points. String[] customDigits = {"(0)", "(1)", "(2)", "(3)", "(4)", "(5)", "(6)", "(7)", "(8)", "(9)"}; symbols.setDigitStrings(customDigits); DecimalFormat fmt = new DecimalFormat("#,##0.0#", symbols); expect2(fmt, 1234567.89, "(1),(2)(3)(4),(5)(6)(7).(8)(9)"); // Scientific notation should work. fmt.applyPattern("@@@E0"); expect2(fmt, 1230000, "(1).(2)(3)E(6)"); // Grouping and decimal with multiple code points (supported in parsing since ICU 61) symbols.setDecimalSeparatorString("~~"); symbols.setGroupingSeparatorString("^^"); fmt.setDecimalFormatSymbols(symbols); fmt.applyPattern("#,##0.0#"); expect2(fmt, 1234567.89, "(1)^^(2)(3)(4)^^(5)(6)(7)~~(8)(9)"); // Digits starting at U+1D7CE MATHEMATICAL BOLD DIGIT ZERO // These are all single code points, so parsing will work. for (int i=0; i<10; i++) customDigits[i] = new String(Character.toChars(0x1D7CE+i)); symbols.setDigitStrings(customDigits); symbols.setDecimalSeparatorString("😁"); symbols.setGroupingSeparatorString("😎"); fmt.setDecimalFormatSymbols(symbols); expect2(fmt, 1234.56, "𝟏😎𝟐𝟑𝟒😁𝟓𝟔"); } @Test public void TestArabicCurrencyPatternInfo() { ULocale arLocale = new ULocale("ar"); DecimalFormatSymbols symbols = new DecimalFormatSymbols(arLocale); String currSpacingPatn = symbols.getPatternForCurrencySpacing(DecimalFormatSymbols.CURRENCY_SPC_CURRENCY_MATCH, true); if (currSpacingPatn==null || currSpacingPatn.length() == 0) { errln("locale ar, getPatternForCurrencySpacing returns null or 0-length string"); } DecimalFormat currAcctFormat = (DecimalFormat)NumberFormat.getInstance(arLocale, NumberFormat.ACCOUNTINGCURRENCYSTYLE); String currAcctPatn = currAcctFormat.toPattern(); if (currAcctPatn==null || currAcctPatn.length() == 0) { errln("locale ar, toPattern for ACCOUNTINGCURRENCYSTYLE returns null or 0-length string"); } } @Test public void TestMinMaxOverrides() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Class<?>[] baseClasses = {NumberFormat.class, NumberFormat.class, DecimalFormat.class}; String[] names = {"Integer", "Fraction", "Significant"}; for (int i = 0; i < 3; i++) { DecimalFormat df = new DecimalFormat(); Class<?> base = baseClasses[i]; String name = names[i]; Method getMinimum = base.getDeclaredMethod("getMinimum" + name + "Digits"); Method setMinimum = base.getDeclaredMethod("setMinimum" + name + "Digits", Integer.TYPE); Method getMaximum = base.getDeclaredMethod("getMaximum" + name + "Digits"); Method setMaximum = base.getDeclaredMethod("setMaximum" + name + "Digits", Integer.TYPE); // Check max overrides min setMinimum.invoke(df, 2); assertEquals(name + " getMin A", 2, getMinimum.invoke(df)); setMaximum.invoke(df, 3); assertEquals(name + " getMin B", 2, getMinimum.invoke(df)); assertEquals(name + " getMax B", 3, getMaximum.invoke(df)); setMaximum.invoke(df, 2); assertEquals(name + " getMin C", 2, getMinimum.invoke(df)); assertEquals(name + " getMax C", 2, getMaximum.invoke(df)); setMaximum.invoke(df, 1); assertEquals(name + " getMin D", 1, getMinimum.invoke(df)); assertEquals(name + " getMax D", 1, getMaximum.invoke(df)); // Check min overrides max setMaximum.invoke(df, 2); assertEquals(name + " getMax E", 2, getMaximum.invoke(df)); setMinimum.invoke(df, 1); assertEquals(name + " getMin F", 1, getMinimum.invoke(df)); assertEquals(name + " getMax F", 2, getMaximum.invoke(df)); setMinimum.invoke(df, 2); assertEquals(name + " getMin G", 2, getMinimum.invoke(df)); assertEquals(name + " getMax G", 2, getMaximum.invoke(df)); setMinimum.invoke(df, 3); assertEquals(name + " getMin H", 3, getMinimum.invoke(df)); assertEquals(name + " getMax H", 3, getMaximum.invoke(df)); } } @Test public void TestSetMathContext() throws ParseException { java.math.MathContext fourDigits = new java.math.MathContext(4); java.math.MathContext unlimitedCeiling = new java.math.MathContext(0, RoundingMode.CEILING); // Test rounding DecimalFormat df = new DecimalFormat(); assertEquals("Default format", "9,876.543", df.format(9876.5432)); df.setMathContext(fourDigits); assertEquals("Format with fourDigits", "9,877", df.format(9876.5432)); df.setMathContext(unlimitedCeiling); assertEquals("Format with unlimitedCeiling", "9,876.544", df.format(9876.5432)); // Test multiplication df = new DecimalFormat("0.000%"); assertEquals("Default multiplication", "12.001%", df.format(0.120011)); df.setMathContext(fourDigits); assertEquals("Multiplication with fourDigits", "12.000%", df.format(0.120011)); df.setMathContext(unlimitedCeiling); assertEquals("Multiplication with unlimitedCeiling", "12.002%", df.format(0.120011)); // Test simple division df = new DecimalFormat("0%"); assertEquals("Default division", 0.12001, df.parse("12.001%").doubleValue()); df.setMathContext(fourDigits); // NOTE: Since ICU 61, division no longer occurs with percentage parsing. // assertEquals("Division with fourDigits", 0.12, df.parse("12.001%").doubleValue()); assertEquals("Division with fourDigits", 0.12001, df.parse("12.001%").doubleValue()); df.setMathContext(unlimitedCeiling); assertEquals("Division with unlimitedCeiling", 0.12001, df.parse("12.001%").doubleValue()); // Test extreme division df = new DecimalFormat(); df.setMultiplier(1000000007); // prime number String hugeNumberString = "9876543212345678987654321234567898765432123456789"; // 49 digits BigInteger huge34Digits = new BigInteger("9876543143209876985185182338271622000000"); BigInteger huge4Digits = new BigInteger("9877000000000000000000000000000000000000"); BigInteger actual34Digits = ((BigDecimal) df.parse(hugeNumberString)).toBigIntegerExact(); assertEquals("Default extreme division", huge34Digits, actual34Digits); df.setMathContext(fourDigits); BigInteger actual4Digits = ((BigDecimal) df.parse(hugeNumberString)).toBigIntegerExact(); assertEquals("Extreme division with fourDigits", huge4Digits, actual4Digits); } /** * ArithmeticException is thrown when inverting multiplier produces a non-terminating * decimal result in conjunction with MathContext of unlimited precision. */ @Test public void testSetMathContextArithmeticException() { DecimalFormat df = new DecimalFormat(); df.setMultiplier(7); try { df.setMathContext(java.math.MathContext.UNLIMITED); fail("Extreme division with unlimited precision should throw ArithmeticException"); } catch (ArithmeticException e) { // expected } } /** * ArithmeticException is thrown when inverting multiplier produces a non-terminating * decimal result in conjunction with MathContext of unlimited precision. */ @Test public void testSetMathContextICUArithmeticException() { DecimalFormat df = new DecimalFormat(); df.setMultiplier(7); try { df.setMathContextICU(new MathContext(0)); fail("Extreme division with unlimited precision should throw ArithmeticException"); } catch (ArithmeticException e) { // expected } } /** * ArithmeticException is thrown when inverting multiplier produces a non-terminating * decimal result in conjunction with MathContext of unlimited precision. */ @Test public void testSetMultiplierArithmeticException() { DecimalFormat df = new DecimalFormat(); df.setMathContext(java.math.MathContext.UNLIMITED); try { df.setMultiplier(7); fail("Extreme division with unlimited precision should throw ArithmeticException"); } catch (ArithmeticException e) { // expected } } @Test public void Test10436() { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); df.setRoundingMode(MathContext.ROUND_CEILING); df.setMinimumFractionDigits(0); df.setMaximumFractionDigits(0); assertEquals("-.99 should round toward infinity", "-0", df.format(-0.99)); } @Test public void Test10765() { NumberFormat fmt = NumberFormat.getInstance(new ULocale("en")); fmt.setMinimumIntegerDigits(10); FieldPosition pos = new FieldPosition(NumberFormat.Field.GROUPING_SEPARATOR); StringBuffer sb = new StringBuffer(); fmt.format(1234567, sb, pos); assertEquals("Should have multiple grouping separators", "0,001,234,567", sb.toString()); assertEquals("FieldPosition should report the first occurence", 1, pos.getBeginIndex()); assertEquals("FieldPosition should report the first occurence", 2, pos.getEndIndex()); } @Test public void Test10997() { NumberFormat fmt = NumberFormat.getCurrencyInstance(new ULocale("en-US")); fmt.setMinimumFractionDigits(4); fmt.setMaximumFractionDigits(4); String str1 = fmt.format(new CurrencyAmount(123.45, Currency.getInstance("USD"))); String str2 = fmt.format(new CurrencyAmount(123.45, Currency.getInstance("EUR"))); assertEquals("minFrac 4 should be respected in default currency", "$123.4500", str1); assertEquals("minFrac 4 should be respected in different currency", "€123.4500", str2); } @Test public void Test11020() { DecimalFormatSymbols sym = new DecimalFormatSymbols(ULocale.FRANCE); DecimalFormat fmt = new DecimalFormat("0.05E0", sym); String result = fmt.format(12301.2).replace('\u00a0', ' '); assertEquals("Rounding increment should be applied after magnitude scaling", "1,25E4", result); } @Test public void Test11025() { String pattern = "¤¤ **####0.00"; DecimalFormatSymbols sym = new DecimalFormatSymbols(ULocale.FRANCE); DecimalFormat fmt = new DecimalFormat(pattern, sym); String result = fmt.format(433.0); assertEquals("Number should be padded to 11 characters", "EUR *433,00", result); } @Test public void Test11640_TripleCurrencySymbol() { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(); df.applyPattern("¤¤¤ 0"); String result = df.getPositivePrefix(); assertEquals("Triple-currency should give long name on getPositivePrefix", "US dollars ", result); } @Test public void Test11645() { String pattern = "#,##0.0#"; DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(); fmt.applyPattern(pattern); DecimalFormat fmtCopy; final int newMultiplier = 37; fmtCopy = (DecimalFormat) fmt.clone(); assertNotEquals("Value before setter", fmtCopy.getMultiplier(), newMultiplier); fmtCopy.setMultiplier(newMultiplier); assertEquals("Value after setter", fmtCopy.getMultiplier(), newMultiplier); fmtCopy.applyPattern(pattern); assertEquals("Value after applyPattern", fmtCopy.getMultiplier(), newMultiplier); assertFalse("multiplier", fmt.equals(fmtCopy)); final int newRoundingMode = RoundingMode.CEILING.ordinal(); fmtCopy = (DecimalFormat) fmt.clone(); assertNotEquals("Value before setter", fmtCopy.getRoundingMode(), newRoundingMode); fmtCopy.setRoundingMode(newRoundingMode); assertEquals("Value after setter", fmtCopy.getRoundingMode(), newRoundingMode); fmtCopy.applyPattern(pattern); assertEquals("Value after applyPattern", fmtCopy.getRoundingMode(), newRoundingMode); assertFalse("roundingMode", fmt.equals(fmtCopy)); final Currency newCurrency = Currency.getInstance("EAT"); fmtCopy = (DecimalFormat) fmt.clone(); assertNotEquals("Value before setter", fmtCopy.getCurrency(), newCurrency); fmtCopy.setCurrency(newCurrency); assertEquals("Value after setter", fmtCopy.getCurrency(), newCurrency); fmtCopy.applyPattern(pattern); assertEquals("Value after applyPattern", fmtCopy.getCurrency(), newCurrency); assertFalse("currency", fmt.equals(fmtCopy)); final CurrencyUsage newCurrencyUsage = CurrencyUsage.CASH; fmtCopy = (DecimalFormat) fmt.clone(); assertNotEquals("Value before setter", fmtCopy.getCurrencyUsage(), newCurrencyUsage); fmtCopy.setCurrencyUsage(CurrencyUsage.CASH); assertEquals("Value after setter", fmtCopy.getCurrencyUsage(), newCurrencyUsage); fmtCopy.applyPattern(pattern); assertEquals("Value after applyPattern", fmtCopy.getCurrencyUsage(), newCurrencyUsage); assertFalse("currencyUsage", fmt.equals(fmtCopy)); } @Test public void Test11646() { DecimalFormatSymbols symbols = new DecimalFormatSymbols(new ULocale("en_US")); String pattern = "\u00a4\u00a4\u00a4 0.00 %\u00a4\u00a4"; DecimalFormat fmt = new DecimalFormat(pattern, symbols); // Test equality with affixes. set affix methods can't capture special // characters which is why equality should fail. { DecimalFormat fmtCopy = (DecimalFormat) fmt.clone(); assertEquals("", fmt, fmtCopy); fmtCopy.setPositivePrefix(fmtCopy.getPositivePrefix()); assertNotEquals("", fmt, fmtCopy); } { DecimalFormat fmtCopy = (DecimalFormat) fmt.clone(); assertEquals("", fmt, fmtCopy); fmtCopy.setPositiveSuffix(fmtCopy.getPositiveSuffix()); assertNotEquals("", fmt, fmtCopy); } { DecimalFormat fmtCopy = (DecimalFormat) fmt.clone(); assertEquals("", fmt, fmtCopy); fmtCopy.setNegativePrefix(fmtCopy.getNegativePrefix()); assertNotEquals("", fmt, fmtCopy); } { DecimalFormat fmtCopy = (DecimalFormat) fmt.clone(); assertEquals("", fmt, fmtCopy); fmtCopy.setNegativeSuffix(fmtCopy.getNegativeSuffix()); assertNotEquals("", fmt, fmtCopy); } } @Test public void Test11648() { DecimalFormat df = new DecimalFormat("0.00"); df.setScientificNotation(true); String pat = df.toPattern(); assertEquals("A valid scientific notation pattern should be produced", "0.00E0", pat); } @Test public void Test11649() { String pattern = "\u00a4\u00a4\u00a4 0.00"; DecimalFormat fmt = new DecimalFormat(pattern); fmt.setCurrency(Currency.getInstance("USD")); assertEquals("Triple currency sign should format long name", "US dollars 12.34", fmt.format(12.34)); String newPattern = fmt.toPattern(); assertEquals("Should produce a valid pattern", pattern, newPattern); DecimalFormat fmt2 = new DecimalFormat(newPattern); fmt2.setCurrency(Currency.getInstance("USD")); assertEquals("Triple currency sign pattern should round-trip", "US dollars 12.34", fmt2.format(12.34)); String quotedPattern = "\u00a4\u00a4'\u00a4' 0.00"; DecimalFormat fmt3 = new DecimalFormat(quotedPattern); assertEquals("Should be treated as double currency sign", "USD\u00a4 12.34", fmt3.format(12.34)); String outQuotedPattern = fmt3.toPattern(); assertEquals("Double currency sign with quoted sign should round-trip", quotedPattern, outQuotedPattern); } @Test @Ignore public void Test11686() { // Only passes with slow mode. // TODO: Re-enable this test with slow mode. DecimalFormat df = new DecimalFormat(); df.setPositiveSuffix("0K"); df.setNegativeSuffix("0N"); expect2(df, 123, "1230K"); expect2(df, -123, "-1230N"); } @Test public void Test11839() { DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.ENGLISH); dfs.setMinusSignString("a∸"); dfs.setPlusSignString("b∔"); // ∔ U+2214 DOT PLUS DecimalFormat df = new DecimalFormat("0.00+;0.00-", dfs); String result = df.format(-1.234); assertEquals("Locale-specific minus sign should be used", "1.23a∸", result); result = df.format(1.234); assertEquals("Locale-specific plus sign should be used", "1.23b∔", result); // Test round-trip with parse expect2(df, -456, "456.00a∸"); expect2(df, 456, "456.00b∔"); } @Test public void Test12753() { ULocale locale = new ULocale("en-US"); DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); symbols.setDecimalSeparator('*'); DecimalFormat df = new DecimalFormat("0.00", symbols); df.setDecimalPatternMatchRequired(true); try { df.parse("123"); fail("Parsing integer succeeded even though setDecimalPatternMatchRequired was set"); } catch (ParseException e) { // Parse failed (expected) } } @Test public void Test12962() { String pat = "**0.00"; DecimalFormat df = new DecimalFormat(pat); String newPat = df.toPattern(); assertEquals("Format width changed upon calling applyPattern", pat.length(), newPat.length()); } @Test public void Test10354() { DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setNaN(""); DecimalFormat df = new DecimalFormat(); df.setDecimalFormatSymbols(dfs); try { df.formatToCharacterIterator(Double.NaN); // pass } catch (IllegalArgumentException e) { throw new AssertionError(e); } } @Test public void Test11913() { NumberFormat df = DecimalFormat.getInstance(); String result = df.format(new BigDecimal("1.23456789E400")); assertEquals("Should format more than 309 digits", "12,345,678", result.substring(0, 10)); assertEquals("Should format more than 309 digits", 534, result.length()); } @Test public void Test12045() { if (logKnownIssue("12045", "XSU is missing from fr")) { return; } NumberFormat nf = NumberFormat.getInstance(new ULocale("fr"), NumberFormat.PLURALCURRENCYSTYLE); ParsePosition ppos = new ParsePosition(0); try { CurrencyAmount result = nf.parseCurrency("2,34 XSU", ppos); assertEquals("Parsing should succeed on XSU", new CurrencyAmount(2.34, Currency.getInstance("XSU")), result); // pass } catch (Exception e) { //throw new AssertionError("Should have been able to parse XSU", e); throw new AssertionError("Should have been able to parse XSU: " + e.getMessage()); } } @Test public void Test11739() { NumberFormat nf = NumberFormat.getCurrencyInstance(new ULocale("sr_BA")); ((DecimalFormat) nf).applyPattern("#,##0.0 ¤¤¤"); ParsePosition ppos = new ParsePosition(0); CurrencyAmount result = nf.parseCurrency("1.500 амерички долар", ppos); assertEquals("Should parse to 1500 USD", new CurrencyAmount(1500, Currency.getInstance("USD")), result); } @Test public void Test11647() { DecimalFormat df = new DecimalFormat(); df.applyPattern("¤¤¤¤#"); String actual = df.format(123); assertEquals("Should replace 4 currency signs with U+FFFD", "\uFFFD123", actual); } @Test public void Test12567() { DecimalFormat df1 = (DecimalFormat) NumberFormat.getInstance(NumberFormat.PLURALCURRENCYSTYLE); DecimalFormat df2 = (DecimalFormat) NumberFormat.getInstance(NumberFormat.NUMBERSTYLE); df2.setCurrency(df1.getCurrency()); df2.setCurrencyPluralInfo(df1.getCurrencyPluralInfo()); df1.applyPattern("0.00"); df2.applyPattern("0.00"); assertEquals("df1 == df2", df1, df2); assertEquals("df2 == df1", df2, df1); df2.setPositivePrefix("abc"); assertNotEquals("df1 != df2", df1, df2); assertNotEquals("df2 != df1", df2, df1); } @Test public void Test11897_LocalizedPatternSeparator() { // In a locale with a different <list> symbol, like arabic, // kPatternSeparatorSymbol should still be ';' { DecimalFormatSymbols dfs = new DecimalFormatSymbols(new ULocale("ar")); assertEquals("pattern separator symbol should be ;", ';', dfs.getPatternSeparator()); } // However, the custom symbol should be used in localized notation // when set manually via API { DecimalFormatSymbols dfs = new DecimalFormatSymbols(new ULocale("en")); dfs.setPatternSeparator('!'); DecimalFormat df = new DecimalFormat("0", dfs); df.applyPattern("a0;b0"); // should not throw assertEquals("should apply the normal pattern", df.getNegativePrefix(), "b"); df.applyLocalizedPattern("c0!d0"); // should not throw assertEquals("should apply the localized pattern", df.getNegativePrefix(), "d"); } } @Test public void Test13055() { DecimalFormat df = (DecimalFormat) NumberFormat.getPercentInstance(); df.setMaximumFractionDigits(0); df.setRoundingMode(BigDecimal.ROUND_HALF_EVEN); assertEquals("Should round percent toward even number", "216%", df.format(2.155)); } @Test public void Test13056() { DecimalFormat df = new DecimalFormat("#,##0"); assertEquals("Primary grouping should return 3", 3, df.getGroupingSize()); assertEquals("Secondary grouping should return 0", 0, df.getSecondaryGroupingSize()); df.setSecondaryGroupingSize(3); assertEquals("Primary grouping should still return 3", 3, df.getGroupingSize()); assertEquals("Secondary grouping should round-trip", 3, df.getSecondaryGroupingSize()); df.setGroupingSize(4); assertEquals("Primary grouping should return 4", 4, df.getGroupingSize()); assertEquals("Secondary should remember explicit setting and return 3", 3, df.getSecondaryGroupingSize()); } @Test public void Test13074() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(new ULocale("bg-BG")); String result = df.format(987654.321); assertEquals("Locale 'bg' should not use monetary grouping", "987654,32 лв.", result); } @Test public void Test13088and13162() { ULocale loc = new ULocale("fa"); String pattern1 = "%\u00A0#,##0;%\u00A0-#,##0"; double num = -12.34; DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(loc); // If the symbols ever change in locale data, please call the setters so that this test // continues to use the old symbols. // The fa percent symbol does change in CLDR 32, so.... symbols.setPercentString("‎٪"); assertEquals("Checking for expected symbols", "‎−", symbols.getMinusSignString()); assertEquals("Checking for expected symbols", "‎٪", symbols.getPercentString()); DecimalFormat numfmt = new DecimalFormat(pattern1, symbols); expect2(numfmt, num, "‎٪ ‎−۱٬۲۳۴"); String pattern2 = "%#,##0;%-#,##0"; numfmt = new DecimalFormat(pattern2, symbols); expect2(numfmt, num, "‎٪‎−۱٬۲۳۴"); } @Test public void Test13113_MalformedPatterns() { String[][] cases = { {"'", "quoted literal"}, {"ab#c'd", "quoted literal"}, {"ab#c*", "unquoted literal"}, {"0#", "# cannot follow 0"}, {".#0", "0 cannot follow #"}, {"@0", "Cannot mix @ and 0"}, {"0@", "Cannot mix 0 and @"}, {"#x#", "unquoted special character"}, {"@#@", "# inside of a run of @"}, }; for (String[] cas : cases) { try { new DecimalFormat(cas[0]); fail("Should have thrown on malformed pattern"); } catch (IllegalArgumentException ex) { assertTrue("Exception should contain \"Malformed pattern\": " + ex.getMessage(), ex.getMessage().contains("Malformed pattern")); assertTrue("Exception should contain \"" + cas[1] + "\"" + ex.getMessage(), ex.getMessage().contains(cas[1])); } } } @Test public void Test13118() { DecimalFormat df = new DecimalFormat("@@@"); df.setScientificNotation(true); for (double d=12345.67; d>1e-6; d/=10) { String result = df.format(d); assertEquals("Should produce a string of expected length on " + d, d > 1 ? 6 : 7, result.length()); } } @Test public void Test13289() { DecimalFormat df = new DecimalFormat("#00.0#E0"); String result = df.format(0.00123); assertEquals("Should ignore scientific minInt if maxInt>minInt", "1.23E-3", result); } @Test public void Test13310() { // Note: if minInt > 8, then maxInt can be greater than 8. assertEquals("Should not throw an assertion error", "100000007.6E-1", new DecimalFormat("000000000.0#E0").format(10000000.76d)); } @Test public void Test13391() throws ParseException { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(new ULocale("ccp")); df.setParseStrict(true); String expected = "\uD804\uDD37\uD804\uDD38,\uD804\uDD39\uD804\uDD3A\uD804\uDD3B"; assertEquals("Should produce expected output in ccp", expected, df.format(12345)); Number result = df.parse(expected); assertEquals("Should parse to 12345 in ccp", 12345, result.longValue()); df = (DecimalFormat) NumberFormat.getScientificInstance(new ULocale("ccp")); df.setParseStrict(true); String expectedScientific = "\uD804\uDD37.\uD804\uDD39E\uD804\uDD38"; assertEquals("Should produce expected scientific output in ccp", expectedScientific, df.format(130)); Number resultScientific = df.parse(expectedScientific); assertEquals("Should parse scientific to 130 in ccp", 130, resultScientific.longValue()); } @Test public void Test13453_AffixContent() { DecimalFormat df = (DecimalFormat) DecimalFormat.getScientificInstance(); assertEquals("Scientific should NOT be included", "", df.getPositiveSuffix()); df = CompactDecimalFormat.getInstance(ULocale.ENGLISH, CompactDecimalFormat.CompactStyle.SHORT); assertEquals("Compact should NOT be included", "", df.getPositiveSuffix()); df = (DecimalFormat) DecimalFormat.getInstance(NumberFormat.ISOCURRENCYSTYLE); df.setCurrency(Currency.getInstance("GBP")); assertEquals("ISO currency SHOULD be included", "GBP", df.getPositivePrefix()); df = (DecimalFormat) DecimalFormat.getInstance(NumberFormat.PLURALCURRENCYSTYLE); df.setCurrency(Currency.getInstance("GBP")); assertEquals("Plural name SHOULD be included", " British pounds", df.getPositiveSuffix()); } @Test public void Test11035_FormatCurrencyAmount() { double amount = 12345.67; String expected = "12,345$67 ​"; Currency cur = Currency.getInstance("PTE"); // Test three ways to set currency via API ULocale loc1 = new ULocale("pt_PT"); NumberFormat fmt1 = NumberFormat.getCurrencyInstance(loc1); fmt1.setCurrency(cur); String actualSetCurrency = fmt1.format(amount); ULocale loc2 = new ULocale("pt_PT@currency=PTE"); NumberFormat fmt2 = NumberFormat.getCurrencyInstance(loc2); String actualLocaleString = fmt2.format(amount); ULocale loc3 = new ULocale("pt_PT"); NumberFormat fmt3 = NumberFormat.getCurrencyInstance(loc3); CurrencyAmount curAmt = new CurrencyAmount(amount, cur); String actualCurrencyAmount = fmt3.format(curAmt); assertEquals("Custom Currency Pattern, Set Currency", expected, actualSetCurrency); assertEquals("Custom Currency Pattern, Locale String", expected, actualCurrencyAmount); assertEquals("Custom Currency Pattern, CurrencyAmount", expected, actualLocaleString); } @Test public void testPercentZero() { DecimalFormat df = (DecimalFormat) NumberFormat.getPercentInstance(); String actual = df.format(0); assertEquals("Should have one zero digit", "0%", actual); } @Test public void testCurrencyZeroRounding() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(); df.setMaximumFractionDigits(0); String actual = df.format(0); assertEquals("Should have zero fraction digits", "$0", actual); } @Test public void testCustomCurrencySymbol() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(); df.setCurrency(Currency.getInstance("USD")); DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); symbols.setCurrencySymbol("#"); df.setDecimalFormatSymbols(symbols); String actual = df.format(123); assertEquals("Should use '#' instad of '$'", "# 123.00", actual); } @Test public void TestBasicSerializationRoundTrip() throws IOException, ClassNotFoundException { DecimalFormat df0 = new DecimalFormat("A-**#####,#00.00b¤"); // Write to byte stream ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(df0); oos.flush(); baos.close(); byte[] bytes = baos.toByteArray(); // Read from byte stream ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); Object obj = ois.readObject(); ois.close(); DecimalFormat df1 = (DecimalFormat) obj; // Test equality assertEquals("Did not round-trip through serialization", df0, df1); // Test basic functionality String str0 = df0.format(12345.67); String str1 = df1.format(12345.67); assertEquals("Serialized formatter does not produce same output", str0, str1); } @Test public void testGetSetCurrency() { DecimalFormat df = new DecimalFormat("¤#", DecimalFormatSymbols.getInstance(ULocale.US)); assertEquals("Currency should start out as the locale default", Currency.getInstance("USD"), df.getCurrency()); Currency curr = Currency.getInstance("EUR"); df.setCurrency(curr); assertEquals("Currency should equal EUR after set", curr, df.getCurrency()); String result = df.format(123); assertEquals("Currency should format as expected in EUR", "€123.00", result); } @Test public void testRoundingModeSetters() { DecimalFormat df1 = new DecimalFormat(); DecimalFormat df2 = new DecimalFormat(); df1.setRoundingMode(java.math.BigDecimal.ROUND_CEILING); assertNotEquals("Rounding mode was set to a non-default", df1, df2); df2.setRoundingMode(com.ibm.icu.math.BigDecimal.ROUND_CEILING); assertEquals("Rounding mode from icu.math and java.math should be the same", df1, df2); df2.setRoundingMode(java.math.RoundingMode.CEILING.ordinal()); assertEquals("Rounding mode ordinal from java.math.RoundingMode should be the same", df1, df2); } @Test public void testCurrencySignificantDigits() { ULocale locale = new ULocale("en-US"); DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(locale); df.setMaximumSignificantDigits(2); String result = df.format(1234); assertEquals("Currency rounding should obey significant digits", "$1,200", result); } @Test public void testParseStrictScientific() { // See ticket #13057 DecimalFormat df = (DecimalFormat) NumberFormat.getScientificInstance(); df.setParseStrict(true); ParsePosition ppos = new ParsePosition(0); Number result0 = df.parse("123E4", ppos); assertEquals("Should accept number with exponent", 1230000L, result0); assertEquals("Should consume the whole number", 5, ppos.getIndex()); ppos.setIndex(0); result0 = df.parse("123", ppos); // #13737: For backwards compatibility, do NOT require the exponent. assertEquals("Should NOT reject number without exponent", 123L, result0); ppos.setIndex(0); CurrencyAmount result1 = df.parseCurrency("USD123", ppos); assertEquals("Should NOT reject currency without exponent", new CurrencyAmount(123L, Currency.getInstance("USD")), result1); } @Test public void testParseLenientScientific() { DecimalFormat df = (DecimalFormat) NumberFormat.getScientificInstance(); ParsePosition ppos = new ParsePosition(0); Number result0 = df.parse("123E", ppos); assertEquals("Should parse the number in lenient mode", 123L, result0); assertEquals("Should stop before the E", 3, ppos.getIndex()); DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); dfs.setExponentSeparator("EE"); df.setDecimalFormatSymbols(dfs); ppos.setIndex(0); result0 = df.parse("123EE", ppos); assertEquals("Should parse the number in lenient mode", 123L, result0); assertEquals("Should stop before the EE", 3, ppos.getIndex()); } @Test public void testParseAcceptAsciiPercentPermilleFallback() { ULocale loc = new ULocale("ar"); DecimalFormat df = (DecimalFormat) NumberFormat.getPercentInstance(loc); ParsePosition ppos = new ParsePosition(0); Number result = df.parse("42%", ppos); assertEquals("Should parse as 0.42 even in ar", new BigDecimal("0.42"), result); assertEquals("Should consume the entire string even in ar", 3, ppos.getIndex()); // TODO: Is there a better way to make a localized permille formatter? df.applyPattern(df.toPattern().replace("%", "‰")); ppos.setIndex(0); result = df.parse("42‰", ppos); assertEquals("Should parse as 0.042 even in ar", new BigDecimal("0.042"), result); assertEquals("Should consume the entire string even in ar", 3, ppos.getIndex()); } @Test public void testParseSubtraction() { // TODO: Is this a case we need to support? It prevents us from automatically parsing // minus signs that appear after the number, like in "12-" vs "-12". DecimalFormat df = new DecimalFormat(); String str = "12 - 5"; ParsePosition ppos = new ParsePosition(0); Number n1 = df.parse(str, ppos); Number n2 = df.parse(str, ppos); assertEquals("Should parse 12 and -5", 12, n1.intValue()); assertEquals("Should parse 12 and -5", -5, n2.intValue()); } @Test public void testSetPrefixDefaultSuffix() { DecimalFormat df = (DecimalFormat) NumberFormat.getPercentInstance(); df.setPositivePrefix("+"); assertEquals("Should have manual plus sign and auto percent sign", "+100%", df.format(1)); } @Test public void testMultiCodePointPaddingInPattern() { DecimalFormat df = new DecimalFormat("a*'நி'###0b"); String result = df.format(12); assertEquals("Multi-codepoint padding should not be split", "aநிநி12b", result); df = new DecimalFormat("a*😁###0b"); result = df.format(12); assertEquals("Single-codepoint padding should not be split", "a😁😁12b", result); df = new DecimalFormat("a*''###0b"); result = df.format(12); assertEquals("Quote should be escapable in padding syntax", "a''12b", result); } @Test public void Test13737_ParseScientificStrict() { NumberFormat df = NumberFormat.getScientificInstance(ULocale.ENGLISH); df.setParseStrict(true); // Parse Test: exponent is not required, even in strict mode expect(df, "1.2", 1.2); } // TODO: Investigate this test and re-enable if appropriate. @Test @Ignore public void testParseAmbiguousAffixes() { BigDecimal positive = new BigDecimal("0.0567"); BigDecimal negative = new BigDecimal("-0.0567"); DecimalFormat df = new DecimalFormat(); df.setParseBigDecimal(true); String[] patterns = { "+0.00%;-0.00%", "+0.00%;0.00%", "0.00%;-0.00%" }; String[] inputs = { "+5.67%", "-5.67%", "5.67%" }; boolean[][] expectedPositive = { { true, false, true }, { true, false, false }, { true, false, true } }; for (int i=0; i<patterns.length; i++) { String pattern = patterns[i]; df.applyPattern(pattern); for (int j=0; j<inputs.length; j++) { String input = inputs[j]; ParsePosition ppos = new ParsePosition(0); Number actual = df.parse(input, ppos); BigDecimal expected = expectedPositive[i][j] ? positive : negative; String message = "Pattern " + pattern + " with input " + input; assertEquals(message, expected, actual); assertEquals(message, input.length(), ppos.getIndex()); } } } @Test public void testParseIgnorables() { // Also see the test case "test parse ignorables" in numberformattestspecification.txt DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); dfs.setPercentString("\u200E%\u200E"); DecimalFormat df = new DecimalFormat("0 %;-0a", dfs); ParsePosition ppos = new ParsePosition(0); Number result = df.parse("42\u200E%\u200E ", ppos); assertEquals("Should parse as percentage", new BigDecimal("0.42"), result); assertEquals("Should consume the trailing bidi since it is in the symbol", 5, ppos.getIndex()); ppos.setIndex(0); result = df.parse("-42a\u200E ", ppos); assertEquals("Should parse as percent", -0.42, result.doubleValue()); assertEquals("Should not consume the trailing bidi or whitespace", 4, ppos.getIndex()); // A few more cases based on the docstring: expect(df, "42%", 0.42); expect(df, "42 %", 0.42); expect(df, "42 %", 0.42); expect(df, "42\u00A0%", 0.42); } @Test public void testCustomCurrencyUsageOverridesPattern() { DecimalFormat df = new DecimalFormat("#,##0.###"); expect2(df, 1234, "1,234"); df.setCurrencyUsage(CurrencyUsage.STANDARD); expect2(df, 1234, "1,234.00"); df.setCurrencyUsage(null); expect2(df, 1234, "1,234"); } @Test public void testCurrencyUsageFractionOverrides() { NumberFormat df = DecimalFormat.getCurrencyInstance(ULocale.US); expect2(df, 35.0, "$35.00"); df.setMinimumFractionDigits(3); expect2(df, 35.0, "$35.000"); df.setMaximumFractionDigits(3); expect2(df, 35.0, "$35.000"); df.setMinimumFractionDigits(-1); expect2(df, 35.0, "$35.00"); df.setMaximumFractionDigits(-1); expect2(df, 35.0, "$35.00"); } @Test public void testParseVeryVeryLargeExponent() { DecimalFormat df = new DecimalFormat(); ParsePosition ppos = new ParsePosition(0); Object[][] cases = { {"1.2E+1234567890", Double.POSITIVE_INFINITY}, {"1.2E+999999999", new com.ibm.icu.math.BigDecimal("1.2E+999999999")}, {"1.2E+1000000000", Double.POSITIVE_INFINITY}, {"-1.2E+999999999", new com.ibm.icu.math.BigDecimal("-1.2E+999999999")}, {"-1.2E+1000000000", Double.NEGATIVE_INFINITY}, {"1.2E-999999999", new com.ibm.icu.math.BigDecimal("1.2E-999999999")}, {"1.2E-1000000000", 0.0}, {"-1.2E-999999999", new com.ibm.icu.math.BigDecimal("-1.2E-999999999")}, {"-1.2E-1000000000", -0.0}, }; for (Object[] cas : cases) { ppos.setIndex(0); String input = (String) cas[0]; Number expected = (Number) cas[1]; Number actual = df.parse(input, ppos); assertEquals(input, expected, actual); } } @Test public void testStringMethodsNPE() { String[] npeMethods = { "applyLocalizedPattern", "applyPattern", "setNegativePrefix", "setNegativeSuffix", "setPositivePrefix", "setPositiveSuffix" }; for (String npeMethod : npeMethods) { DecimalFormat df = new DecimalFormat(); try { DecimalFormat.class.getDeclaredMethod(npeMethod, String.class).invoke(df, (String) null); fail("NullPointerException not thrown in method " + npeMethod); } catch (InvocationTargetException e) { assertTrue("Exception should be NullPointerException in method " + npeMethod, e.getCause() instanceof NullPointerException); } catch (Exception e) { // Other reflection exceptions throw new AssertionError("Reflection error in method " + npeMethod + ": " + e.getMessage()); } } // Also test the constructors try { new DecimalFormat(null); fail("NullPointerException not thrown in 1-parameter constructor"); } catch (NullPointerException e) { // Expected } try { new DecimalFormat(null, new DecimalFormatSymbols()); fail("NullPointerException not thrown in 2-parameter constructor"); } catch (NullPointerException e) { // Expected } try { new DecimalFormat(null, new DecimalFormatSymbols(), CurrencyPluralInfo.getInstance(), 0); fail("NullPointerException not thrown in 4-parameter constructor"); } catch (NullPointerException e) { // Expected } } @Test public void testParseNoExponent() throws ParseException { DecimalFormat df = new DecimalFormat(); assertEquals("Parse no exponent has wrong default", false, df.getParseNoExponent()); Number result1 = df.parse("123E4"); df.setParseNoExponent(true); assertEquals("Parse no exponent getter is broken", true, df.getParseNoExponent()); Number result2 = df.parse("123E4"); assertEquals("Exponent did not parse before setParseNoExponent", result1, new Long(1230000)); assertEquals("Exponent parsed after setParseNoExponent", result2, new Long(123)); } @Test public void testMinimumGroupingDigits() { String[][] allExpected = { {"123", "123"}, {"1,230", "1230"}, {"12,300", "12,300"}, {"1,23,000", "1,23,000"} }; DecimalFormat df = new DecimalFormat("#,##,##0"); assertEquals("Minimum grouping digits has wrong default", 1, df.getMinimumGroupingDigits()); for (int l = 123, i=0; l <= 123000; l *= 10, i++) { df.setMinimumGroupingDigits(1); assertEquals("Minimum grouping digits getter is broken", 1, df.getMinimumGroupingDigits()); String actual = df.format(l); assertEquals("Output is wrong for 1, "+i, allExpected[i][0], actual); df.setMinimumGroupingDigits(2); assertEquals("Minimum grouping digits getter is broken", 2, df.getMinimumGroupingDigits()); actual = df.format(l); assertEquals("Output is wrong for 2, "+i, allExpected[i][1], actual); } } @Test public void testParseCaseSensitive() { String[] patterns = {"a#b", "A#B"}; String[] inputs = {"a500b", "A500b", "a500B", "a500e10b", "a500E10b"}; int[][] expectedParsePositions = { {5, 5, 5, 8, 8}, // case insensitive, pattern 0 {5, 0, 4, 4, 8}, // case sensitive, pattern 0 {5, 5, 5, 8, 8}, // case insensitive, pattern 1 {0, 4, 0, 0, 0}, // case sensitive, pattern 1 }; for (int p = 0; p < patterns.length; p++) { String pat = patterns[p]; DecimalFormat df = new DecimalFormat(pat); assertEquals("parseCaseSensitive default is wrong", false, df.getParseCaseSensitive()); for (int i = 0; i < inputs.length; i++) { String inp = inputs[i]; df.setParseCaseSensitive(false); assertEquals("parseCaseSensitive getter is broken", false, df.getParseCaseSensitive()); ParsePosition actualInsensitive = new ParsePosition(0); df.parse(inp, actualInsensitive); assertEquals("Insensitive, pattern "+p+", input "+i, expectedParsePositions[p*2][i], actualInsensitive.getIndex()); df.setParseCaseSensitive(true); assertEquals("parseCaseSensitive getter is broken", true, df.getParseCaseSensitive()); ParsePosition actualSensitive = new ParsePosition(0); df.parse(inp, actualSensitive); assertEquals("Sensitive, pattern "+p+", input "+i, expectedParsePositions[p*2+1][i], actualSensitive.getIndex()); } } } @Test public void testPlusSignAlwaysShown() throws ParseException { double[] numbers = {0.012, 5.78, 0, -0.012, -5.78}; ULocale[] locs = {new ULocale("en-US"), new ULocale("ar-EG"), new ULocale("es-CL")}; String[][][] expecteds = { // en-US { // decimal { "+0.012", "+5.78", "+0", "-0.012", "-5.78" }, // currency { "+$0.01", "+$5.78", "+$0.00", "-$0.01", "-$5.78" } }, // ar-EG (interesting because the plus sign string starts with \u061C) { // decimal { "\u061C+\u0660\u066B\u0660\u0661\u0662", // "؜+٠٫٠١٢" "\u061C+\u0665\u066B\u0667\u0668", // "؜+٥٫٧٨" "\u061C+\u0660", // "؜+٠" "\u061C-\u0660\u066B\u0660\u0661\u0662", // "؜-٠٫٠١٢" "\u061C-\u0665\u066B\u0667\u0668", // "؜-٥٫٧٨" }, // currency (\062C.\0645.\200F is the currency sign in ar for EGP) { "\u061C+\u0660\u066B\u0660\u0661\u00A0\u062C.\u0645.\u200F", "\u061C+\u0665\u066B\u0667\u0668\u00A0\u062C.\u0645.\u200F", "\u061C+\u0660\u066B\u0660\u0660\u00A0\u062C.\u0645.\u200F", "\u061C-\u0660\u066B\u0660\u0661\u00A0\u062C.\u0645.\u200F", "\u061C-\u0665\u066B\u0667\u0668\u00A0\u062C.\u0645.\u200F" } }, // es-CL (interesting because of position of sign in currency) { // decimal { "+0,012", "+5,78", "+0", "-0,012", "-5,78" }, // currency (note: rounding for es-CL's currency, CLP, is 0 fraction digits) { "$+0", "$+6", "$+0", "$-0", "$-6" } } }; for (int i=0; i<locs.length; i++) { ULocale loc = locs[i]; DecimalFormat df1 = (DecimalFormat) NumberFormat.getNumberInstance(loc); assertFalse("Default should be false", df1.getSignAlwaysShown()); df1.setSignAlwaysShown(true); assertTrue("Getter should now return true", df1.getSignAlwaysShown()); DecimalFormat df2 = (DecimalFormat) NumberFormat.getCurrencyInstance(loc); assertFalse("Default should be false", df2.getSignAlwaysShown()); df2.setSignAlwaysShown(true); assertTrue("Getter should now return true", df2.getSignAlwaysShown()); for (int j=0; j<2; j++) { DecimalFormat df = (j == 0) ? df1 : df2; for (int k=0; k<numbers.length; k++) { double d = numbers[k]; String exp = expecteds[i][j][k]; String act = df.format(d); assertEquals("Locale " + loc + ", type " + j + ", " + d, exp, act); BigDecimal parsedExp = BigDecimal.valueOf(d); if (j == 1) { // Currency-round expected parse output int scale = (i == 2) ? 0 : 2; parsedExp = parsedExp.setScale(scale, BigDecimal.ROUND_HALF_EVEN); } Number parsedNum = df.parse(exp); BigDecimal parsedAct = (parsedNum.getClass() == BigDecimal.class) ? (BigDecimal) parsedNum : BigDecimal.valueOf(parsedNum.doubleValue()); assertEquals( "Locale " + loc + ", type " + j + ", " + d + ", " + parsedExp + " => " + parsedAct, 0, parsedExp.compareTo(parsedAct)); } } } } @Test public void Test20073_StrictPercentParseErrorIndex() { ParsePosition parsePosition = new ParsePosition(0); DecimalFormat df = new DecimalFormat("0%", DecimalFormatSymbols.getInstance(Locale.US)); df.setParseStrict(true); Number number = df.parse("%2%", parsePosition); assertNull("", number); assertEquals("", 0, parsePosition.getIndex()); assertEquals("", 0, parsePosition.getErrorIndex()); } @Test public void Test11626_CustomizeCurrencyPluralInfo() throws ParseException { // Use locale sr because it has interesting plural rules. ULocale locale = ULocale.forLanguageTag("sr"); DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); CurrencyPluralInfo info = CurrencyPluralInfo.getInstance(locale); info.setCurrencyPluralPattern("one", "0 qwerty"); info.setCurrencyPluralPattern("few", "0 dvorak"); DecimalFormat df = new DecimalFormat("#", symbols, info, NumberFormat.CURRENCYSTYLE); df.setCurrency(Currency.getInstance("USD")); df.setMaximumFractionDigits(0); assertEquals("Plural one", "1 qwerty", df.format(1)); assertEquals("Plural few", "3 dvorak", df.format(3)); assertEquals("Plural other", "99 америчких долара", df.format(99)); info.setPluralRules("few: n is 1; one: n in 2..4"); df.setCurrencyPluralInfo(info); assertEquals("Plural one", "1 dvorak", df.format(1)); assertEquals("Plural few", "3 qwerty", df.format(3)); assertEquals("Plural other", "99 америчких долара", df.format(99)); } @Test public void TestNarrowCurrencySymbols() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(ULocale.CANADA); df.setCurrency(Currency.getInstance("USD")); expect2(df, 123.45, "US$123.45"); String pattern = df.toPattern(); pattern = pattern.replace("¤", "¤¤¤¤¤"); df.applyPattern(pattern); // Note: Narrow currency is not parseable because of ambiguity. assertEquals("Narrow currency symbol for USD in en_CA is $", "$123.45", df.format(123.45)); } @Test public void TestAffixOverrideBehavior() { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(ULocale.ENGLISH); expect2(df, 100, "100"); expect2(df, -100, "-100"); // This is not the right way to set an override plus sign, but we need to support it for compatibility. df.setPositivePrefix("+"); expect2(df, 100, "+100"); expect2(df, -100, "-100"); // note: the positive prefix does not affect the negative prefix df.applyPattern("a0"); expect2(df, 100, "a100"); expect2(df, -100, "-a100"); } @Test public void TestCurrencyRoundingMinWithoutMax() { NumberFormat currencyFormat = DecimalFormat.getCurrencyInstance(Locale.US); currencyFormat.setCurrency(Currency.getInstance("AUD")); currencyFormat.setMinimumFractionDigits(0); expect(currencyFormat, 0.001, "A$0"); // NOTE: The size of the increment takes precedent over minFrac since ICU 59. // CAD-Cash uses nickel rounding. currencyFormat = DecimalFormat.getCurrencyInstance(Locale.US); currencyFormat.setCurrency(Currency.getInstance("CAD")); ((DecimalFormat)currencyFormat).setCurrencyUsage(CurrencyUsage.CASH); currencyFormat.setMinimumFractionDigits(0); // expect(currencyFormat, 0.08, "CA$0.1"); // ICU 58 and down expect(currencyFormat, 0.08, "CA$0.10"); // ICU 59 and up } @Test public void testParsePositionIncrease() { String input = "123\n456\n$789"; ParsePosition ppos = new ParsePosition(0); DecimalFormat df = new DecimalFormat(); df.parse(input, ppos); assertEquals("Should stop after first entry", 3, ppos.getIndex()); ppos.setIndex(ppos.getIndex() + 1); df.parse(input, ppos); assertEquals("Should stop after second entry", 7, ppos.getIndex()); ppos.setIndex(ppos.getIndex() + 1); df.parseCurrency(input, ppos); // test parseCurrency API as well assertEquals("Should stop after third entry", 12, ppos.getIndex()); } @Test public void testTrailingMinusSign() { String input = "52-"; DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(ULocale.ENGLISH); ParsePosition ppos = new ParsePosition(0); Number result = df.parse(input, ppos); assertEquals("Trailing sign should NOT be accepted after the number in English by default", 52.0, result.doubleValue(), 0.0); df.applyPattern("#;#-"); ppos.setIndex(0); result = df.parse(input, ppos); assertEquals("Trailing sign SHOULD be accepted if there is one in the pattern", -52.0, result.doubleValue(), 0.0); } @Test public void testScientificCustomSign() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); dfs.setMinusSignString("nnn"); dfs.setPlusSignString("ppp"); DecimalFormat df = new DecimalFormat("0E0", dfs); df.setExponentSignAlwaysShown(true); expect2(df, 0.5, "5Ennn1"); expect2(df, 50, "5Eppp1"); } @Test public void testParsePercentInPattern() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); DecimalFormat df = new DecimalFormat("0x%", dfs); df.setParseStrict(true); expect2(df, 0.5, "50x%"); } @Test public void testParseIsoStrict() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); DecimalFormat df = new DecimalFormat("¤¤0;-0¤¤", dfs); df.setCurrency(Currency.getInstance("USD")); df.setParseStrict(true); expect2(df, 45, "USD 45.00"); expect2(df, -45, "-45.00 USD"); } @Test public void test13684_FrenchPercentParsing() { NumberFormat numberFormat = NumberFormat.getPercentInstance(ULocale.FRENCH); numberFormat.setParseStrict(true); ParsePosition ppos = new ParsePosition(0); Number percentage = numberFormat.parse("8\u00A0%", ppos); assertEquals("Should parse successfully", 0.08, percentage.doubleValue()); assertEquals("Should consume whole string", 3, ppos.getIndex()); } @Test public void testStrictParseCurrencyLongNames() { DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(ULocale.ENGLISH, DecimalFormat.PLURALCURRENCYSTYLE); df.setParseStrict(true); df.setCurrency(Currency.getInstance("USD")); double input = 514.23; String formatted = df.format(input); String expected = "514.23 US dollars"; assertEquals("Should format as expected", expected, formatted); ParsePosition ppos = new ParsePosition(0); CurrencyAmount ca = df.parseCurrency(formatted, ppos); assertEquals("Should consume whole number", ppos.getIndex(), 17); assertEquals("Number should round-trip", ca.getNumber().doubleValue(), input); assertEquals("Should get correct currency", ca.getCurrency().getCurrencyCode(), "USD"); // Should also round-trip in non-currency parsing expect2(df, input, expected); } @Test public void testStrictParseCurrencySpacing() { DecimalFormat df = new DecimalFormat("¤ 0", DecimalFormatSymbols.getInstance(ULocale.ROOT)); df.setCurrency(Currency.getInstance("USD")); df.setParseStrict(true); expect2(df, -51.42, "-US$ 51.42"); } @Test public void testCaseSensitiveCustomIsoCurrency() { DecimalFormat df = new DecimalFormat("¤¤0", DecimalFormatSymbols.getInstance(ULocale.ENGLISH)); df.setCurrency(Currency.getInstance("ICU")); ParsePosition ppos = new ParsePosition(0); df.parseCurrency("icu123", ppos); assertEquals("Should succeed", 6, ppos.getIndex()); assertEquals("Should succeed", -1, ppos.getErrorIndex()); } @Test public void testCurrencyPluralAffixOverrides() { // The affix setters should override CurrencyPluralInfo, used in the plural currency constructor. DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(ULocale.ENGLISH, NumberFormat.PLURALCURRENCYSTYLE); assertEquals("Defaults to unknown currency", " (unknown currency)", df.getPositiveSuffix()); df.setCurrency(Currency.getInstance("USD")); assertEquals("Should resolve to CurrencyPluralInfo", " US dollars", df.getPositiveSuffix()); df.setPositiveSuffix("lala"); assertEquals("Custom suffix should round-trip", "lala", df.getPositiveSuffix()); assertEquals("Custom suffix should be used in formatting", "123.00lala", df.format(123)); } @Test public void testParseDoubleMinus() { DecimalFormat df = new DecimalFormat("-0", DecimalFormatSymbols.getInstance(ULocale.ENGLISH)); expect2(df, -5, "--5"); } @Test public void testParsePercentRegression() { DecimalFormat df1 = (DecimalFormat) NumberFormat.getInstance(ULocale.ENGLISH); DecimalFormat df2 = (DecimalFormat) NumberFormat.getPercentInstance(ULocale.ENGLISH); df1.setParseStrict(false); df2.setParseStrict(false); { ParsePosition ppos = new ParsePosition(0); Number result = df1.parse("50%", ppos); assertEquals("df1 should accept a number but not the percent sign", 2, ppos.getIndex()); assertEquals("df1 should return the number as 50", 50.0, result.doubleValue()); } { ParsePosition ppos = new ParsePosition(0); Number result = df2.parse("50%", ppos); assertEquals("df2 should accept the percent sign", 3, ppos.getIndex()); assertEquals("df2 should return the number as 0.5", 0.5, result.doubleValue()); } { ParsePosition ppos = new ParsePosition(0); Number result = df2.parse("50", ppos); assertEquals("df2 should return the number as 0.5 even though the percent sign is missing", 0.5, result.doubleValue()); } } @Test public void test13148_GroupingSeparatorOverride() throws Exception { DecimalFormat fmt = (DecimalFormat)NumberFormat.getInstance(new ULocale("en", "ZA")); DecimalFormatSymbols symbols = fmt.getDecimalFormatSymbols(); symbols.setDecimalSeparator('.'); symbols.setGroupingSeparator(','); fmt.setDecimalFormatSymbols(symbols); Number number = fmt.parse("300,000"); assertEquals("Should use custom symbols and not monetary symbols", 300000L, number); } @Test public void test11897_LocalizedPatternSeparator() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); dfs.setPatternSeparator('!'); DecimalFormat df = new DecimalFormat("0", dfs); df.applyPattern("a0;b0"); // should not throw assertEquals("should apply the normal pattern", df.getNegativePrefix(), "b"); df.applyLocalizedPattern("c0!d0"); // should not throw assertEquals("should apply the localized pattern", df.getNegativePrefix(), "d"); } @Test public void test13777_ParseLongNameNonCurrencyMode() { // Currency long name should round-trip even when non-currency parsing is used. NumberFormat df = NumberFormat.getInstance(ULocale.US, NumberFormat.PLURALCURRENCYSTYLE); expect2(df, 1.5, "1.50 US dollars"); } @Test public void test13804_EmptyStringsWhenParsing() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); dfs.setCurrencySymbol(""); dfs.setDecimalSeparatorString(""); dfs.setDigitStrings(new String[] { "", "", "", "", "", "", "", "", "", "" }); dfs.setExponentMultiplicationSign(""); dfs.setExponentSeparator(""); dfs.setGroupingSeparatorString(""); dfs.setInfinity(""); dfs.setInternationalCurrencySymbol(""); dfs.setMinusSignString(""); dfs.setMonetaryDecimalSeparatorString(""); dfs.setMonetaryGroupingSeparatorString(""); dfs.setNaN(""); dfs.setPatternForCurrencySpacing(DecimalFormatSymbols.CURRENCY_SPC_INSERT, false, ""); dfs.setPatternForCurrencySpacing(DecimalFormatSymbols.CURRENCY_SPC_INSERT, true, ""); dfs.setPercentString(""); dfs.setPerMillString(""); dfs.setPlusSignString(""); DecimalFormat df = new DecimalFormat("0", dfs); df.setGroupingUsed(true); df.setScientificNotation(true); df.setParseStrict(false); // enable all matchers df.format(0); // should not throw or hit infinite loop String[] samples = new String[] { "", "123", "$123", "-", "+", "44%", "1E+2.3" }; for (String sample : samples) { logln("Attempting parse on: " + sample); // We don't care about the results, only that we don't throw and don't loop. ParsePosition ppos = new ParsePosition(0); df.parse(sample, ppos); ppos = new ParsePosition(0); df.parseCurrency(sample, ppos); } // Test with a nonempty exponent separator symbol to cover more code dfs.setExponentSeparator("E"); df.setDecimalFormatSymbols(dfs); { ParsePosition ppos = new ParsePosition(0); df.parse("1E+2.3", ppos); } } @Test public void Test20037_ScientificIntegerOverflow() throws ParseException { NumberFormat nf = NumberFormat.getInstance(ULocale.US); // Test overflow of exponent Number result = nf.parse("1E-2147483648"); assertEquals("Should snap to zero", "0", result.toString()); // Test edge case overflow of exponent // Note: the behavior is different from C++; this is probably due to the // intermediate BigDecimal form, which has its own restrictions result = nf.parse("1E-2147483647E-1"); assertEquals("Should not overflow and should parse only the first exponent", "0.0", result.toString()); // For Java, we should get *pretty close* to 2^31. result = nf.parse("1E-547483647"); assertEquals("Should *not* snap to zero", "1E-547483647", result.toString()); } @Test public void test13840_ParseLongStringCrash() throws ParseException { NumberFormat nf = NumberFormat.getInstance(ULocale.ENGLISH); String bigString = "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111"; Number result = nf.parse(bigString); // Normalize the input string: BigDecimal expectedBigDecimal = new BigDecimal(bigString); String expectedUString = expectedBigDecimal.toString(); // Get the output string: BigDecimal actualBigDecimal = (BigDecimal) result; String actualUString = actualBigDecimal.toString(); assertEquals("Should round-trip without crashing", expectedUString, actualUString); } }
./CrossVul/dataset_final_sorted/CWE-190/java/bad_434_5
crossvul-java_data_good_434_3
// © 2017 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License package com.ibm.icu.impl.number; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.text.FieldPosition; import com.ibm.icu.impl.StandardPlural; import com.ibm.icu.impl.Utility; import com.ibm.icu.text.PluralRules; import com.ibm.icu.text.PluralRules.Operand; import com.ibm.icu.text.UFieldPosition; /** * Represents numbers and digit display properties using Binary Coded Decimal (BCD). * * @implements {@link DecimalQuantity} */ public abstract class DecimalQuantity_AbstractBCD implements DecimalQuantity { /** * The power of ten corresponding to the least significant digit in the BCD. For example, if this * object represents the number "3.14", the BCD will be "0x314" and the scale will be -2. * * <p> * Note that in {@link java.math.BigDecimal}, the scale is defined differently: the number of digits * after the decimal place, which is the negative of our definition of scale. */ protected int scale; /** * The number of digits in the BCD. For example, "1007" has BCD "0x1007" and precision 4. A long * cannot represent precisions greater than 16. * * <p> * This value must be re-calculated whenever the value in bcd changes by using * {@link #computePrecisionAndCompact()}. */ protected int precision; /** * A bitmask of properties relating to the number represented by this object. * * @see #NEGATIVE_FLAG * @see #INFINITY_FLAG * @see #NAN_FLAG */ protected byte flags; protected static final int NEGATIVE_FLAG = 1; protected static final int INFINITY_FLAG = 2; protected static final int NAN_FLAG = 4; // The following three fields relate to the double-to-ascii fast path algorithm. // When a double is given to DecimalQuantityBCD, it is converted to using a fast algorithm. The // fast algorithm guarantees correctness to only the first ~12 digits of the double. The process // of rounding the number ensures that the converted digits are correct, falling back to a slow- // path algorithm if required. Therefore, if a DecimalQuantity is constructed from a double, it // is *required* that roundToMagnitude(), roundToIncrement(), or roundToInfinity() is called. If // you don't round, assertions will fail in certain other methods if you try calling them. /** * The original number provided by the user and which is represented in BCD. Used when we need to * re-compute the BCD for an exact double representation. */ protected double origDouble; /** * The change in magnitude relative to the original double. Used when we need to re-compute the BCD * for an exact double representation. */ protected int origDelta; /** * Whether the value in the BCD comes from the double fast path without having been rounded to ensure * correctness */ protected boolean isApproximate; // Four positions: left optional '(', left required '[', right required ']', right optional ')'. // These four positions determine which digits are displayed in the output string. They do NOT // affect rounding. These positions are internal-only and can be specified only by the public // endpoints like setFractionLength, setIntegerLength, and setSignificantDigits, among others. // // * Digits between lReqPos and rReqPos are in the "required zone" and are always displayed. // * Digits between lOptPos and rOptPos but outside the required zone are in the "optional zone" // and are displayed unless they are trailing off the left or right edge of the number and // have a numerical value of zero. In order to be "trailing", the digits need to be beyond // the decimal point in their respective directions. // * Digits outside of the "optional zone" are never displayed. // // See the table below for illustrative examples. // // +---------+---------+---------+---------+------------+------------------------+--------------+ // | lOptPos | lReqPos | rReqPos | rOptPos | number | positions | en-US string | // +---------+---------+---------+---------+------------+------------------------+--------------+ // | 5 | 2 | -1 | -5 | 1234.567 | ( 12[34.5]67 ) | 1,234.567 | // | 3 | 2 | -1 | -5 | 1234.567 | 1(2[34.5]67 ) | 234.567 | // | 3 | 2 | -1 | -2 | 1234.567 | 1(2[34.5]6)7 | 234.56 | // | 6 | 4 | 2 | -5 | 123456789. | 123(45[67]89. ) | 456,789. | // | 6 | 4 | 2 | 1 | 123456789. | 123(45[67]8)9. | 456,780. | // | -1 | -1 | -3 | -4 | 0.123456 | 0.1([23]4)56 | .0234 | // | 6 | 4 | -2 | -2 | 12.3 | ( [ 12.3 ]) | 0012.30 | // +---------+---------+---------+---------+------------+------------------------+--------------+ // protected int lOptPos = Integer.MAX_VALUE; protected int lReqPos = 0; protected int rReqPos = 0; protected int rOptPos = Integer.MIN_VALUE; @Override public void copyFrom(DecimalQuantity _other) { copyBcdFrom(_other); DecimalQuantity_AbstractBCD other = (DecimalQuantity_AbstractBCD) _other; lOptPos = other.lOptPos; lReqPos = other.lReqPos; rReqPos = other.rReqPos; rOptPos = other.rOptPos; scale = other.scale; precision = other.precision; flags = other.flags; origDouble = other.origDouble; origDelta = other.origDelta; isApproximate = other.isApproximate; } public DecimalQuantity_AbstractBCD clear() { lOptPos = Integer.MAX_VALUE; lReqPos = 0; rReqPos = 0; rOptPos = Integer.MIN_VALUE; flags = 0; setBcdToZero(); // sets scale, precision, hasDouble, origDouble, origDelta, and BCD data return this; } @Override public void setIntegerLength(int minInt, int maxInt) { // Validation should happen outside of DecimalQuantity, e.g., in the Rounder class. assert minInt >= 0; assert maxInt >= minInt; // Special behavior: do not set minInt to be less than what is already set. // This is so significant digits rounding can set the integer length. if (minInt < lReqPos) { minInt = lReqPos; } // Save values into internal state // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE lOptPos = maxInt; lReqPos = minInt; } @Override public void setFractionLength(int minFrac, int maxFrac) { // Validation should happen outside of DecimalQuantity, e.g., in the Rounder class. assert minFrac >= 0; assert maxFrac >= minFrac; // Save values into internal state // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE rReqPos = -minFrac; rOptPos = -maxFrac; } @Override public long getPositionFingerprint() { long fingerprint = 0; fingerprint ^= lOptPos; fingerprint ^= (lReqPos << 16); fingerprint ^= ((long) rReqPos << 32); fingerprint ^= ((long) rOptPos << 48); return fingerprint; } @Override public void roundToIncrement(BigDecimal roundingIncrement, MathContext mathContext) { // TODO(13701): Avoid this check on every call to roundToIncrement(). BigDecimal stripped = roundingIncrement.stripTrailingZeros(); if (stripped.unscaledValue().compareTo(BigInteger.valueOf(5)) == 0) { roundToNickel(-stripped.scale(), mathContext); return; } BigDecimal temp = toBigDecimal(); temp = temp.divide(roundingIncrement, 0, mathContext.getRoundingMode()) .multiply(roundingIncrement).round(mathContext); if (temp.signum() == 0) { setBcdToZero(); // keeps negative flag for -0.0 } else { setToBigDecimal(temp); } } @Override public void multiplyBy(BigDecimal multiplicand) { if (isInfinite() || isZero() || isNaN()) { return; } BigDecimal temp = toBigDecimal(); temp = temp.multiply(multiplicand); setToBigDecimal(temp); } @Override public void negate() { flags ^= NEGATIVE_FLAG; } @Override public int getMagnitude() throws ArithmeticException { if (precision == 0) { throw new ArithmeticException("Magnitude is not well-defined for zero"); } else { return scale + precision - 1; } } @Override public void adjustMagnitude(int delta) { if (precision != 0) { scale = Utility.addExact(scale, delta); origDelta = Utility.addExact(origDelta, delta); } } @Override public StandardPlural getStandardPlural(PluralRules rules) { if (rules == null) { // Fail gracefully if the user didn't provide a PluralRules return StandardPlural.OTHER; } else { @SuppressWarnings("deprecation") String ruleString = rules.select(this); return StandardPlural.orOtherFromString(ruleString); } } @Override public double getPluralOperand(Operand operand) { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; switch (operand) { case i: // Invert the negative sign if necessary return isNegative() ? -toLong(true) : toLong(true); case f: return toFractionLong(true); case t: return toFractionLong(false); case v: return fractionCount(); case w: return fractionCountWithoutTrailingZeros(); default: return Math.abs(toDouble()); } } @Override public void populateUFieldPosition(FieldPosition fp) { if (fp instanceof UFieldPosition) { ((UFieldPosition) fp).setFractionDigits((int) getPluralOperand(Operand.v), (long) getPluralOperand(Operand.f)); } } @Override public int getUpperDisplayMagnitude() { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; int magnitude = scale + precision; int result = (lReqPos > magnitude) ? lReqPos : (lOptPos < magnitude) ? lOptPos : magnitude; return result - 1; } @Override public int getLowerDisplayMagnitude() { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; int magnitude = scale; int result = (rReqPos < magnitude) ? rReqPos : (rOptPos > magnitude) ? rOptPos : magnitude; return result; } @Override public byte getDigit(int magnitude) { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; return getDigitPos(magnitude - scale); } private int fractionCount() { return -getLowerDisplayMagnitude(); } private int fractionCountWithoutTrailingZeros() { return Math.max(-scale, 0); } @Override public boolean isNegative() { return (flags & NEGATIVE_FLAG) != 0; } @Override public int signum() { return isNegative() ? -1 : isZero() ? 0 : 1; } @Override public boolean isInfinite() { return (flags & INFINITY_FLAG) != 0; } @Override public boolean isNaN() { return (flags & NAN_FLAG) != 0; } @Override public boolean isZero() { return precision == 0; } public void setToInt(int n) { setBcdToZero(); flags = 0; if (n < 0) { flags |= NEGATIVE_FLAG; n = -n; } if (n != 0) { _setToInt(n); compact(); } } private void _setToInt(int n) { if (n == Integer.MIN_VALUE) { readLongToBcd(-(long) n); } else { readIntToBcd(n); } } public void setToLong(long n) { setBcdToZero(); flags = 0; if (n < 0) { flags |= NEGATIVE_FLAG; n = -n; } if (n != 0) { _setToLong(n); compact(); } } private void _setToLong(long n) { if (n == Long.MIN_VALUE) { readBigIntegerToBcd(BigInteger.valueOf(n).negate()); } else if (n <= Integer.MAX_VALUE) { readIntToBcd((int) n); } else { readLongToBcd(n); } } public void setToBigInteger(BigInteger n) { setBcdToZero(); flags = 0; if (n.signum() == -1) { flags |= NEGATIVE_FLAG; n = n.negate(); } if (n.signum() != 0) { _setToBigInteger(n); compact(); } } private void _setToBigInteger(BigInteger n) { if (n.bitLength() < 32) { readIntToBcd(n.intValue()); } else if (n.bitLength() < 64) { readLongToBcd(n.longValue()); } else { readBigIntegerToBcd(n); } } /** * Sets the internal BCD state to represent the value in the given double. * * @param n * The value to consume. */ public void setToDouble(double n) { setBcdToZero(); flags = 0; // Double.compare() handles +0.0 vs -0.0 if (Double.compare(n, 0.0) < 0) { flags |= NEGATIVE_FLAG; n = -n; } if (Double.isNaN(n)) { flags |= NAN_FLAG; } else if (Double.isInfinite(n)) { flags |= INFINITY_FLAG; } else if (n != 0) { _setToDoubleFast(n); compact(); } } private static final double[] DOUBLE_MULTIPLIERS = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21 }; /** * Uses double multiplication and division to get the number into integer space before converting to * digits. Since double arithmetic is inexact, the resulting digits may not be accurate. */ private void _setToDoubleFast(double n) { isApproximate = true; origDouble = n; origDelta = 0; // NOTE: Unlike ICU4C, doubles are always IEEE 754 doubles. long ieeeBits = Double.doubleToLongBits(n); int exponent = (int) ((ieeeBits & 0x7ff0000000000000L) >> 52) - 0x3ff; // Not all integers can be represented exactly for exponent > 52 if (exponent <= 52 && (long) n == n) { _setToLong((long) n); return; } // 3.3219... is log2(10) int fracLength = (int) ((52 - exponent) / 3.32192809489); if (fracLength >= 0) { int i = fracLength; // 1e22 is the largest exact double. for (; i >= 22; i -= 22) n *= 1e22; n *= DOUBLE_MULTIPLIERS[i]; } else { int i = fracLength; // 1e22 is the largest exact double. for (; i <= -22; i += 22) n /= 1e22; n /= DOUBLE_MULTIPLIERS[-i]; } long result = Math.round(n); if (result != 0) { _setToLong(result); scale -= fracLength; } } /** * Uses Double.toString() to obtain an exact accurate representation of the double, overwriting it * into the BCD. This method can be called at any point after {@link #_setToDoubleFast} while * {@link #isApproximate} is still true. */ private void convertToAccurateDouble() { double n = origDouble; assert n != 0; int delta = origDelta; setBcdToZero(); // Call the slow oracle function (Double.toString in Java, sprintf in C++). String dstr = Double.toString(n); if (dstr.indexOf('E') != -1) { // Case 1: Exponential notation. assert dstr.indexOf('.') == 1; int expPos = dstr.indexOf('E'); _setToLong(Long.parseLong(dstr.charAt(0) + dstr.substring(2, expPos))); scale += Integer.parseInt(dstr.substring(expPos + 1)) - (expPos - 1) + 1; } else if (dstr.charAt(0) == '0') { // Case 2: Fraction-only number. assert dstr.indexOf('.') == 1; _setToLong(Long.parseLong(dstr.substring(2))); scale += 2 - dstr.length(); } else if (dstr.charAt(dstr.length() - 1) == '0') { // Case 3: Integer-only number. // Note: this path should not normally happen, because integer-only numbers are captured // before the approximate double logic is performed. assert dstr.indexOf('.') == dstr.length() - 2; assert dstr.length() - 2 <= 18; _setToLong(Long.parseLong(dstr.substring(0, dstr.length() - 2))); // no need to adjust scale } else { // Case 4: Number with both a fraction and an integer. int decimalPos = dstr.indexOf('.'); _setToLong(Long.parseLong(dstr.substring(0, decimalPos) + dstr.substring(decimalPos + 1))); scale += decimalPos - dstr.length() + 1; } scale += delta; compact(); explicitExactDouble = true; } /** * Whether this {@link DecimalQuantity_DualStorageBCD} has been explicitly converted to an exact * double. true if backed by a double that was explicitly converted via convertToAccurateDouble; * false otherwise. Used for testing. * * @internal * @deprecated This API is ICU internal only. */ @Deprecated public boolean explicitExactDouble = false; /** * Sets the internal BCD state to represent the value in the given BigDecimal. * * @param n * The value to consume. */ @Override public void setToBigDecimal(BigDecimal n) { setBcdToZero(); flags = 0; if (n.signum() == -1) { flags |= NEGATIVE_FLAG; n = n.negate(); } if (n.signum() != 0) { _setToBigDecimal(n); compact(); } } private void _setToBigDecimal(BigDecimal n) { int fracLength = n.scale(); n = n.scaleByPowerOfTen(fracLength); BigInteger bi = n.toBigInteger(); _setToBigInteger(bi); scale -= fracLength; } /** * Returns a long approximating the internal BCD. A long can only represent the integral part of the * number. * * @param truncateIfOverflow if false and the number does NOT fit, fails with an assertion error. * @return A 64-bit integer representation of the internal BCD. */ public long toLong(boolean truncateIfOverflow) { // NOTE: Call sites should be guarded by fitsInLong(), like this: // if (dq.fitsInLong()) { /* use dq.toLong() */ } else { /* use some fallback */ } // Fallback behavior upon truncateIfOverflow is to truncate at 17 digits. assert(truncateIfOverflow || fitsInLong()); long result = 0L; int upperMagnitude = Math.min(scale + precision, lOptPos) - 1; if (truncateIfOverflow) { upperMagnitude = Math.min(upperMagnitude, 17); } for (int magnitude = upperMagnitude; magnitude >= 0; magnitude--) { result = result * 10 + getDigitPos(magnitude - scale); } if (isNegative()) { result = -result; } return result; } /** * This returns a long representing the fraction digits of the number, as required by PluralRules. * For example, if we represent the number "1.20" (including optional and required digits), then this * function returns "20" if includeTrailingZeros is true or "2" if false. */ public long toFractionLong(boolean includeTrailingZeros) { long result = 0L; int magnitude = -1; int lowerMagnitude = Math.max(scale, rOptPos); if (includeTrailingZeros) { lowerMagnitude = Math.min(lowerMagnitude, rReqPos); } // NOTE: Java has only signed longs, so we check result <= 1e17 instead of 1e18 for (; magnitude >= lowerMagnitude && result <= 1e17; magnitude--) { result = result * 10 + getDigitPos(magnitude - scale); } // Remove trailing zeros; this can happen during integer overflow cases. if (!includeTrailingZeros) { while (result > 0 && (result % 10) == 0) { result /= 10; } } return result; } static final byte[] INT64_BCD = { 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 8 }; /** * Returns whether or not a Long can fully represent the value stored in this DecimalQuantity. */ public boolean fitsInLong() { if (isZero()) { return true; } if (scale < 0) { return false; } int magnitude = getMagnitude(); if (magnitude < 18) { return true; } if (magnitude > 18) { return false; } // Hard case: the magnitude is 10^18. // The largest int64 is: 9,223,372,036,854,775,807 for (int p = 0; p < precision; p++) { byte digit = getDigit(18 - p); if (digit < INT64_BCD[p]) { return true; } else if (digit > INT64_BCD[p]) { return false; } } // Exactly equal to max long plus one. return isNegative(); } /** * Returns a double approximating the internal BCD. The double may not retain all of the information * encoded in the BCD if the BCD represents a number out of range of a double. * * @return A double representation of the internal BCD. */ @Override public double toDouble() { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; if (isNaN()) { return Double.NaN; } else if (isInfinite()) { return isNegative() ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } // TODO: Do like in C++ and use a library function to perform this conversion? // This code is not as hot in Java because .parse() returns a BigDecimal, not a double. long tempLong = 0L; int lostDigits = precision - Math.min(precision, 17); for (int shift = precision - 1; shift >= lostDigits; shift--) { tempLong = tempLong * 10 + getDigitPos(shift); } double result = tempLong; int _scale = scale + lostDigits; if (_scale >= 0) { // 1e22 is the largest exact double. int i = _scale; for (; i >= 22; i -= 22) { result *= 1e22; if (Double.isInfinite(result)) { // Further multiplications will not be productive. i = 0; break; } } result *= DOUBLE_MULTIPLIERS[i]; } else { // 1e22 is the largest exact double. int i = _scale; for (; i <= -22; i += 22) { result /= 1e22; if (result == 0.0) { // Further divisions will not be productive. i = 0; break; } } result /= DOUBLE_MULTIPLIERS[-i]; } if (isNegative()) { result = -result; } return result; } @Override public BigDecimal toBigDecimal() { if (isApproximate) { // Converting to a BigDecimal requires Double.toString(). convertToAccurateDouble(); } return bcdToBigDecimal(); } private static int safeSubtract(int a, int b) { int diff = a - b; if (b < 0 && diff < a) return Integer.MAX_VALUE; if (b > 0 && diff > a) return Integer.MIN_VALUE; return diff; } private static final int SECTION_LOWER_EDGE = -1; private static final int SECTION_UPPER_EDGE = -2; /** Removes all fraction digits. */ public void truncate() { if (scale < 0) { shiftRight(-scale); scale = 0; compact(); } } @Override public void roundToNickel(int magnitude, MathContext mathContext) { roundToMagnitude(magnitude, mathContext, true); } @Override public void roundToMagnitude(int magnitude, MathContext mathContext) { roundToMagnitude(magnitude, mathContext, false); } private void roundToMagnitude(int magnitude, MathContext mathContext, boolean nickel) { // The position in the BCD at which rounding will be performed; digits to the right of position // will be rounded away. int position = safeSubtract(magnitude, scale); // Enforce the number of digits required by the MathContext. int _mcPrecision = mathContext.getPrecision(); if (_mcPrecision > 0 && precision - _mcPrecision > position) { position = precision - _mcPrecision; } // "trailing" = least significant digit to the left of rounding byte trailingDigit = getDigitPos(position); if (position <= 0 && !isApproximate && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { // All digits are to the left of the rounding magnitude. } else if (precision == 0) { // No rounding for zero. } else { // Perform rounding logic. // "leading" = most significant digit to the right of rounding byte leadingDigit = getDigitPos(safeSubtract(position, 1)); // Compute which section of the number we are in. // EDGE means we are at the bottom or top edge, like 1.000 or 1.999 (used by doubles) // LOWER means we are between the bottom edge and the midpoint, like 1.391 // MIDPOINT means we are exactly in the middle, like 1.500 // UPPER means we are between the midpoint and the top edge, like 1.916 int section; if (!isApproximate) { if (nickel && trailingDigit != 2 && trailingDigit != 7) { // Nickel rounding, and not at .02x or .07x if (trailingDigit < 2) { // .00, .01 => down to .00 section = RoundingUtils.SECTION_LOWER; } else if (trailingDigit < 5) { // .03, .04 => up to .05 section = RoundingUtils.SECTION_UPPER; } else if (trailingDigit < 7) { // .05, .06 => down to .05 section = RoundingUtils.SECTION_LOWER; } else { // .08, .09 => up to .10 section = RoundingUtils.SECTION_UPPER; } } else if (leadingDigit < 5) { // Includes nickel rounding .020-.024 and .070-.074 section = RoundingUtils.SECTION_LOWER; } else if (leadingDigit > 5) { // Includes nickel rounding .026-.029 and .076-.079 section = RoundingUtils.SECTION_UPPER; } else { // Includes nickel rounding .025 and .075 section = RoundingUtils.SECTION_MIDPOINT; for (int p = safeSubtract(position, 2); p >= 0; p--) { if (getDigitPos(p) != 0) { section = RoundingUtils.SECTION_UPPER; break; } } } } else { int p = safeSubtract(position, 2); int minP = Math.max(0, precision - 14); if (leadingDigit == 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { section = SECTION_LOWER_EDGE; for (; p >= minP; p--) { if (getDigitPos(p) != 0) { section = RoundingUtils.SECTION_LOWER; break; } } } else if (leadingDigit == 4 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) { section = RoundingUtils.SECTION_MIDPOINT; for (; p >= minP; p--) { if (getDigitPos(p) != 9) { section = RoundingUtils.SECTION_LOWER; break; } } } else if (leadingDigit == 5 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) { section = RoundingUtils.SECTION_MIDPOINT; for (; p >= minP; p--) { if (getDigitPos(p) != 0) { section = RoundingUtils.SECTION_UPPER; break; } } } else if (leadingDigit == 9 && (!nickel || trailingDigit == 4 || trailingDigit == 9)) { section = SECTION_UPPER_EDGE; for (; p >= minP; p--) { if (getDigitPos(p) != 9) { section = RoundingUtils.SECTION_UPPER; break; } } } else if (nickel && trailingDigit != 2 && trailingDigit != 7) { // Nickel rounding, and not at .02x or .07x if (trailingDigit < 2) { // .00, .01 => down to .00 section = RoundingUtils.SECTION_LOWER; } else if (trailingDigit < 5) { // .03, .04 => up to .05 section = RoundingUtils.SECTION_UPPER; } else if (trailingDigit < 7) { // .05, .06 => down to .05 section = RoundingUtils.SECTION_LOWER; } else { // .08, .09 => up to .10 section = RoundingUtils.SECTION_UPPER; } } else if (leadingDigit < 5) { // Includes nickel rounding .020-.024 and .070-.074 section = RoundingUtils.SECTION_LOWER; } else { // Includes nickel rounding .026-.029 and .076-.079 section = RoundingUtils.SECTION_UPPER; } boolean roundsAtMidpoint = RoundingUtils .roundsAtMidpoint(mathContext.getRoundingMode().ordinal()); if (safeSubtract(position, 1) < precision - 14 || (roundsAtMidpoint && section == RoundingUtils.SECTION_MIDPOINT) || (!roundsAtMidpoint && section < 0 /* i.e. at upper or lower edge */)) { // Oops! This means that we have to get the exact representation of the double, // because the zone of uncertainty is along the rounding boundary. convertToAccurateDouble(); roundToMagnitude(magnitude, mathContext, nickel); // start over return; } // Turn off the approximate double flag, since the value is now confirmed to be exact. isApproximate = false; origDouble = 0.0; origDelta = 0; if (position <= 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { // All digits are to the left of the rounding magnitude. return; } // Good to continue rounding. if (section == SECTION_LOWER_EDGE) section = RoundingUtils.SECTION_LOWER; if (section == SECTION_UPPER_EDGE) section = RoundingUtils.SECTION_UPPER; } // Nickel rounding "half even" goes to the nearest whole (away from the 5). boolean isEven = nickel ? (trailingDigit < 2 || trailingDigit > 7 || (trailingDigit == 2 && section != RoundingUtils.SECTION_UPPER) || (trailingDigit == 7 && section == RoundingUtils.SECTION_UPPER)) : (trailingDigit % 2) == 0; boolean roundDown = RoundingUtils.getRoundingDirection(isEven, isNegative(), section, mathContext.getRoundingMode().ordinal(), this); // Perform truncation if (position >= precision) { setBcdToZero(); scale = magnitude; } else { shiftRight(position); } if (nickel) { if (trailingDigit < 5 && roundDown) { setDigitPos(0, (byte) 0); compact(); return; } else if (trailingDigit >= 5 && !roundDown) { setDigitPos(0, (byte) 9); trailingDigit = 9; // do not return: use the bubbling logic below } else { setDigitPos(0, (byte) 5); // compact not necessary: digit at position 0 is nonzero return; } } // Bubble the result to the higher digits if (!roundDown) { if (trailingDigit == 9) { int bubblePos = 0; // Note: in the long implementation, the most digits BCD can have at this point is // 15, so bubblePos <= 15 and getDigitPos(bubblePos) is safe. for (; getDigitPos(bubblePos) == 9; bubblePos++) { } shiftRight(bubblePos); // shift off the trailing 9s } byte digit0 = getDigitPos(0); assert digit0 != 9; setDigitPos(0, (byte) (digit0 + 1)); precision += 1; // in case an extra digit got added } compact(); } } @Override public void roundToInfinity() { if (isApproximate) { convertToAccurateDouble(); } } /** * Appends a digit, optionally with one or more leading zeros, to the end of the value represented by * this DecimalQuantity. * * <p> * The primary use of this method is to construct numbers during a parsing loop. It allows parsing to * take advantage of the digit list infrastructure primarily designed for formatting. * * @param value * The digit to append. * @param leadingZeros * The number of zeros to append before the digit. For example, if the value in this * instance starts as 12.3, and you append a 4 with 1 leading zero, the value becomes * 12.304. * @param appendAsInteger * If true, increase the magnitude of existing digits to make room for the new digit. If * false, append to the end like a fraction digit. If true, there must not be any fraction * digits already in the number. * @internal * @deprecated This API is ICU internal only. */ @Deprecated public void appendDigit(byte value, int leadingZeros, boolean appendAsInteger) { assert leadingZeros >= 0; // Zero requires special handling to maintain the invariant that the least-significant digit // in the BCD is nonzero. if (value == 0) { if (appendAsInteger && precision != 0) { scale += leadingZeros + 1; } return; } // Deal with trailing zeros if (scale > 0) { leadingZeros += scale; if (appendAsInteger) { scale = 0; } } // Append digit shiftLeft(leadingZeros + 1); setDigitPos(0, value); // Fix scale if in integer mode if (appendAsInteger) { scale += leadingZeros + 1; } } @Override public String toPlainString() { // NOTE: This logic is duplicated between here and DecimalQuantity_SimpleStorage. StringBuilder sb = new StringBuilder(); if (isNegative()) { sb.append('-'); } if (precision == 0 || getMagnitude() < 0) { sb.append('0'); } for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) { sb.append((char) ('0' + getDigit(m))); if (m == 0) sb.append('.'); } return sb.toString(); } public String toScientificString() { StringBuilder sb = new StringBuilder(); toScientificString(sb); return sb.toString(); } public void toScientificString(StringBuilder result) { assert(!isApproximate); if (isNegative()) { result.append('-'); } if (precision == 0) { result.append("0E+0"); return; } // NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from // rOptPos (aka -maxFrac) due to overflow. int upperPos = Math.min(precision + scale, lOptPos) - scale - 1; int lowerPos = Math.max(scale, rOptPos) - scale; int p = upperPos; result.append((char) ('0' + getDigitPos(p))); if ((--p) >= lowerPos) { result.append('.'); for (; p >= lowerPos; p--) { result.append((char) ('0' + getDigitPos(p))); } } result.append('E'); int _scale = upperPos + scale; if (_scale == Integer.MIN_VALUE) { result.append("-2147483648"); return; } else if (_scale < 0) { _scale *= -1; result.append('-'); } else { result.append('+'); } if (_scale == 0) { result.append('0'); } int insertIndex = result.length(); while (_scale > 0) { int quot = _scale / 10; int rem = _scale % 10; result.insert(insertIndex, (char) ('0' + rem)); _scale = quot; } } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } if (!(other instanceof DecimalQuantity_AbstractBCD)) { return false; } DecimalQuantity_AbstractBCD _other = (DecimalQuantity_AbstractBCD) other; boolean basicEquals = scale == _other.scale && precision == _other.precision && flags == _other.flags && lOptPos == _other.lOptPos && lReqPos == _other.lReqPos && rReqPos == _other.rReqPos && rOptPos == _other.rOptPos && isApproximate == _other.isApproximate; if (!basicEquals) { return false; } if (precision == 0) { return true; } else if (isApproximate) { return origDouble == _other.origDouble && origDelta == _other.origDelta; } else { for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) { if (getDigit(m) != _other.getDigit(m)) { return false; } } return true; } } /** * Returns a single digit from the BCD list. No internal state is changed by calling this method. * * @param position * The position of the digit to pop, counted in BCD units from the least significant * digit. If outside the range supported by the implementation, zero is returned. * @return The digit at the specified location. */ protected abstract byte getDigitPos(int position); /** * Sets the digit in the BCD list. This method only sets the digit; it is the caller's responsibility * to call {@link #compact} after setting the digit. * * @param position * The position of the digit to pop, counted in BCD units from the least significant * digit. If outside the range supported by the implementation, an AssertionError is * thrown. * @param value * The digit to set at the specified location. */ protected abstract void setDigitPos(int position, byte value); /** * Adds zeros to the end of the BCD list. This will result in an invalid BCD representation; it is * the caller's responsibility to do further manipulation and then call {@link #compact}. * * @param numDigits * The number of zeros to add. */ protected abstract void shiftLeft(int numDigits); /** * Removes digits from the end of the BCD list. This may result in an invalid BCD representation; it * is the caller's responsibility to follow-up with a call to {@link #compact}. * * @param numDigits * The number of digits to remove. */ protected abstract void shiftRight(int numDigits); /** * Sets the internal representation to zero. Clears any values stored in scale, precision, hasDouble, * origDouble, origDelta, and BCD data. */ protected abstract void setBcdToZero(); /** * Sets the internal BCD state to represent the value in the given int. The int is guaranteed to be * either positive. The internal state is guaranteed to be empty when this method is called. * * @param n * The value to consume. */ protected abstract void readIntToBcd(int input); /** * Sets the internal BCD state to represent the value in the given long. The long is guaranteed to be * either positive. The internal state is guaranteed to be empty when this method is called. * * @param n * The value to consume. */ protected abstract void readLongToBcd(long input); /** * Sets the internal BCD state to represent the value in the given BigInteger. The BigInteger is * guaranteed to be positive, and it is guaranteed to be larger than Long.MAX_VALUE. The internal * state is guaranteed to be empty when this method is called. * * @param n * The value to consume. */ protected abstract void readBigIntegerToBcd(BigInteger input); /** * Returns a BigDecimal encoding the internal BCD value. * * @return A BigDecimal representation of the internal BCD. */ protected abstract BigDecimal bcdToBigDecimal(); protected abstract void copyBcdFrom(DecimalQuantity _other); /** * Removes trailing zeros from the BCD (adjusting the scale as required) and then computes the * precision. The precision is the number of digits in the number up through the greatest nonzero * digit. * * <p> * This method must always be called when bcd changes in order for assumptions to be correct in * methods like {@link #fractionCount()}. */ protected abstract void compact(); }
./CrossVul/dataset_final_sorted/CWE-190/java/good_434_3
crossvul-java_data_bad_434_3
// © 2017 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License package com.ibm.icu.impl.number; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.text.FieldPosition; import com.ibm.icu.impl.StandardPlural; import com.ibm.icu.impl.Utility; import com.ibm.icu.text.PluralRules; import com.ibm.icu.text.PluralRules.Operand; import com.ibm.icu.text.UFieldPosition; /** * Represents numbers and digit display properties using Binary Coded Decimal (BCD). * * @implements {@link DecimalQuantity} */ public abstract class DecimalQuantity_AbstractBCD implements DecimalQuantity { /** * The power of ten corresponding to the least significant digit in the BCD. For example, if this * object represents the number "3.14", the BCD will be "0x314" and the scale will be -2. * * <p> * Note that in {@link java.math.BigDecimal}, the scale is defined differently: the number of digits * after the decimal place, which is the negative of our definition of scale. */ protected int scale; /** * The number of digits in the BCD. For example, "1007" has BCD "0x1007" and precision 4. A long * cannot represent precisions greater than 16. * * <p> * This value must be re-calculated whenever the value in bcd changes by using * {@link #computePrecisionAndCompact()}. */ protected int precision; /** * A bitmask of properties relating to the number represented by this object. * * @see #NEGATIVE_FLAG * @see #INFINITY_FLAG * @see #NAN_FLAG */ protected byte flags; protected static final int NEGATIVE_FLAG = 1; protected static final int INFINITY_FLAG = 2; protected static final int NAN_FLAG = 4; // The following three fields relate to the double-to-ascii fast path algorithm. // When a double is given to DecimalQuantityBCD, it is converted to using a fast algorithm. The // fast algorithm guarantees correctness to only the first ~12 digits of the double. The process // of rounding the number ensures that the converted digits are correct, falling back to a slow- // path algorithm if required. Therefore, if a DecimalQuantity is constructed from a double, it // is *required* that roundToMagnitude(), roundToIncrement(), or roundToInfinity() is called. If // you don't round, assertions will fail in certain other methods if you try calling them. /** * The original number provided by the user and which is represented in BCD. Used when we need to * re-compute the BCD for an exact double representation. */ protected double origDouble; /** * The change in magnitude relative to the original double. Used when we need to re-compute the BCD * for an exact double representation. */ protected int origDelta; /** * Whether the value in the BCD comes from the double fast path without having been rounded to ensure * correctness */ protected boolean isApproximate; // Four positions: left optional '(', left required '[', right required ']', right optional ')'. // These four positions determine which digits are displayed in the output string. They do NOT // affect rounding. These positions are internal-only and can be specified only by the public // endpoints like setFractionLength, setIntegerLength, and setSignificantDigits, among others. // // * Digits between lReqPos and rReqPos are in the "required zone" and are always displayed. // * Digits between lOptPos and rOptPos but outside the required zone are in the "optional zone" // and are displayed unless they are trailing off the left or right edge of the number and // have a numerical value of zero. In order to be "trailing", the digits need to be beyond // the decimal point in their respective directions. // * Digits outside of the "optional zone" are never displayed. // // See the table below for illustrative examples. // // +---------+---------+---------+---------+------------+------------------------+--------------+ // | lOptPos | lReqPos | rReqPos | rOptPos | number | positions | en-US string | // +---------+---------+---------+---------+------------+------------------------+--------------+ // | 5 | 2 | -1 | -5 | 1234.567 | ( 12[34.5]67 ) | 1,234.567 | // | 3 | 2 | -1 | -5 | 1234.567 | 1(2[34.5]67 ) | 234.567 | // | 3 | 2 | -1 | -2 | 1234.567 | 1(2[34.5]6)7 | 234.56 | // | 6 | 4 | 2 | -5 | 123456789. | 123(45[67]89. ) | 456,789. | // | 6 | 4 | 2 | 1 | 123456789. | 123(45[67]8)9. | 456,780. | // | -1 | -1 | -3 | -4 | 0.123456 | 0.1([23]4)56 | .0234 | // | 6 | 4 | -2 | -2 | 12.3 | ( [ 12.3 ]) | 0012.30 | // +---------+---------+---------+---------+------------+------------------------+--------------+ // protected int lOptPos = Integer.MAX_VALUE; protected int lReqPos = 0; protected int rReqPos = 0; protected int rOptPos = Integer.MIN_VALUE; @Override public void copyFrom(DecimalQuantity _other) { copyBcdFrom(_other); DecimalQuantity_AbstractBCD other = (DecimalQuantity_AbstractBCD) _other; lOptPos = other.lOptPos; lReqPos = other.lReqPos; rReqPos = other.rReqPos; rOptPos = other.rOptPos; scale = other.scale; precision = other.precision; flags = other.flags; origDouble = other.origDouble; origDelta = other.origDelta; isApproximate = other.isApproximate; } public DecimalQuantity_AbstractBCD clear() { lOptPos = Integer.MAX_VALUE; lReqPos = 0; rReqPos = 0; rOptPos = Integer.MIN_VALUE; flags = 0; setBcdToZero(); // sets scale, precision, hasDouble, origDouble, origDelta, and BCD data return this; } @Override public void setIntegerLength(int minInt, int maxInt) { // Validation should happen outside of DecimalQuantity, e.g., in the Rounder class. assert minInt >= 0; assert maxInt >= minInt; // Special behavior: do not set minInt to be less than what is already set. // This is so significant digits rounding can set the integer length. if (minInt < lReqPos) { minInt = lReqPos; } // Save values into internal state // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE lOptPos = maxInt; lReqPos = minInt; } @Override public void setFractionLength(int minFrac, int maxFrac) { // Validation should happen outside of DecimalQuantity, e.g., in the Rounder class. assert minFrac >= 0; assert maxFrac >= minFrac; // Save values into internal state // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE rReqPos = -minFrac; rOptPos = -maxFrac; } @Override public long getPositionFingerprint() { long fingerprint = 0; fingerprint ^= lOptPos; fingerprint ^= (lReqPos << 16); fingerprint ^= ((long) rReqPos << 32); fingerprint ^= ((long) rOptPos << 48); return fingerprint; } @Override public void roundToIncrement(BigDecimal roundingIncrement, MathContext mathContext) { // TODO(13701): Avoid this check on every call to roundToIncrement(). BigDecimal stripped = roundingIncrement.stripTrailingZeros(); if (stripped.unscaledValue().compareTo(BigInteger.valueOf(5)) == 0) { roundToNickel(-stripped.scale(), mathContext); return; } BigDecimal temp = toBigDecimal(); temp = temp.divide(roundingIncrement, 0, mathContext.getRoundingMode()) .multiply(roundingIncrement).round(mathContext); if (temp.signum() == 0) { setBcdToZero(); // keeps negative flag for -0.0 } else { setToBigDecimal(temp); } } @Override public void multiplyBy(BigDecimal multiplicand) { if (isInfinite() || isZero() || isNaN()) { return; } BigDecimal temp = toBigDecimal(); temp = temp.multiply(multiplicand); setToBigDecimal(temp); } @Override public void negate() { flags ^= NEGATIVE_FLAG; } @Override public int getMagnitude() throws ArithmeticException { if (precision == 0) { throw new ArithmeticException("Magnitude is not well-defined for zero"); } else { return scale + precision - 1; } } @Override public void adjustMagnitude(int delta) { if (precision != 0) { scale = Utility.addExact(scale, delta); origDelta = Utility.addExact(origDelta, delta); } } @Override public StandardPlural getStandardPlural(PluralRules rules) { if (rules == null) { // Fail gracefully if the user didn't provide a PluralRules return StandardPlural.OTHER; } else { @SuppressWarnings("deprecation") String ruleString = rules.select(this); return StandardPlural.orOtherFromString(ruleString); } } @Override public double getPluralOperand(Operand operand) { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; switch (operand) { case i: // Invert the negative sign if necessary return isNegative() ? -toLong(true) : toLong(true); case f: return toFractionLong(true); case t: return toFractionLong(false); case v: return fractionCount(); case w: return fractionCountWithoutTrailingZeros(); default: return Math.abs(toDouble()); } } @Override public void populateUFieldPosition(FieldPosition fp) { if (fp instanceof UFieldPosition) { ((UFieldPosition) fp).setFractionDigits((int) getPluralOperand(Operand.v), (long) getPluralOperand(Operand.f)); } } @Override public int getUpperDisplayMagnitude() { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; int magnitude = scale + precision; int result = (lReqPos > magnitude) ? lReqPos : (lOptPos < magnitude) ? lOptPos : magnitude; return result - 1; } @Override public int getLowerDisplayMagnitude() { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; int magnitude = scale; int result = (rReqPos < magnitude) ? rReqPos : (rOptPos > magnitude) ? rOptPos : magnitude; return result; } @Override public byte getDigit(int magnitude) { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; return getDigitPos(magnitude - scale); } private int fractionCount() { return -getLowerDisplayMagnitude(); } private int fractionCountWithoutTrailingZeros() { return Math.max(-scale, 0); } @Override public boolean isNegative() { return (flags & NEGATIVE_FLAG) != 0; } @Override public int signum() { return isNegative() ? -1 : isZero() ? 0 : 1; } @Override public boolean isInfinite() { return (flags & INFINITY_FLAG) != 0; } @Override public boolean isNaN() { return (flags & NAN_FLAG) != 0; } @Override public boolean isZero() { return precision == 0; } public void setToInt(int n) { setBcdToZero(); flags = 0; if (n < 0) { flags |= NEGATIVE_FLAG; n = -n; } if (n != 0) { _setToInt(n); compact(); } } private void _setToInt(int n) { if (n == Integer.MIN_VALUE) { readLongToBcd(-(long) n); } else { readIntToBcd(n); } } public void setToLong(long n) { setBcdToZero(); flags = 0; if (n < 0) { flags |= NEGATIVE_FLAG; n = -n; } if (n != 0) { _setToLong(n); compact(); } } private void _setToLong(long n) { if (n == Long.MIN_VALUE) { readBigIntegerToBcd(BigInteger.valueOf(n).negate()); } else if (n <= Integer.MAX_VALUE) { readIntToBcd((int) n); } else { readLongToBcd(n); } } public void setToBigInteger(BigInteger n) { setBcdToZero(); flags = 0; if (n.signum() == -1) { flags |= NEGATIVE_FLAG; n = n.negate(); } if (n.signum() != 0) { _setToBigInteger(n); compact(); } } private void _setToBigInteger(BigInteger n) { if (n.bitLength() < 32) { readIntToBcd(n.intValue()); } else if (n.bitLength() < 64) { readLongToBcd(n.longValue()); } else { readBigIntegerToBcd(n); } } /** * Sets the internal BCD state to represent the value in the given double. * * @param n * The value to consume. */ public void setToDouble(double n) { setBcdToZero(); flags = 0; // Double.compare() handles +0.0 vs -0.0 if (Double.compare(n, 0.0) < 0) { flags |= NEGATIVE_FLAG; n = -n; } if (Double.isNaN(n)) { flags |= NAN_FLAG; } else if (Double.isInfinite(n)) { flags |= INFINITY_FLAG; } else if (n != 0) { _setToDoubleFast(n); compact(); } } private static final double[] DOUBLE_MULTIPLIERS = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21 }; /** * Uses double multiplication and division to get the number into integer space before converting to * digits. Since double arithmetic is inexact, the resulting digits may not be accurate. */ private void _setToDoubleFast(double n) { isApproximate = true; origDouble = n; origDelta = 0; // NOTE: Unlike ICU4C, doubles are always IEEE 754 doubles. long ieeeBits = Double.doubleToLongBits(n); int exponent = (int) ((ieeeBits & 0x7ff0000000000000L) >> 52) - 0x3ff; // Not all integers can be represented exactly for exponent > 52 if (exponent <= 52 && (long) n == n) { _setToLong((long) n); return; } // 3.3219... is log2(10) int fracLength = (int) ((52 - exponent) / 3.32192809489); if (fracLength >= 0) { int i = fracLength; // 1e22 is the largest exact double. for (; i >= 22; i -= 22) n *= 1e22; n *= DOUBLE_MULTIPLIERS[i]; } else { int i = fracLength; // 1e22 is the largest exact double. for (; i <= -22; i += 22) n /= 1e22; n /= DOUBLE_MULTIPLIERS[-i]; } long result = Math.round(n); if (result != 0) { _setToLong(result); scale -= fracLength; } } /** * Uses Double.toString() to obtain an exact accurate representation of the double, overwriting it * into the BCD. This method can be called at any point after {@link #_setToDoubleFast} while * {@link #isApproximate} is still true. */ private void convertToAccurateDouble() { double n = origDouble; assert n != 0; int delta = origDelta; setBcdToZero(); // Call the slow oracle function (Double.toString in Java, sprintf in C++). String dstr = Double.toString(n); if (dstr.indexOf('E') != -1) { // Case 1: Exponential notation. assert dstr.indexOf('.') == 1; int expPos = dstr.indexOf('E'); _setToLong(Long.parseLong(dstr.charAt(0) + dstr.substring(2, expPos))); scale += Integer.parseInt(dstr.substring(expPos + 1)) - (expPos - 1) + 1; } else if (dstr.charAt(0) == '0') { // Case 2: Fraction-only number. assert dstr.indexOf('.') == 1; _setToLong(Long.parseLong(dstr.substring(2))); scale += 2 - dstr.length(); } else if (dstr.charAt(dstr.length() - 1) == '0') { // Case 3: Integer-only number. // Note: this path should not normally happen, because integer-only numbers are captured // before the approximate double logic is performed. assert dstr.indexOf('.') == dstr.length() - 2; assert dstr.length() - 2 <= 18; _setToLong(Long.parseLong(dstr.substring(0, dstr.length() - 2))); // no need to adjust scale } else { // Case 4: Number with both a fraction and an integer. int decimalPos = dstr.indexOf('.'); _setToLong(Long.parseLong(dstr.substring(0, decimalPos) + dstr.substring(decimalPos + 1))); scale += decimalPos - dstr.length() + 1; } scale += delta; compact(); explicitExactDouble = true; } /** * Whether this {@link DecimalQuantity_DualStorageBCD} has been explicitly converted to an exact * double. true if backed by a double that was explicitly converted via convertToAccurateDouble; * false otherwise. Used for testing. * * @internal * @deprecated This API is ICU internal only. */ @Deprecated public boolean explicitExactDouble = false; /** * Sets the internal BCD state to represent the value in the given BigDecimal. * * @param n * The value to consume. */ @Override public void setToBigDecimal(BigDecimal n) { setBcdToZero(); flags = 0; if (n.signum() == -1) { flags |= NEGATIVE_FLAG; n = n.negate(); } if (n.signum() != 0) { _setToBigDecimal(n); compact(); } } private void _setToBigDecimal(BigDecimal n) { int fracLength = n.scale(); n = n.scaleByPowerOfTen(fracLength); BigInteger bi = n.toBigInteger(); _setToBigInteger(bi); scale -= fracLength; } /** * Returns a long approximating the internal BCD. A long can only represent the integral part of the * number. * * @param truncateIfOverflow if false and the number does NOT fit, fails with an assertion error. * @return A 64-bit integer representation of the internal BCD. */ public long toLong(boolean truncateIfOverflow) { // NOTE: Call sites should be guarded by fitsInLong(), like this: // if (dq.fitsInLong()) { /* use dq.toLong() */ } else { /* use some fallback */ } // Fallback behavior upon truncateIfOverflow is to truncate at 17 digits. assert(truncateIfOverflow || fitsInLong()); long result = 0L; int upperMagnitude = Math.min(scale + precision, lOptPos) - 1; if (truncateIfOverflow) { upperMagnitude = Math.min(upperMagnitude, 17); } for (int magnitude = upperMagnitude; magnitude >= 0; magnitude--) { result = result * 10 + getDigitPos(magnitude - scale); } if (isNegative()) { result = -result; } return result; } /** * This returns a long representing the fraction digits of the number, as required by PluralRules. * For example, if we represent the number "1.20" (including optional and required digits), then this * function returns "20" if includeTrailingZeros is true or "2" if false. */ public long toFractionLong(boolean includeTrailingZeros) { long result = 0L; int magnitude = -1; int lowerMagnitude = Math.max(scale, rOptPos); if (includeTrailingZeros) { lowerMagnitude = Math.min(lowerMagnitude, rReqPos); } // NOTE: Java has only signed longs, so we check result <= 1e17 instead of 1e18 for (; magnitude >= lowerMagnitude && result <= 1e17; magnitude--) { result = result * 10 + getDigitPos(magnitude - scale); } // Remove trailing zeros; this can happen during integer overflow cases. if (!includeTrailingZeros) { while (result > 0 && (result % 10) == 0) { result /= 10; } } return result; } static final byte[] INT64_BCD = { 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 8 }; /** * Returns whether or not a Long can fully represent the value stored in this DecimalQuantity. */ public boolean fitsInLong() { if (isZero()) { return true; } if (scale < 0) { return false; } int magnitude = getMagnitude(); if (magnitude < 18) { return true; } if (magnitude > 18) { return false; } // Hard case: the magnitude is 10^18. // The largest int64 is: 9,223,372,036,854,775,807 for (int p = 0; p < precision; p++) { byte digit = getDigit(18 - p); if (digit < INT64_BCD[p]) { return true; } else if (digit > INT64_BCD[p]) { return false; } } // Exactly equal to max long plus one. return isNegative(); } /** * Returns a double approximating the internal BCD. The double may not retain all of the information * encoded in the BCD if the BCD represents a number out of range of a double. * * @return A double representation of the internal BCD. */ @Override public double toDouble() { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. assert !isApproximate; if (isNaN()) { return Double.NaN; } else if (isInfinite()) { return isNegative() ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY; } // TODO: Do like in C++ and use a library function to perform this conversion? // This code is not as hot in Java because .parse() returns a BigDecimal, not a double. long tempLong = 0L; int lostDigits = precision - Math.min(precision, 17); for (int shift = precision - 1; shift >= lostDigits; shift--) { tempLong = tempLong * 10 + getDigitPos(shift); } double result = tempLong; int _scale = scale + lostDigits; if (_scale >= 0) { // 1e22 is the largest exact double. int i = _scale; for (; i >= 22; i -= 22) { result *= 1e22; if (Double.isInfinite(result)) { // Further multiplications will not be productive. i = 0; break; } } result *= DOUBLE_MULTIPLIERS[i]; } else { // 1e22 is the largest exact double. int i = _scale; for (; i <= -22; i += 22) { result /= 1e22; if (result == 0.0) { // Further divisions will not be productive. i = 0; break; } } result /= DOUBLE_MULTIPLIERS[-i]; } if (isNegative()) { result = -result; } return result; } @Override public BigDecimal toBigDecimal() { if (isApproximate) { // Converting to a BigDecimal requires Double.toString(). convertToAccurateDouble(); } return bcdToBigDecimal(); } private static int safeSubtract(int a, int b) { int diff = a - b; if (b < 0 && diff < a) return Integer.MAX_VALUE; if (b > 0 && diff > a) return Integer.MIN_VALUE; return diff; } private static final int SECTION_LOWER_EDGE = -1; private static final int SECTION_UPPER_EDGE = -2; /** Removes all fraction digits. */ public void truncate() { if (scale < 0) { shiftRight(-scale); scale = 0; compact(); } } @Override public void roundToNickel(int magnitude, MathContext mathContext) { roundToMagnitude(magnitude, mathContext, true); } @Override public void roundToMagnitude(int magnitude, MathContext mathContext) { roundToMagnitude(magnitude, mathContext, false); } private void roundToMagnitude(int magnitude, MathContext mathContext, boolean nickel) { // The position in the BCD at which rounding will be performed; digits to the right of position // will be rounded away. int position = safeSubtract(magnitude, scale); // Enforce the number of digits required by the MathContext. int _mcPrecision = mathContext.getPrecision(); if (_mcPrecision > 0 && precision - _mcPrecision > position) { position = precision - _mcPrecision; } // "trailing" = least significant digit to the left of rounding byte trailingDigit = getDigitPos(position); if (position <= 0 && !isApproximate && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { // All digits are to the left of the rounding magnitude. } else if (precision == 0) { // No rounding for zero. } else { // Perform rounding logic. // "leading" = most significant digit to the right of rounding byte leadingDigit = getDigitPos(safeSubtract(position, 1)); // Compute which section of the number we are in. // EDGE means we are at the bottom or top edge, like 1.000 or 1.999 (used by doubles) // LOWER means we are between the bottom edge and the midpoint, like 1.391 // MIDPOINT means we are exactly in the middle, like 1.500 // UPPER means we are between the midpoint and the top edge, like 1.916 int section; if (!isApproximate) { if (nickel && trailingDigit != 2 && trailingDigit != 7) { // Nickel rounding, and not at .02x or .07x if (trailingDigit < 2) { // .00, .01 => down to .00 section = RoundingUtils.SECTION_LOWER; } else if (trailingDigit < 5) { // .03, .04 => up to .05 section = RoundingUtils.SECTION_UPPER; } else if (trailingDigit < 7) { // .05, .06 => down to .05 section = RoundingUtils.SECTION_LOWER; } else { // .08, .09 => up to .10 section = RoundingUtils.SECTION_UPPER; } } else if (leadingDigit < 5) { // Includes nickel rounding .020-.024 and .070-.074 section = RoundingUtils.SECTION_LOWER; } else if (leadingDigit > 5) { // Includes nickel rounding .026-.029 and .076-.079 section = RoundingUtils.SECTION_UPPER; } else { // Includes nickel rounding .025 and .075 section = RoundingUtils.SECTION_MIDPOINT; for (int p = safeSubtract(position, 2); p >= 0; p--) { if (getDigitPos(p) != 0) { section = RoundingUtils.SECTION_UPPER; break; } } } } else { int p = safeSubtract(position, 2); int minP = Math.max(0, precision - 14); if (leadingDigit == 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { section = SECTION_LOWER_EDGE; for (; p >= minP; p--) { if (getDigitPos(p) != 0) { section = RoundingUtils.SECTION_LOWER; break; } } } else if (leadingDigit == 4 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) { section = RoundingUtils.SECTION_MIDPOINT; for (; p >= minP; p--) { if (getDigitPos(p) != 9) { section = RoundingUtils.SECTION_LOWER; break; } } } else if (leadingDigit == 5 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) { section = RoundingUtils.SECTION_MIDPOINT; for (; p >= minP; p--) { if (getDigitPos(p) != 0) { section = RoundingUtils.SECTION_UPPER; break; } } } else if (leadingDigit == 9 && (!nickel || trailingDigit == 4 || trailingDigit == 9)) { section = SECTION_UPPER_EDGE; for (; p >= minP; p--) { if (getDigitPos(p) != 9) { section = RoundingUtils.SECTION_UPPER; break; } } } else if (nickel && trailingDigit != 2 && trailingDigit != 7) { // Nickel rounding, and not at .02x or .07x if (trailingDigit < 2) { // .00, .01 => down to .00 section = RoundingUtils.SECTION_LOWER; } else if (trailingDigit < 5) { // .03, .04 => up to .05 section = RoundingUtils.SECTION_UPPER; } else if (trailingDigit < 7) { // .05, .06 => down to .05 section = RoundingUtils.SECTION_LOWER; } else { // .08, .09 => up to .10 section = RoundingUtils.SECTION_UPPER; } } else if (leadingDigit < 5) { // Includes nickel rounding .020-.024 and .070-.074 section = RoundingUtils.SECTION_LOWER; } else { // Includes nickel rounding .026-.029 and .076-.079 section = RoundingUtils.SECTION_UPPER; } boolean roundsAtMidpoint = RoundingUtils .roundsAtMidpoint(mathContext.getRoundingMode().ordinal()); if (safeSubtract(position, 1) < precision - 14 || (roundsAtMidpoint && section == RoundingUtils.SECTION_MIDPOINT) || (!roundsAtMidpoint && section < 0 /* i.e. at upper or lower edge */)) { // Oops! This means that we have to get the exact representation of the double, // because the zone of uncertainty is along the rounding boundary. convertToAccurateDouble(); roundToMagnitude(magnitude, mathContext, nickel); // start over return; } // Turn off the approximate double flag, since the value is now confirmed to be exact. isApproximate = false; origDouble = 0.0; origDelta = 0; if (position <= 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { // All digits are to the left of the rounding magnitude. return; } // Good to continue rounding. if (section == SECTION_LOWER_EDGE) section = RoundingUtils.SECTION_LOWER; if (section == SECTION_UPPER_EDGE) section = RoundingUtils.SECTION_UPPER; } // Nickel rounding "half even" goes to the nearest whole (away from the 5). boolean isEven = nickel ? (trailingDigit < 2 || trailingDigit > 7 || (trailingDigit == 2 && section != RoundingUtils.SECTION_UPPER) || (trailingDigit == 7 && section == RoundingUtils.SECTION_UPPER)) : (trailingDigit % 2) == 0; boolean roundDown = RoundingUtils.getRoundingDirection(isEven, isNegative(), section, mathContext.getRoundingMode().ordinal(), this); // Perform truncation if (position >= precision) { setBcdToZero(); scale = magnitude; } else { shiftRight(position); } if (nickel) { if (trailingDigit < 5 && roundDown) { setDigitPos(0, (byte) 0); compact(); return; } else if (trailingDigit >= 5 && !roundDown) { setDigitPos(0, (byte) 9); trailingDigit = 9; // do not return: use the bubbling logic below } else { setDigitPos(0, (byte) 5); // compact not necessary: digit at position 0 is nonzero return; } } // Bubble the result to the higher digits if (!roundDown) { if (trailingDigit == 9) { int bubblePos = 0; // Note: in the long implementation, the most digits BCD can have at this point is // 15, so bubblePos <= 15 and getDigitPos(bubblePos) is safe. for (; getDigitPos(bubblePos) == 9; bubblePos++) { } shiftRight(bubblePos); // shift off the trailing 9s } byte digit0 = getDigitPos(0); assert digit0 != 9; setDigitPos(0, (byte) (digit0 + 1)); precision += 1; // in case an extra digit got added } compact(); } } @Override public void roundToInfinity() { if (isApproximate) { convertToAccurateDouble(); } } /** * Appends a digit, optionally with one or more leading zeros, to the end of the value represented by * this DecimalQuantity. * * <p> * The primary use of this method is to construct numbers during a parsing loop. It allows parsing to * take advantage of the digit list infrastructure primarily designed for formatting. * * @param value * The digit to append. * @param leadingZeros * The number of zeros to append before the digit. For example, if the value in this * instance starts as 12.3, and you append a 4 with 1 leading zero, the value becomes * 12.304. * @param appendAsInteger * If true, increase the magnitude of existing digits to make room for the new digit. If * false, append to the end like a fraction digit. If true, there must not be any fraction * digits already in the number. * @internal * @deprecated This API is ICU internal only. */ @Deprecated public void appendDigit(byte value, int leadingZeros, boolean appendAsInteger) { assert leadingZeros >= 0; // Zero requires special handling to maintain the invariant that the least-significant digit // in the BCD is nonzero. if (value == 0) { if (appendAsInteger && precision != 0) { scale += leadingZeros + 1; } return; } // Deal with trailing zeros if (scale > 0) { leadingZeros += scale; if (appendAsInteger) { scale = 0; } } // Append digit shiftLeft(leadingZeros + 1); setDigitPos(0, value); // Fix scale if in integer mode if (appendAsInteger) { scale += leadingZeros + 1; } } @Override public String toPlainString() { // NOTE: This logic is duplicated between here and DecimalQuantity_SimpleStorage. StringBuilder sb = new StringBuilder(); if (isNegative()) { sb.append('-'); } if (precision == 0 || getMagnitude() < 0) { sb.append('0'); } for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) { sb.append((char) ('0' + getDigit(m))); if (m == 0) sb.append('.'); } return sb.toString(); } public String toScientificString() { StringBuilder sb = new StringBuilder(); toScientificString(sb); return sb.toString(); } public void toScientificString(StringBuilder result) { assert(!isApproximate); if (isNegative()) { result.append('-'); } if (precision == 0) { result.append("0E+0"); return; } // NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from // rOptPos (aka -maxFrac) due to overflow. int upperPos = Math.min(precision + scale, lOptPos) - scale - 1; int lowerPos = Math.max(scale, rOptPos) - scale; int p = upperPos; result.append((char) ('0' + getDigitPos(p))); if ((--p) >= lowerPos) { result.append('.'); for (; p >= lowerPos; p--) { result.append((char) ('0' + getDigitPos(p))); } } result.append('E'); int _scale = upperPos + scale; if (_scale < 0) { _scale *= -1; result.append('-'); } else { result.append('+'); } if (_scale == 0) { result.append('0'); } int insertIndex = result.length(); while (_scale > 0) { int quot = _scale / 10; int rem = _scale % 10; result.insert(insertIndex, (char) ('0' + rem)); _scale = quot; } } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null) { return false; } if (!(other instanceof DecimalQuantity_AbstractBCD)) { return false; } DecimalQuantity_AbstractBCD _other = (DecimalQuantity_AbstractBCD) other; boolean basicEquals = scale == _other.scale && precision == _other.precision && flags == _other.flags && lOptPos == _other.lOptPos && lReqPos == _other.lReqPos && rReqPos == _other.rReqPos && rOptPos == _other.rOptPos && isApproximate == _other.isApproximate; if (!basicEquals) { return false; } if (precision == 0) { return true; } else if (isApproximate) { return origDouble == _other.origDouble && origDelta == _other.origDelta; } else { for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) { if (getDigit(m) != _other.getDigit(m)) { return false; } } return true; } } /** * Returns a single digit from the BCD list. No internal state is changed by calling this method. * * @param position * The position of the digit to pop, counted in BCD units from the least significant * digit. If outside the range supported by the implementation, zero is returned. * @return The digit at the specified location. */ protected abstract byte getDigitPos(int position); /** * Sets the digit in the BCD list. This method only sets the digit; it is the caller's responsibility * to call {@link #compact} after setting the digit. * * @param position * The position of the digit to pop, counted in BCD units from the least significant * digit. If outside the range supported by the implementation, an AssertionError is * thrown. * @param value * The digit to set at the specified location. */ protected abstract void setDigitPos(int position, byte value); /** * Adds zeros to the end of the BCD list. This will result in an invalid BCD representation; it is * the caller's responsibility to do further manipulation and then call {@link #compact}. * * @param numDigits * The number of zeros to add. */ protected abstract void shiftLeft(int numDigits); /** * Removes digits from the end of the BCD list. This may result in an invalid BCD representation; it * is the caller's responsibility to follow-up with a call to {@link #compact}. * * @param numDigits * The number of digits to remove. */ protected abstract void shiftRight(int numDigits); /** * Sets the internal representation to zero. Clears any values stored in scale, precision, hasDouble, * origDouble, origDelta, and BCD data. */ protected abstract void setBcdToZero(); /** * Sets the internal BCD state to represent the value in the given int. The int is guaranteed to be * either positive. The internal state is guaranteed to be empty when this method is called. * * @param n * The value to consume. */ protected abstract void readIntToBcd(int input); /** * Sets the internal BCD state to represent the value in the given long. The long is guaranteed to be * either positive. The internal state is guaranteed to be empty when this method is called. * * @param n * The value to consume. */ protected abstract void readLongToBcd(long input); /** * Sets the internal BCD state to represent the value in the given BigInteger. The BigInteger is * guaranteed to be positive, and it is guaranteed to be larger than Long.MAX_VALUE. The internal * state is guaranteed to be empty when this method is called. * * @param n * The value to consume. */ protected abstract void readBigIntegerToBcd(BigInteger input); /** * Returns a BigDecimal encoding the internal BCD value. * * @return A BigDecimal representation of the internal BCD. */ protected abstract BigDecimal bcdToBigDecimal(); protected abstract void copyBcdFrom(DecimalQuantity _other); /** * Removes trailing zeros from the BCD (adjusting the scale as required) and then computes the * precision. The precision is the number of digits in the number up through the greatest nonzero * digit. * * <p> * This method must always be called when bcd changes in order for assumptions to be correct in * methods like {@link #fractionCount()}. */ protected abstract void compact(); }
./CrossVul/dataset_final_sorted/CWE-190/java/bad_434_3
crossvul-java_data_good_434_4
// © 2017 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License package com.ibm.icu.impl.number; import java.math.BigDecimal; import java.math.BigInteger; /** * A DecimalQuantity with internal storage as a 64-bit BCD, with fallback to a byte array for numbers * that don't fit into the standard BCD. */ public final class DecimalQuantity_DualStorageBCD extends DecimalQuantity_AbstractBCD { /** * The BCD of the 16 digits of the number represented by this object. Every 4 bits of the long map to * one digit. For example, the number "12345" in BCD is "0x12345". * * <p> * Whenever bcd changes internally, {@link #compact()} must be called, except in special cases like * setting the digit to zero. */ private byte[] bcdBytes; private long bcdLong = 0L; private boolean usingBytes = false; @Override public int maxRepresentableDigits() { return Integer.MAX_VALUE; } public DecimalQuantity_DualStorageBCD() { setBcdToZero(); flags = 0; } public DecimalQuantity_DualStorageBCD(long input) { setToLong(input); } public DecimalQuantity_DualStorageBCD(int input) { setToInt(input); } public DecimalQuantity_DualStorageBCD(double input) { setToDouble(input); } public DecimalQuantity_DualStorageBCD(BigInteger input) { setToBigInteger(input); } public DecimalQuantity_DualStorageBCD(BigDecimal input) { setToBigDecimal(input); } public DecimalQuantity_DualStorageBCD(DecimalQuantity_DualStorageBCD other) { copyFrom(other); } public DecimalQuantity_DualStorageBCD(Number number) { // NOTE: Number type expansion happens both here // and in NumberFormat.java if (number instanceof Long) { setToLong(number.longValue()); } else if (number instanceof Integer) { setToInt(number.intValue()); } else if (number instanceof Float) { setToDouble(number.doubleValue()); } else if (number instanceof Double) { setToDouble(number.doubleValue()); } else if (number instanceof BigInteger) { setToBigInteger((BigInteger) number); } else if (number instanceof BigDecimal) { setToBigDecimal((BigDecimal) number); } else if (number instanceof com.ibm.icu.math.BigDecimal) { setToBigDecimal(((com.ibm.icu.math.BigDecimal) number).toBigDecimal()); } else { throw new IllegalArgumentException( "Number is of an unsupported type: " + number.getClass().getName()); } } @Override public DecimalQuantity createCopy() { return new DecimalQuantity_DualStorageBCD(this); } @Override protected byte getDigitPos(int position) { if (usingBytes) { if (position < 0 || position >= precision) return 0; return bcdBytes[position]; } else { if (position < 0 || position >= 16) return 0; return (byte) ((bcdLong >>> (position * 4)) & 0xf); } } @Override protected void setDigitPos(int position, byte value) { assert position >= 0; if (usingBytes) { ensureCapacity(position + 1); bcdBytes[position] = value; } else if (position >= 16) { switchStorage(); ensureCapacity(position + 1); bcdBytes[position] = value; } else { int shift = position * 4; bcdLong = bcdLong & ~(0xfL << shift) | ((long) value << shift); } } @Override protected void shiftLeft(int numDigits) { if (!usingBytes && precision + numDigits > 16) { switchStorage(); } if (usingBytes) { ensureCapacity(precision + numDigits); int i = precision + numDigits - 1; for (; i >= numDigits; i--) { bcdBytes[i] = bcdBytes[i - numDigits]; } for (; i >= 0; i--) { bcdBytes[i] = 0; } } else { bcdLong <<= (numDigits * 4); } scale -= numDigits; precision += numDigits; } @Override protected void shiftRight(int numDigits) { if (usingBytes) { int i = 0; for (; i < precision - numDigits; i++) { bcdBytes[i] = bcdBytes[i + numDigits]; } for (; i < precision; i++) { bcdBytes[i] = 0; } } else { bcdLong >>>= (numDigits * 4); } scale += numDigits; precision -= numDigits; } @Override protected void setBcdToZero() { if (usingBytes) { bcdBytes = null; usingBytes = false; } bcdLong = 0L; scale = 0; precision = 0; isApproximate = false; origDouble = 0; origDelta = 0; } @Override protected void readIntToBcd(int n) { assert n != 0; // ints always fit inside the long implementation. long result = 0L; int i = 16; for (; n != 0; n /= 10, i--) { result = (result >>> 4) + (((long) n % 10) << 60); } assert !usingBytes; bcdLong = result >>> (i * 4); scale = 0; precision = 16 - i; } @Override protected void readLongToBcd(long n) { assert n != 0; if (n >= 10000000000000000L) { ensureCapacity(); int i = 0; for (; n != 0L; n /= 10L, i++) { bcdBytes[i] = (byte) (n % 10); } assert usingBytes; scale = 0; precision = i; } else { long result = 0L; int i = 16; for (; n != 0L; n /= 10L, i--) { result = (result >>> 4) + ((n % 10) << 60); } assert i >= 0; assert !usingBytes; bcdLong = result >>> (i * 4); scale = 0; precision = 16 - i; } } @Override protected void readBigIntegerToBcd(BigInteger n) { assert n.signum() != 0; ensureCapacity(); // allocate initial byte array int i = 0; for (; n.signum() != 0; i++) { BigInteger[] temp = n.divideAndRemainder(BigInteger.TEN); ensureCapacity(i + 1); bcdBytes[i] = temp[1].byteValue(); n = temp[0]; } scale = 0; precision = i; } @Override protected BigDecimal bcdToBigDecimal() { if (usingBytes) { // Converting to a string here is faster than doing BigInteger/BigDecimal arithmetic. BigDecimal result = new BigDecimal(toNumberString()); if (isNegative()) { result = result.negate(); } return result; } else { long tempLong = 0L; for (int shift = (precision - 1); shift >= 0; shift--) { tempLong = tempLong * 10 + getDigitPos(shift); } BigDecimal result = BigDecimal.valueOf(tempLong); try { result = result.scaleByPowerOfTen(scale); } catch (ArithmeticException e) { if (e.getMessage().contains("Underflow")) { result = BigDecimal.ZERO; } else { throw e; } } if (isNegative()) result = result.negate(); return result; } } @Override protected void compact() { if (usingBytes) { int delta = 0; for (; delta < precision && bcdBytes[delta] == 0; delta++) ; if (delta == precision) { // Number is zero setBcdToZero(); return; } else { // Remove trailing zeros shiftRight(delta); } // Compute precision int leading = precision - 1; for (; leading >= 0 && bcdBytes[leading] == 0; leading--) ; precision = leading + 1; // Switch storage mechanism if possible if (precision <= 16) { switchStorage(); } } else { if (bcdLong == 0L) { // Number is zero setBcdToZero(); return; } // Compact the number (remove trailing zeros) int delta = Long.numberOfTrailingZeros(bcdLong) / 4; bcdLong >>>= delta * 4; scale += delta; // Compute precision precision = 16 - (Long.numberOfLeadingZeros(bcdLong) / 4); } } /** Ensure that a byte array of at least 40 digits is allocated. */ private void ensureCapacity() { ensureCapacity(40); } private void ensureCapacity(int capacity) { if (capacity == 0) return; int oldCapacity = usingBytes ? bcdBytes.length : 0; if (!usingBytes) { bcdBytes = new byte[capacity]; } else if (oldCapacity < capacity) { byte[] bcd1 = new byte[capacity * 2]; System.arraycopy(bcdBytes, 0, bcd1, 0, oldCapacity); bcdBytes = bcd1; } usingBytes = true; } /** Switches the internal storage mechanism between the 64-bit long and the byte array. */ private void switchStorage() { if (usingBytes) { // Change from bytes to long bcdLong = 0L; for (int i = precision - 1; i >= 0; i--) { bcdLong <<= 4; bcdLong |= bcdBytes[i]; } bcdBytes = null; usingBytes = false; } else { // Change from long to bytes ensureCapacity(); for (int i = 0; i < precision; i++) { bcdBytes[i] = (byte) (bcdLong & 0xf); bcdLong >>>= 4; } assert usingBytes; } } @Override protected void copyBcdFrom(DecimalQuantity _other) { DecimalQuantity_DualStorageBCD other = (DecimalQuantity_DualStorageBCD) _other; setBcdToZero(); if (other.usingBytes) { ensureCapacity(other.precision); System.arraycopy(other.bcdBytes, 0, bcdBytes, 0, other.precision); } else { bcdLong = other.bcdLong; } } /** * Checks whether the bytes stored in this instance are all valid. For internal unit testing only. * * @return An error message if this instance is invalid, or null if this instance is healthy. * @internal * @deprecated This API is for ICU internal use only. */ @Deprecated public String checkHealth() { if (usingBytes) { if (bcdLong != 0) return "Value in bcdLong but we are in byte mode"; if (precision == 0) return "Zero precision but we are in byte mode"; if (precision > bcdBytes.length) return "Precision exceeds length of byte array"; if (getDigitPos(precision - 1) == 0) return "Most significant digit is zero in byte mode"; if (getDigitPos(0) == 0) return "Least significant digit is zero in long mode"; for (int i = 0; i < precision; i++) { if (getDigitPos(i) >= 10) return "Digit exceeding 10 in byte array"; if (getDigitPos(i) < 0) return "Digit below 0 in byte array"; } for (int i = precision; i < bcdBytes.length; i++) { if (getDigitPos(i) != 0) return "Nonzero digits outside of range in byte array"; } } else { if (bcdBytes != null) { for (int i = 0; i < bcdBytes.length; i++) { if (bcdBytes[i] != 0) return "Nonzero digits in byte array but we are in long mode"; } } if (precision == 0 && bcdLong != 0) return "Value in bcdLong even though precision is zero"; if (precision > 16) return "Precision exceeds length of long"; if (precision != 0 && getDigitPos(precision - 1) == 0) return "Most significant digit is zero in long mode"; if (precision != 0 && getDigitPos(0) == 0) return "Least significant digit is zero in long mode"; for (int i = 0; i < precision; i++) { if (getDigitPos(i) >= 10) return "Digit exceeding 10 in long"; if (getDigitPos(i) < 0) return "Digit below 0 in long (?!)"; } for (int i = precision; i < 16; i++) { if (getDigitPos(i) != 0) return "Nonzero digits outside of range in long"; } } return null; } /** * Checks whether this {@link DecimalQuantity_DualStorageBCD} is using its internal byte array * storage mechanism. * * @return true if an internal byte array is being used; false if a long is being used. * @internal * @deprecated This API is ICU internal only. */ @Deprecated public boolean isUsingBytes() { return usingBytes; } @Override public String toString() { return String.format("<DecimalQuantity %s:%d:%d:%s %s %s%s>", (lOptPos > 1000 ? "999" : String.valueOf(lOptPos)), lReqPos, rReqPos, (rOptPos < -1000 ? "-999" : String.valueOf(rOptPos)), (usingBytes ? "bytes" : "long"), (isNegative() ? "-" : ""), toNumberString()); } private String toNumberString() { StringBuilder sb = new StringBuilder(); if (usingBytes) { if (precision == 0) { sb.append('0'); } for (int i = precision - 1; i >= 0; i--) { sb.append(bcdBytes[i]); } } else { sb.append(Long.toHexString(bcdLong)); } sb.append("E"); sb.append(scale); return sb.toString(); } }
./CrossVul/dataset_final_sorted/CWE-190/java/good_434_4
crossvul-java_data_good_4445_0
/* Copyright (c) 2008-2015, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ package java.io; public class FileOutputStream extends OutputStream { // static { // System.loadLibrary("natives"); // } private int fd; public FileOutputStream(FileDescriptor fd) { this.fd = fd.value; } public FileOutputStream(String path) throws IOException { this(path, false); } public FileOutputStream(String path, boolean append) throws IOException { fd = open(path, append); } public FileOutputStream(File file) throws IOException { this(file.getPath()); } private static native int open(String path, boolean append) throws IOException; private static native void write(int fd, int c) throws IOException; private static native void write(int fd, byte[] b, int offset, int length) throws IOException; private static native void close(int fd) throws IOException; public void write(int c) throws IOException { write(fd, c); } public void write(byte[] b, int offset, int length) throws IOException { if (b == null) { throw new NullPointerException(); } if (offset < 0 || length < 0 || length > b.length || offset > b.length - length) { throw new ArrayIndexOutOfBoundsException(); } write(fd, b, offset, length); } public void close() throws IOException { if (fd != -1) { close(fd); fd = -1; } } }
./CrossVul/dataset_final_sorted/CWE-190/java/good_4445_0
crossvul-java_data_good_434_5
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html#License /* ******************************************************************************* * Copyright (C) 2001-2016, International Business Machines Corporation and * others. All Rights Reserved. ******************************************************************************* */ /** * Port From: ICU4C v1.8.1 : format : NumberFormatTest * Source File: $ICU4oot/source/test/intltest/numfmtst.cpp **/ package com.ibm.icu.dev.test.format; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigInteger; import java.math.RoundingMode; import java.text.AttributedCharacterIterator; import java.text.FieldPosition; import java.text.Format; import java.text.ParseException; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.Set; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import com.ibm.icu.dev.test.TestFmwk; import com.ibm.icu.dev.test.TestUtil; import com.ibm.icu.dev.test.format.IntlTestDecimalFormatAPIC.FieldContainer; import com.ibm.icu.dev.text.DecimalFormat_ICU58; import com.ibm.icu.impl.ICUConfig; import com.ibm.icu.impl.LocaleUtility; import com.ibm.icu.impl.data.ResourceReader; import com.ibm.icu.impl.data.TokenIterator; import com.ibm.icu.math.BigDecimal; import com.ibm.icu.math.MathContext; import com.ibm.icu.text.CompactDecimalFormat; import com.ibm.icu.text.CurrencyPluralInfo; import com.ibm.icu.text.DecimalFormat; import com.ibm.icu.text.DecimalFormatSymbols; import com.ibm.icu.text.DisplayContext; import com.ibm.icu.text.MeasureFormat; import com.ibm.icu.text.NumberFormat; import com.ibm.icu.text.NumberFormat.NumberFormatFactory; import com.ibm.icu.text.NumberFormat.SimpleNumberFormatFactory; import com.ibm.icu.text.NumberingSystem; import com.ibm.icu.text.RuleBasedNumberFormat; import com.ibm.icu.text.UnicodeSet; import com.ibm.icu.util.Currency; import com.ibm.icu.util.Currency.CurrencyUsage; import com.ibm.icu.util.CurrencyAmount; import com.ibm.icu.util.ULocale; @RunWith(JUnit4.class) public class NumberFormatTest extends TestFmwk { @Test public void TestRoundingScientific10542() { DecimalFormat format = new DecimalFormat("0.00E0"); int[] roundingModes = { BigDecimal.ROUND_CEILING, BigDecimal.ROUND_DOWN, BigDecimal.ROUND_FLOOR, BigDecimal.ROUND_HALF_DOWN, BigDecimal.ROUND_HALF_EVEN, BigDecimal.ROUND_HALF_UP, BigDecimal.ROUND_UP}; String[] descriptions = { "Round Ceiling", "Round Down", "Round Floor", "Round half down", "Round half even", "Round half up", "Round up"}; double[] values = {-0.003006, -0.003005, -0.003004, 0.003014, 0.003015, 0.003016}; // The order of these expected values correspond to the order of roundingModes and the order of values. String[][] expected = { {"-3.00E-3", "-3.00E-3", "-3.00E-3", "3.02E-3", "3.02E-3", "3.02E-3"}, {"-3.00E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.01E-3", "3.01E-3"}, {"-3.01E-3", "-3.01E-3", "-3.01E-3", "3.01E-3", "3.01E-3", "3.01E-3"}, {"-3.01E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.01E-3", "3.02E-3"}, {"-3.01E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.02E-3", "3.02E-3"}, {"-3.01E-3", "-3.01E-3", "-3.00E-3", "3.01E-3", "3.02E-3", "3.02E-3"}, {"-3.01E-3", "-3.01E-3", "-3.01E-3", "3.02E-3", "3.02E-3", "3.02E-3"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{-3006.0, -3005, -3004, 3014, 3015, 3016}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"-3.00E3", "-3.00E3", "-3.00E3", "3.02E3", "3.02E3", "3.02E3"}, {"-3.00E3", "-3.00E3", "-3.00E3", "3.01E3", "3.01E3", "3.01E3"}, {"-3.01E3", "-3.01E3", "-3.01E3", "3.01E3", "3.01E3", "3.01E3"}, {"-3.01E3", "-3.00E3", "-3.00E3", "3.01E3", "3.01E3", "3.02E3"}, {"-3.01E3", "-3.00E3", "-3.00E3", "3.01E3", "3.02E3", "3.02E3"}, {"-3.01E3", "-3.01E3", "-3.00E3", "3.01E3", "3.02E3", "3.02E3"}, {"-3.01E3", "-3.01E3", "-3.01E3", "3.02E3", "3.02E3", "3.02E3"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{0.0, -0.0}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}, {"0.00E0", "-0.00E0"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{1e25, 1e25 + 1e15, 1e25 - 1e15}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"1.00E25", "1.01E25", "1.00E25"}, {"1.00E25", "1.00E25", "9.99E24"}, {"1.00E25", "1.00E25", "9.99E24"}, {"1.00E25", "1.00E25", "1.00E25"}, {"1.00E25", "1.00E25", "1.00E25"}, {"1.00E25", "1.00E25", "1.00E25"}, {"1.00E25", "1.01E25", "1.00E25"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{-1e25, -1e25 + 1e15, -1e25 - 1e15}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"-1.00E25", "-9.99E24", "-1.00E25"}, {"-1.00E25", "-9.99E24", "-1.00E25"}, {"-1.00E25", "-1.00E25", "-1.01E25"}, {"-1.00E25", "-1.00E25", "-1.00E25"}, {"-1.00E25", "-1.00E25", "-1.00E25"}, {"-1.00E25", "-1.00E25", "-1.00E25"}, {"-1.00E25", "-1.00E25", "-1.01E25"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{1e-25, 1e-25 + 1e-35, 1e-25 - 1e-35}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"1.00E-25", "1.01E-25", "1.00E-25"}, {"1.00E-25", "1.00E-25", "9.99E-26"}, {"1.00E-25", "1.00E-25", "9.99E-26"}, {"1.00E-25", "1.00E-25", "1.00E-25"}, {"1.00E-25", "1.00E-25", "1.00E-25"}, {"1.00E-25", "1.00E-25", "1.00E-25"}, {"1.00E-25", "1.01E-25", "1.00E-25"}}; verifyRounding(format, values, expected, roundingModes, descriptions); values = new double[]{-1e-25, -1e-25 + 1e-35, -1e-25 - 1e-35}; // The order of these expected values correspond to the order of roundingModes and the order of values. expected = new String[][]{ {"-1.00E-25", "-9.99E-26", "-1.00E-25"}, {"-1.00E-25", "-9.99E-26", "-1.00E-25"}, {"-1.00E-25", "-1.00E-25", "-1.01E-25"}, {"-1.00E-25", "-1.00E-25", "-1.00E-25"}, {"-1.00E-25", "-1.00E-25", "-1.00E-25"}, {"-1.00E-25", "-1.00E-25", "-1.00E-25"}, {"-1.00E-25", "-1.00E-25", "-1.01E-25"}}; verifyRounding(format, values, expected, roundingModes, descriptions); } private void verifyRounding(DecimalFormat format, double[] values, String[][] expected, int[] roundingModes, String[] descriptions) { for (int i = 0; i < roundingModes.length; i++) { format.setRoundingMode(roundingModes[i]); for (int j = 0; j < values.length; j++) { assertEquals(descriptions[i]+" " +values[j], expected[i][j], format.format(values[j])); } } } @Test public void Test10419RoundingWith0FractionDigits() { Object[][] data = new Object[][]{ {BigDecimal.ROUND_CEILING, 1.488, "2"}, {BigDecimal.ROUND_DOWN, 1.588, "1"}, {BigDecimal.ROUND_FLOOR, 1.588, "1"}, {BigDecimal.ROUND_HALF_DOWN, 1.5, "1"}, {BigDecimal.ROUND_HALF_EVEN, 2.5, "2"}, {BigDecimal.ROUND_HALF_UP, 2.5, "3"}, {BigDecimal.ROUND_UP, 1.5, "2"}, }; NumberFormat nff = NumberFormat.getNumberInstance(ULocale.ENGLISH); nff.setMaximumFractionDigits(0); for (Object[] item : data) { nff.setRoundingMode(((Integer) item[0]).intValue()); assertEquals("Test10419", item[2], nff.format(item[1])); } } @Test public void TestParseNegativeWithFaLocale() { DecimalFormat parser = (DecimalFormat) NumberFormat.getInstance(new ULocale("fa")); try { double value = parser.parse("-0,5").doubleValue(); assertEquals("Expect -0.5", -0.5, value); } catch (ParseException e) { TestFmwk.errln("Parsing -0.5 should have succeeded."); } } @Test public void TestParseNegativeWithAlternativeMinusSign() { DecimalFormat parser = (DecimalFormat) NumberFormat.getInstance(new ULocale("en")); try { double value = parser.parse("\u208B0.5").doubleValue(); assertEquals("Expect -0.5", -0.5, value); } catch (ParseException e) { TestFmwk.errln("Parsing -0.5 should have succeeded."); } } // Test various patterns @Test public void TestPatterns() { DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); final String pat[] = { "#.#", "#.", ".#", "#" }; int pat_length = pat.length; final String newpat[] = { "0.#", "0.", "#.0", "0" }; final String num[] = { "0", "0.", ".0", "0" }; for (int i=0; i<pat_length; ++i) { DecimalFormat fmt = new DecimalFormat(pat[i], sym); String newp = fmt.toPattern(); if (!newp.equals(newpat[i])) errln("FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] + "; " + newp + " seen instead"); String s = ((NumberFormat)fmt).format(0); if (!s.equals(num[i])) { errln("FAIL: Pattern " + pat[i] + " should format zero as " + num[i] + "; " + s + " seen instead"); logln("Min integer digits = " + fmt.getMinimumIntegerDigits()); } // BigInteger 0 - ticket#4731 s = ((NumberFormat)fmt).format(BigInteger.ZERO); if (!s.equals(num[i])) { errln("FAIL: Pattern " + pat[i] + " should format BigInteger zero as " + num[i] + "; " + s + " seen instead"); logln("Min integer digits = " + fmt.getMinimumIntegerDigits()); } } } // Test exponential pattern @Test public void TestExponential() { DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); final String pat[] = { "0.####E0", "00.000E00", "##0.######E000", "0.###E0;[0.###E0]" }; int pat_length = pat.length; double val[] = { 0.01234, 123456789, 1.23e300, -3.141592653e-271 }; int val_length = val.length; final String valFormat[] = { // 0.####E0 "1.234E-2", "1.2346E8", "1.23E300", "-3.1416E-271", // 00.000E00 "12.340E-03", "12.346E07", "12.300E299", "-31.416E-272", // ##0.######E000 "12.34E-003", "123.4568E006", "1.23E300", "-314.1593E-273", // 0.###E0;[0.###E0] "1.234E-2", "1.235E8", "1.23E300", "[3.142E-271]" }; /*double valParse[] = { 0.01234, 123460000, 1.23E300, -3.1416E-271, 0.01234, 123460000, 1.23E300, -3.1416E-271, 0.01234, 123456800, 1.23E300, -3.141593E-271, 0.01234, 123500000, 1.23E300, -3.142E-271, };*/ //The variable is never used int lval[] = { 0, -1, 1, 123456789 }; int lval_length = lval.length; final String lvalFormat[] = { // 0.####E0 "0E0", "-1E0", "1E0", "1.2346E8", // 00.000E00 "00.000E00", "-10.000E-01", "10.000E-01", "12.346E07", // ##0.######E000 "0E000", "-1E000", "1E000", "123.4568E006", // 0.###E0;[0.###E0] "0E0", "[1E0]", "1E0", "1.235E8" }; int lvalParse[] = { 0, -1, 1, 123460000, 0, -1, 1, 123460000, 0, -1, 1, 123456800, 0, -1, 1, 123500000, }; int ival = 0, ilval = 0; for (int p = 0; p < pat_length; ++p) { DecimalFormat fmt = new DecimalFormat(pat[p], sym); logln("Pattern \"" + pat[p] + "\" -toPattern-> \"" + fmt.toPattern() + "\""); int v; for (v = 0; v < val_length; ++v) { String s; s = ((NumberFormat) fmt).format(val[v]); logln(" " + val[v] + " -format-> " + s); if (!s.equals(valFormat[v + ival])) errln("FAIL: Expected " + valFormat[v + ival]); ParsePosition pos = new ParsePosition(0); double a = fmt.parse(s, pos).doubleValue(); if (pos.getIndex() == s.length()) { logln(" -parse-> " + Double.toString(a)); // Use epsilon comparison as necessary } else errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); } for (v = 0; v < lval_length; ++v) { String s; s = ((NumberFormat) fmt).format(lval[v]); logln(" " + lval[v] + "L -format-> " + s); if (!s.equals(lvalFormat[v + ilval])) errln("ERROR: Expected " + lvalFormat[v + ilval] + " Got: " + s); ParsePosition pos = new ParsePosition(0); long a = 0; Number A = fmt.parse(s, pos); if (A != null) { a = A.longValue(); if (pos.getIndex() == s.length()) { logln(" -parse-> " + a); if (a != lvalParse[v + ilval]) errln("FAIL: Expected " + lvalParse[v + ilval]); } else errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + Long.toString(a)); } else { errln("Fail to parse the string: " + s); } } ival += val_length; ilval += lval_length; } } // Test the handling of quotes @Test public void TestQuotes() { StringBuffer pat; DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); pat = new StringBuffer("a'fo''o'b#"); DecimalFormat fmt = new DecimalFormat(pat.toString(), sym); String s = ((NumberFormat)fmt).format(123); logln("Pattern \"" + pat + "\""); logln(" Format 123 . " + s); if (!s.equals("afo'ob123")) errln("FAIL: Expected afo'ob123"); s =""; pat = new StringBuffer("a''b#"); fmt = new DecimalFormat(pat.toString(), sym); s = ((NumberFormat)fmt).format(123); logln("Pattern \"" + pat + "\""); logln(" Format 123 . " + s); if (!s.equals("a'b123")) errln("FAIL: Expected a'b123"); } @Test public void TestParseCurrencyTrailingSymbol() { // see sun bug 4709840 NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.GERMANY); float val = 12345.67f; String str = fmt.format(val); logln("val: " + val + " str: " + str); try { Number num = fmt.parse(str); logln("num: " + num); } catch (ParseException e) { errln("parse of '" + str + "' threw exception: " + e); } } /** * Test the handling of the currency symbol in patterns. **/ @Test public void TestCurrencySign() { DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); StringBuffer pat = new StringBuffer(""); char currency = 0x00A4; // "\xA4#,##0.00;-\xA4#,##0.00" pat.append(currency).append("#,##0.00;-").append(currency).append("#,##0.00"); DecimalFormat fmt = new DecimalFormat(pat.toString(), sym); String s = ((NumberFormat) fmt).format(1234.56); pat = new StringBuffer(); logln("Pattern \"" + fmt.toPattern() + "\""); logln(" Format " + 1234.56 + " . " + s); assertEquals("symbol, pos", "$1,234.56", s); s = ((NumberFormat) fmt).format(-1234.56); logln(" Format " + Double.toString(-1234.56) + " . " + s); assertEquals("symbol, neg", "-$1,234.56", s); pat.setLength(0); // "\xA4\xA4 #,##0.00;\xA4\xA4 -#,##0.00" pat.append(currency).append(currency).append(" #,##0.00;").append(currency).append(currency).append(" -#,##0.00"); fmt = new DecimalFormat(pat.toString(), sym); s = ((NumberFormat) fmt).format(1234.56); logln("Pattern \"" + fmt.toPattern() + "\""); logln(" Format " + Double.toString(1234.56) + " . " + s); assertEquals("name, pos", "USD 1,234.56", s); s = ((NumberFormat) fmt).format(-1234.56); logln(" Format " + Double.toString(-1234.56) + " . " + s); assertEquals("name, neg", "USD -1,234.56", s); } @Test public void TestSpaceParsing() { // the data are: // the string to be parsed, parsed position, parsed error index String[][] DATA = { {"$124", "4", "-1"}, {"$124 $124", "4", "-1"}, {"$124 ", "4", "-1"}, {"$124 ", "4", "-1"}, {"$ 124 ", "5", "-1"}, {"$\u00A0124 ", "5", "-1"}, {" $ 124 ", "6", "-1"}, {"124$", "4", "-1"}, {"124 $", "5", "-1"}, {"$124\u200A", "4", "-1"}, {"$\u200A124", "5", "-1"}, }; NumberFormat foo = NumberFormat.getCurrencyInstance(); for (int i = 0; i < DATA.length; ++i) { ParsePosition parsePosition = new ParsePosition(0); String stringToBeParsed = DATA[i][0]; int parsedPosition = Integer.parseInt(DATA[i][1]); int errorIndex = Integer.parseInt(DATA[i][2]); try { Number result = foo.parse(stringToBeParsed, parsePosition); if (parsePosition.getIndex() != parsedPosition || parsePosition.getErrorIndex() != errorIndex) { errln("FAILED parse " + stringToBeParsed + "; parse position: " + parsePosition.getIndex() + "; error position: " + parsePosition.getErrorIndex()); } if (parsePosition.getErrorIndex() == -1 && result.doubleValue() != 124) { errln("FAILED parse " + stringToBeParsed + "; value " + result.doubleValue()); } } catch (Exception e) { errln("FAILED " + e.toString()); } } } @Test public void TestSpaceParsingStrict() { // All trailing grouping separators should be ignored in strict mode, not just the first. Object[][] cases = { {"123 ", 3, -1}, {"123 ", 3, -1}, {"123 ,", 3, -1}, {"123,", 3, -1}, {"123, ", 3, -1}, {"123,,", 3, -1}, {"123,, ", 3, -1}, {"123,,456", 3, -1}, {"123 ,", 3, -1}, {"123, ", 3, -1}, {"123, 456", 3, -1}, {"123 456", 3, -1} }; DecimalFormat df = new DecimalFormat("#,###"); df.setParseStrict(true); for (Object[] cas : cases) { String input = (String) cas[0]; int expectedIndex = (Integer) cas[1]; int expectedErrorIndex = (Integer) cas[2]; ParsePosition ppos = new ParsePosition(0); df.parse(input, ppos); assertEquals("Failed on index: '" + input + "'", expectedIndex, ppos.getIndex()); assertEquals("Failed on error: '" + input + "'", expectedErrorIndex, ppos.getErrorIndex()); } } @Test public void TestMultiCurrencySign() { String[][] DATA = { // the fields in the following test are: // locale, // currency pattern (with negative pattern), // currency number to be formatted, // currency format using currency symbol name, such as "$" for USD, // currency format using currency ISO name, such as "USD", // currency format using plural name, such as "US dollars". // for US locale {"en_US", "\u00A4#,##0.00;-\u00A4#,##0.00", "1234.56", "$1,234.56", "USD 1,234.56", "US dollars 1,234.56"}, {"en_US", "\u00A4#,##0.00;-\u00A4#,##0.00", "-1234.56", "-$1,234.56", "-USD 1,234.56", "-US dollars 1,234.56"}, {"en_US", "\u00A4#,##0.00;-\u00A4#,##0.00", "1", "$1.00", "USD 1.00", "US dollars 1.00"}, // for CHINA locale {"zh_CN", "\u00A4#,##0.00;(\u00A4#,##0.00)", "1234.56", "\uFFE51,234.56", "CNY 1,234.56", "\u4EBA\u6C11\u5E01 1,234.56"}, {"zh_CN", "\u00A4#,##0.00;(\u00A4#,##0.00)", "-1234.56", "(\uFFE51,234.56)", "(CNY 1,234.56)", "(\u4EBA\u6C11\u5E01 1,234.56)"}, {"zh_CN", "\u00A4#,##0.00;(\u00A4#,##0.00)", "1", "\uFFE51.00", "CNY 1.00", "\u4EBA\u6C11\u5E01 1.00"} }; String doubleCurrencyStr = "\u00A4\u00A4"; String tripleCurrencyStr = "\u00A4\u00A4\u00A4"; for (int i=0; i<DATA.length; ++i) { String locale = DATA[i][0]; String pat = DATA[i][1]; Double numberToBeFormat = new Double(DATA[i][2]); DecimalFormatSymbols sym = new DecimalFormatSymbols(new ULocale(locale)); for (int j=1; j<=3; ++j) { // j represents the number of currency sign in the pattern. if (j == 2) { pat = pat.replaceAll("\u00A4", doubleCurrencyStr); } else if (j == 3) { pat = pat.replaceAll("\u00A4\u00A4", tripleCurrencyStr); } DecimalFormat fmt = new DecimalFormat(pat, sym); String s = ((NumberFormat) fmt).format(numberToBeFormat); // DATA[i][3] is the currency format result using a // single currency sign. // DATA[i][4] is the currency format result using // double currency sign. // DATA[i][5] is the currency format result using // triple currency sign. // DATA[i][j+2] is the currency format result using // 'j' number of currency sign. String currencyFormatResult = DATA[i][2+j]; if (!s.equals(currencyFormatResult)) { errln("FAIL format: Expected " + currencyFormatResult + " but got " + s); } try { // mix style parsing for (int k=3; k<=4; ++k) { // DATA[i][3] is the currency format result using a // single currency sign. // DATA[i][4] is the currency format result using // double currency sign. // DATA[i][5] is the currency format result using // triple currency sign. // ICU 59: long name parsing requires currency mode. String oneCurrencyFormat = DATA[i][k]; if (fmt.parse(oneCurrencyFormat).doubleValue() != numberToBeFormat.doubleValue()) { errln("FAILED parse " + oneCurrencyFormat); } } } catch (ParseException e) { errln("FAILED, DecimalFormat parse currency: " + e.toString()); } } } } @Test public void TestCurrencyFormatForMixParsing() { MeasureFormat curFmt = MeasureFormat.getCurrencyFormat(new ULocale("en_US")); String[] formats = { "$1,234.56", // string to be parsed "USD1,234.56", "US dollars1,234.56", "1,234.56 US dollars" }; try { for (int i = 0; i < formats.length; ++i) { String stringToBeParsed = formats[i]; CurrencyAmount parsedVal = (CurrencyAmount)curFmt.parseObject(stringToBeParsed); Number val = parsedVal.getNumber(); if (!val.equals(new BigDecimal("1234.56"))) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the number. val=" + val); } if (!parsedVal.getCurrency().equals(Currency.getInstance("USD"))) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the currency"); } } } catch (ParseException e) { errln("parse FAILED: " + e.toString()); } } /** Starting in ICU 62, strict mode is actually strict with currency formats. */ @Test public void TestMismatchedCurrencyFormatFail() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(ULocale.ENGLISH); assertEquals("Test assumes that currency sign is at the beginning", "\u00A4#,##0.00", df.toPattern()); // Should round-trip on the correct currency format: expect2(df, 1.23, "\u00A41.23"); df.setCurrency(Currency.getInstance("EUR")); expect2(df, 1.23, "\u20AC1.23"); // Should parse with currency in the wrong place in lenient mode df.setParseStrict(false); expect(df, "1.23\u20AC", 1.23); expectParseCurrency(df, Currency.getInstance("EUR"), "1.23\u20AC"); // Should NOT parse with currency in the wrong place in STRICT mode df.setParseStrict(true); { ParsePosition ppos = new ParsePosition(0); df.parse("1.23\u20AC", ppos); assertEquals("Should fail to parse", 0, ppos.getIndex()); } { ParsePosition ppos = new ParsePosition(0); df.parseCurrency("1.23\u20AC", ppos); assertEquals("Should fail to parse currency", 0, ppos.getIndex()); } } @Test public void TestDecimalFormatCurrencyParse() { // Locale.US DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); StringBuffer pat = new StringBuffer(""); char currency = 0x00A4; // "\xA4#,##0.00;-\xA4#,##0.00" pat.append(currency).append(currency).append(currency).append("#,##0.00;-").append(currency).append(currency).append(currency).append("#,##0.00"); DecimalFormat fmt = new DecimalFormat(pat.toString(), sym); String[][] DATA = { // the data are: // string to be parsed, the parsed result (number) {"$1.00", "1"}, {"USD1.00", "1"}, {"1.00 US dollar", "1"}, {"$1,234.56", "1234.56"}, {"USD1,234.56", "1234.56"}, {"1,234.56 US dollar", "1234.56"}, }; try { for (int i = 0; i < DATA.length; ++i) { String stringToBeParsed = DATA[i][0]; double parsedResult = Double.parseDouble(DATA[i][1]); Number num = fmt.parse(stringToBeParsed); if (num.doubleValue() != parsedResult) { errln("FAIL parse: Expected " + parsedResult); } } } catch (ParseException e) { errln("FAILED, DecimalFormat parse currency: " + e.toString()); } } /** * Test localized currency patterns. */ @Test public void TestCurrency() { String[] DATA = { "fr", "CA", "", "1,50\u00a0$", "de", "DE", "", "1,50\u00a0\u20AC", "de", "DE", "PREEURO", "1,50\u00a0DM", "fr", "FR", "", "1,50\u00a0\u20AC", "fr", "FR", "PREEURO", "1,50\u00a0F", }; for (int i=0; i<DATA.length; i+=4) { Locale locale = new Locale(DATA[i], DATA[i+1], DATA[i+2]); NumberFormat fmt = NumberFormat.getCurrencyInstance(locale); String s = fmt.format(1.50); if (s.equals(DATA[i+3])) { logln("Ok: 1.50 x " + locale + " => " + s); } else { logln("FAIL: 1.50 x " + locale + " => " + s + ", expected " + DATA[i+3]); } } // format currency with CurrencyAmount for (int i=0; i<DATA.length; i+=4) { Locale locale = new Locale(DATA[i], DATA[i+1], DATA[i+2]); Currency curr = Currency.getInstance(locale); logln("\nName of the currency is: " + curr.getName(locale, Currency.LONG_NAME, new boolean[] {false})); CurrencyAmount cAmt = new CurrencyAmount(1.5, curr); logln("CurrencyAmount object's hashCode is: " + cAmt.hashCode()); //cover hashCode NumberFormat fmt = NumberFormat.getCurrencyInstance(locale); String sCurr = fmt.format(cAmt); if (sCurr.equals(DATA[i+3])) { logln("Ok: 1.50 x " + locale + " => " + sCurr); } else { errln("FAIL: 1.50 x " + locale + " => " + sCurr + ", expected " + DATA[i+3]); } } //Cover MeasureFormat.getCurrencyFormat() ULocale save = ULocale.getDefault(); ULocale.setDefault(ULocale.US); MeasureFormat curFmt = MeasureFormat.getCurrencyFormat(); String strBuf = curFmt.format(new CurrencyAmount(new Float(1234.56), Currency.getInstance("USD"))); try { CurrencyAmount parsedVal = (CurrencyAmount)curFmt.parseObject(strBuf); Number val = parsedVal.getNumber(); if (!val.equals(new BigDecimal("1234.56"))) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the number. val=" + val); } if (!parsedVal.getCurrency().equals(Currency.getInstance("USD"))) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the currency"); } } catch (ParseException e) { errln("FAIL: " + e.getMessage()); } ULocale.setDefault(save); } @Test public void TestJavaCurrencyConversion() { java.util.Currency gbpJava = java.util.Currency.getInstance("GBP"); Currency gbpIcu = Currency.getInstance("GBP"); assertEquals("ICU should equal API value", gbpIcu, Currency.fromJavaCurrency(gbpJava)); assertEquals("Java should equal API value", gbpJava, gbpIcu.toJavaCurrency()); // Test CurrencyAmount constructors CurrencyAmount ca1 = new CurrencyAmount(123.45, gbpJava); CurrencyAmount ca2 = new CurrencyAmount(123.45, gbpIcu); assertEquals("CurrencyAmount from both Double constructors should be equal", ca1, ca2); // Coverage for the Number constructor ca1 = new CurrencyAmount(new BigDecimal("543.21"), gbpJava); ca2 = new CurrencyAmount(new BigDecimal("543.21"), gbpIcu); assertEquals("CurrencyAmount from both Number constructors should be equal", ca1, ca2); } @Test public void TestCurrencyIsoPluralFormat() { String[][] DATA = { // the data are: // locale, // currency amount to be formatted, // currency ISO code to be formatted, // format result using CURRENCYSTYLE, // format result using ISOCURRENCYSTYLE, // format result using PLURALCURRENCYSTYLE, {"en_US", "1", "USD", "$1.00", "USD 1.00", "1.00 US dollars"}, {"en_US", "1234.56", "USD", "$1,234.56", "USD 1,234.56", "1,234.56 US dollars"}, {"en_US", "-1234.56", "USD", "-$1,234.56", "-USD 1,234.56", "-1,234.56 US dollars"}, {"zh_CN", "1", "USD", "US$1.00", "USD 1.00", "1.00 美元"}, {"zh_CN", "1234.56", "USD", "US$1,234.56", "USD 1,234.56", "1,234.56 美元"}, {"zh_CN", "1", "CNY", "¥1.00", "CNY 1.00", "1.00 人民币"}, {"zh_CN", "1234.56", "CNY", "¥1,234.56", "CNY 1,234.56", "1,234.56 人民币"}, {"ru_RU", "1", "RUB", "1,00 \u20BD", "1,00 RUB", "1,00 российского рубля"}, {"ru_RU", "2", "RUB", "2,00 \u20BD", "2,00 RUB", "2,00 российского рубля"}, {"ru_RU", "5", "RUB", "5,00 \u20BD", "5,00 RUB", "5,00 российского рубля"}, // test locale without currency information {"root", "-1.23", "USD", "-US$ 1.23", "-USD 1.23", "-1.23 USD"}, {"root@numbers=latn", "-1.23", "USD", "-US$ 1.23", "-USD 1.23", "-1.23 USD"}, // ensure that the root locale is still used with modifiers {"root@numbers=arab", "-1.23", "USD", "\u061C-\u0661\u066B\u0662\u0663\u00A0US$", "\u061C-\u0661\u066B\u0662\u0663\u00A0USD", "\u061C-\u0661\u066B\u0662\u0663 USD"}, // ensure that the root locale is still used with modifiers {"es_AR", "1", "INR", "INR\u00A01,00", "INR\u00A01,00", "1,00 rupia india"}, {"ar_EG", "1", "USD", "١٫٠٠\u00A0US$", "١٫٠٠\u00A0USD", "١٫٠٠ دولار أمريكي"}, }; for (int i=0; i<DATA.length; ++i) { for (int k = NumberFormat.CURRENCYSTYLE; k <= NumberFormat.PLURALCURRENCYSTYLE; ++k) { // k represents currency format style. if ( k != NumberFormat.CURRENCYSTYLE && k != NumberFormat.ISOCURRENCYSTYLE && k != NumberFormat.PLURALCURRENCYSTYLE ) { continue; } String localeString = DATA[i][0]; Double numberToBeFormat = new Double(DATA[i][1]); String currencyISOCode = DATA[i][2]; ULocale locale = new ULocale(localeString); NumberFormat numFmt = NumberFormat.getInstance(locale, k); numFmt.setCurrency(Currency.getInstance(currencyISOCode)); String strBuf = numFmt.format(numberToBeFormat); int resultDataIndex = k-1; if ( k == NumberFormat.CURRENCYSTYLE ) { resultDataIndex = k+2; } // DATA[i][resultDataIndex] is the currency format result // using 'k' currency style. String formatResult = DATA[i][resultDataIndex]; if (!strBuf.equals(formatResult)) { errln("FAIL: localeID: " + localeString + ", expected(" + formatResult.length() + "): \"" + formatResult + "\", actual(" + strBuf.length() + "): \"" + strBuf + "\""); } // test parsing, and test parsing for all currency formats. for (int j = 3; j < 6; ++j) { // DATA[i][3] is the currency format result using // CURRENCYSTYLE formatter. // DATA[i][4] is the currency format result using // ISOCURRENCYSTYLE formatter. // DATA[i][5] is the currency format result using // PLURALCURRENCYSTYLE formatter. String oneCurrencyFormatResult = DATA[i][j]; CurrencyAmount val = numFmt.parseCurrency(oneCurrencyFormatResult, null); if (val.getNumber().doubleValue() != numberToBeFormat.doubleValue()) { errln("FAIL: getCurrencyFormat of locale " + localeString + " failed roundtripping the number. val=" + val + "; expected: " + numberToBeFormat); } } } } } @Test public void TestMiscCurrencyParsing() { String[][] DATA = { // each has: string to be parsed, parsed position, error position {"1.00 ", "4", "-1", "0", "4"}, {"1.00 UAE dirha", "4", "-1", "0", "4"}, {"1.00 us dollar", "14", "-1", "14", "-1"}, {"1.00 US DOLLAR", "14", "-1", "14", "-1"}, {"1.00 usd", "8", "-1", "8", "-1"}, {"1.00 USD", "8", "-1", "8", "-1"}, }; ULocale locale = new ULocale("en_US"); for (int i=0; i<DATA.length; ++i) { String stringToBeParsed = DATA[i][0]; int parsedPosition = Integer.parseInt(DATA[i][1]); int errorIndex = Integer.parseInt(DATA[i][2]); int currParsedPosition = Integer.parseInt(DATA[i][3]); int currErrorIndex = Integer.parseInt(DATA[i][4]); NumberFormat numFmt = NumberFormat.getInstance(locale, NumberFormat.CURRENCYSTYLE); ParsePosition parsePosition = new ParsePosition(0); Number val = numFmt.parse(stringToBeParsed, parsePosition); if (parsePosition.getIndex() != parsedPosition || parsePosition.getErrorIndex() != errorIndex) { errln("FAIL: parse failed on case "+i+". expected position: " + parsedPosition +"; actual: " + parsePosition.getIndex()); errln("FAIL: parse failed on case "+i+". expected error position: " + errorIndex + "; actual: " + parsePosition.getErrorIndex()); } if (parsePosition.getErrorIndex() == -1 && val.doubleValue() != 1.00) { errln("FAIL: parse failed. expected 1.00, actual:" + val); } parsePosition = new ParsePosition(0); CurrencyAmount amt = numFmt.parseCurrency(stringToBeParsed, parsePosition); if (parsePosition.getIndex() != currParsedPosition || parsePosition.getErrorIndex() != currErrorIndex) { errln("FAIL: parseCurrency failed on case "+i+". expected error position: " + currErrorIndex + "; actual: " + parsePosition.getErrorIndex()); errln("FAIL: parseCurrency failed on case "+i+". expected position: " + currParsedPosition +"; actual: " + parsePosition.getIndex()); } if (parsePosition.getErrorIndex() == -1 && amt.getNumber().doubleValue() != 1.00) { errln("FAIL: parseCurrency failed. expected 1.00, actual:" + val); } } } @Test public void TestParseCurrency() { class ParseCurrencyItem { private final String localeString; private final String descrip; private final String currStr; private final int doubExpectPos; private final int doubExpectVal; private final int curExpectPos; private final int curExpectVal; private final String curExpectCurr; ParseCurrencyItem(String locStr, String desc, String curr, int doubExPos, int doubExVal, int curExPos, int curExVal, String curExCurr) { localeString = locStr; descrip = desc; currStr = curr; doubExpectPos = doubExPos; doubExpectVal = doubExVal; curExpectPos = curExPos; curExpectVal = curExVal; curExpectCurr = curExCurr; } public String getLocaleString() { return localeString; } public String getDescrip() { return descrip; } public String getCurrStr() { return currStr; } public int getDoubExpectPos() { return doubExpectPos; } public int getDoubExpectVal() { return doubExpectVal; } public int getCurExpectPos() { return curExpectPos; } public int getCurExpectVal() { return curExpectVal; } public String getCurExpectCurr() { return curExpectCurr; } } // Note: In cases where the number occurs before the currency sign, non-currency mode will parse the number // and stop when it reaches the currency symbol. final ParseCurrencyItem[] parseCurrencyItems = { new ParseCurrencyItem( "en_US", "dollars2", "$2.00", 5, 2, 5, 2, "USD" ), new ParseCurrencyItem( "en_US", "dollars4", "$4", 2, 4, 2, 4, "USD" ), new ParseCurrencyItem( "en_US", "dollars9", "9\u00A0$", 3, 9, 3, 9, "USD" ), new ParseCurrencyItem( "en_US", "pounds3", "\u00A33.00", 0, 0, 5, 3, "GBP" ), new ParseCurrencyItem( "en_US", "pounds5", "\u00A35", 0, 0, 2, 5, "GBP" ), new ParseCurrencyItem( "en_US", "pounds7", "7\u00A0\u00A3", 1, 7, 3, 7, "GBP" ), new ParseCurrencyItem( "en_US", "euros8", "\u20AC8", 0, 0, 2, 8, "EUR" ), new ParseCurrencyItem( "en_GB", "pounds3", "\u00A33.00", 5, 3, 5, 3, "GBP" ), new ParseCurrencyItem( "en_GB", "pounds5", "\u00A35", 2, 5, 2, 5, "GBP" ), new ParseCurrencyItem( "en_GB", "pounds7", "7\u00A0\u00A3", 3, 7, 3, 7, "GBP" ), new ParseCurrencyItem( "en_GB", "euros4", "4,00\u00A0\u20AC", 4,400, 6,400, "EUR" ), new ParseCurrencyItem( "en_GB", "euros6", "6\u00A0\u20AC", 1, 6, 3, 6, "EUR" ), new ParseCurrencyItem( "en_GB", "euros8", "\u20AC8", 0, 0, 2, 8, "EUR" ), new ParseCurrencyItem( "en_GB", "dollars4", "US$4", 0, 0, 4, 4, "USD" ), new ParseCurrencyItem( "fr_FR", "euros4", "4,00\u00A0\u20AC", 6, 4, 6, 4, "EUR" ), new ParseCurrencyItem( "fr_FR", "euros6", "6\u00A0\u20AC", 3, 6, 3, 6, "EUR" ), new ParseCurrencyItem( "fr_FR", "euros8", "\u20AC8", 2, 8, 2, 8, "EUR" ), new ParseCurrencyItem( "fr_FR", "dollars2", "$2.00", 0, 0, 0, 0, "" ), new ParseCurrencyItem( "fr_FR", "dollars4", "$4", 0, 0, 0, 0, "" ), }; for (ParseCurrencyItem item: parseCurrencyItems) { String localeString = item.getLocaleString(); ULocale uloc = new ULocale(localeString); NumberFormat fmt = null; try { fmt = NumberFormat.getCurrencyInstance(uloc); } catch (Exception e) { errln("NumberFormat.getCurrencyInstance fails for locale " + localeString); continue; } String currStr = item.getCurrStr(); ParsePosition parsePos = new ParsePosition(0); Number numVal = fmt.parse(currStr, parsePos); if ( parsePos.getIndex() != item.getDoubExpectPos() || (numVal != null && numVal.intValue() != item.getDoubExpectVal()) ) { if (numVal != null) { errln("NumberFormat.getCurrencyInstance parse " + localeString + "/" + item.getDescrip() + ", expect pos/val " + item.getDoubExpectPos() + "/" + item.getDoubExpectVal() + ", get " + parsePos.getIndex() + "/" + numVal.intValue() ); } else { errln("NumberFormat.getCurrencyInstance parse " + localeString + "/" + item.getDescrip() + ", expect pos/val " + item.getDoubExpectPos() + "/" + item.getDoubExpectVal() + ", get " + parsePos.getIndex() + "/(NULL)" ); } } parsePos.setIndex(0); int curExpectPos = item.getCurExpectPos(); CurrencyAmount currAmt = fmt.parseCurrency(currStr, parsePos); if ( parsePos.getIndex() != curExpectPos || (currAmt != null && (currAmt.getNumber().intValue() != item.getCurExpectVal() || currAmt.getCurrency().getCurrencyCode().compareTo(item.getCurExpectCurr()) != 0)) ) { if (currAmt != null) { errln("NumberFormat.getCurrencyInstance parseCurrency " + localeString + "/" + item.getDescrip() + ", expect pos/val/curr " + curExpectPos + "/" + item.getCurExpectVal() + "/" + item.getCurExpectCurr() + ", get " + parsePos.getIndex() + "/" + currAmt.getNumber().intValue() + "/" + currAmt.getCurrency().getCurrencyCode() ); } else { errln("NumberFormat.getCurrencyInstance parseCurrency " + localeString + "/" + item.getDescrip() + ", expect pos/val/curr " + curExpectPos + "/" + item.getCurExpectVal() + "/" + item.getCurExpectCurr() + ", get " + parsePos.getIndex() + "/(NULL)" ); } } } } @Test public void TestParseCurrencyWithWhitespace() { DecimalFormat df = new DecimalFormat("#,##0.00 ¤¤"); ParsePosition ppos = new ParsePosition(0); df.parseCurrency("1.00 us denmark", ppos); assertEquals("Expected to fail on 'us denmark' string", 4, ppos.getErrorIndex()); } @Test public void TestParseCurrPatternWithDecStyle() { String currpat = "¤#,##0.00"; String parsetxt = "x0y$"; DecimalFormat decfmt = (DecimalFormat)NumberFormat.getInstance(new ULocale("en_US"), NumberFormat.NUMBERSTYLE); decfmt.applyPattern(currpat); ParsePosition ppos = new ParsePosition(0); Number value = decfmt.parse(parsetxt, ppos); if (ppos.getIndex() != 0) { errln("DecimalFormat.parse expected to fail but got ppos " + ppos.getIndex() + ", value " + value); } } /** * Test the Currency object handling, new as of ICU 2.2. */ @Test public void TestCurrencyObject() { NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US); expectCurrency(fmt, null, 1234.56, "$1,234.56"); expectCurrency(fmt, Currency.getInstance(Locale.FRANCE), 1234.56, "\u20AC1,234.56"); // Euro expectCurrency(fmt, Currency.getInstance(Locale.JAPAN), 1234.56, "\u00A51,235"); // Yen expectCurrency(fmt, Currency.getInstance(new Locale("fr", "CH", "")), 1234.56, "CHF 1,234.56"); // no more 0.05 rounding here, see cldrbug 5548 expectCurrency(fmt, Currency.getInstance(Locale.US), 1234.56, "$1,234.56"); fmt = NumberFormat.getCurrencyInstance(Locale.FRANCE); expectCurrency(fmt, null, 1234.56, "1\u202F234,56 \u20AC"); expectCurrency(fmt, Currency.getInstance(Locale.JAPAN), 1234.56, "1\u202F235 JPY"); // Yen expectCurrency(fmt, Currency.getInstance(new Locale("fr", "CH", "")), 1234.56, "1\u202F234,56 CHF"); // no more rounding here, see cldrbug 5548 expectCurrency(fmt, Currency.getInstance(Locale.US), 1234.56, "1\u202F234,56 $US"); expectCurrency(fmt, Currency.getInstance(Locale.FRANCE), 1234.56, "1\u202F234,56 \u20AC"); // Euro } @Test public void TestCompatibleCurrencies() { NumberFormat fmt = NumberFormat.getCurrencyInstance(Locale.US); expectParseCurrency(fmt, Currency.getInstance(Locale.JAPAN), "\u00A51,235"); // Yen half-width expectParseCurrency(fmt, Currency.getInstance(Locale.JAPAN), "\uFFE51,235"); // Yen full-wdith } @Test public void TestCurrencyPatterns() { int i; Random rnd = new Random(2017); Locale[] locs = NumberFormat.getAvailableLocales(); for (i=0; i<locs.length; ++i) { if (rnd.nextDouble() < 0.9) { // Check a random subset for speed: // Otherwise, this test takes a large fraction of the entire time. continue; } NumberFormat nf = NumberFormat.getCurrencyInstance(locs[i]); // Make sure currency formats do not have a variable number // of fraction digits int min = nf.getMinimumFractionDigits(); int max = nf.getMaximumFractionDigits(); if (min != max) { String a = nf.format(1.0); String b = nf.format(1.125); errln("FAIL: " + locs[i] + " min fraction digits != max fraction digits; "+ "x 1.0 => " + a + "; x 1.125 => " + b); } // Make sure EURO currency formats have exactly 2 fraction digits if (nf instanceof DecimalFormat) { Currency curr = ((DecimalFormat) nf).getCurrency(); if (curr != null && "EUR".equals(curr.getCurrencyCode())) { if (min != 2 || max != 2) { String a = nf.format(1.0); errln("FAIL: " + locs[i] + " is a EURO format but it does not have 2 fraction digits; "+ "x 1.0 => " + a); } } } } } /** * Do rudimentary testing of parsing. */ @Test public void TestParse() { String arg = "0.0"; DecimalFormat format = new DecimalFormat("00"); double aNumber = 0l; try { aNumber = format.parse(arg).doubleValue(); } catch (ParseException e) { System.out.println(e); } logln("parse(" + arg + ") = " + aNumber); } /** * Test proper rounding by the format method. */ @Test public void TestRounding487() { NumberFormat nf = NumberFormat.getInstance(); roundingTest(nf, 0.00159999, 4, "0.0016"); roundingTest(nf, 0.00995, 4, "0.01"); roundingTest(nf, 12.3995, 3, "12.4"); roundingTest(nf, 12.4999, 0, "12"); roundingTest(nf, - 19.5, 0, "-20"); } /** * Test the functioning of the secondary grouping value. */ @Test public void TestSecondaryGrouping() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat f = new DecimalFormat("#,##,###", US); expect(f, 123456789L, "12,34,56,789"); expectPat(f, "#,##,##0"); f.applyPattern("#,###"); f.setSecondaryGroupingSize(4); expect(f, 123456789L, "12,3456,789"); expectPat(f, "#,####,##0"); NumberFormat g = NumberFormat.getInstance(new Locale("hi", "IN")); String out = ""; long l = 1876543210L; out = g.format(l); // expect "1,87,65,43,210", but with Hindi digits // 01234567890123 boolean ok = true; if (out.length() != 14) { ok = false; } else { for (int i = 0; i < out.length(); ++i) { boolean expectGroup = false; switch (i) { case 1 : case 4 : case 7 : case 10 : expectGroup = true; break; } // Later -- fix this to get the actual grouping // character from the resource bundle. boolean isGroup = (out.charAt(i) == 0x002C); if (isGroup != expectGroup) { ok = false; break; } } } if (!ok) { errln("FAIL Expected "+ l + " x hi_IN . \"1,87,65,43,210\" (with Hindi digits), got \"" + out + "\""); } else { logln("Ok " + l + " x hi_IN . \"" + out + "\""); } } /* * Internal test utility. */ private void roundingTest(NumberFormat nf, double x, int maxFractionDigits, final String expected) { nf.setMaximumFractionDigits(maxFractionDigits); String out = nf.format(x); logln(x + " formats with " + maxFractionDigits + " fractional digits to " + out); if (!out.equals(expected)) errln("FAIL: Expected " + expected); } /** * Upgrade to alphaWorks */ @Test public void TestExponent() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt1 = new DecimalFormat("0.###E0", US); DecimalFormat fmt2 = new DecimalFormat("0.###E+0", US); int n = 1234; expect2(fmt1, n, "1.234E3"); expect2(fmt2, n, "1.234E+3"); expect(fmt1, "1.234E+3", n); // Either format should parse "E+3" } /** * Upgrade to alphaWorks */ @Test public void TestScientific() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); // Test pattern round-trip final String PAT[] = { "#E0", "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" }; int PAT_length = PAT.length; int DIGITS[] = { // min int, max int, min frac, max frac 0, 1, 0, 0, // "#E0" 1, 1, 0, 4, // "0.####E0" 2, 2, 3, 3, // "00.000E00" 1, 3, 0, 4, // "##0.####E000" 1, 1, 0, 3, // "0.###E0;[0.###E0]" }; for (int i = 0; i < PAT_length; ++i) { String pat = PAT[i]; DecimalFormat df = new DecimalFormat(pat, US); String pat2 = df.toPattern(); if (pat.equals(pat2)) { logln("Ok Pattern rt \"" + pat + "\" . \"" + pat2 + "\""); } else { errln("FAIL Pattern rt \"" + pat + "\" . \"" + pat2 + "\""); } // Make sure digit counts match what we expect if (i == 0) continue; // outputs to 1,1,0,0 since at least one min digit is required. if (df.getMinimumIntegerDigits() != DIGITS[4 * i] || df.getMaximumIntegerDigits() != DIGITS[4 * i + 1] || df.getMinimumFractionDigits() != DIGITS[4 * i + 2] || df.getMaximumFractionDigits() != DIGITS[4 * i + 3]) { errln("FAIL \""+ pat+ "\" min/max int; min/max frac = " + df.getMinimumIntegerDigits() + "/" + df.getMaximumIntegerDigits() + ";" + df.getMinimumFractionDigits() + "/" + df.getMaximumFractionDigits() + ", expect " + DIGITS[4 * i] + "/" + DIGITS[4 * i + 1] + ";" + DIGITS[4 * i + 2] + "/" + DIGITS[4 * i + 3]); } } expect2(new DecimalFormat("#E0", US), 12345.0, "1.2345E4"); expect(new DecimalFormat("0E0", US), 12345.0, "1E4"); // pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0" // so result = 1.234568E4 not 1.2345678901E4 //when the pattern problem is finalized, delete comment mark'//' //of the following code expect2(NumberFormat.getScientificInstance(Locale.US), 12345.678901, "1.2345678901E4"); logln("Testing NumberFormat.getScientificInstance(ULocale) ..."); expect2(NumberFormat.getScientificInstance(ULocale.US), 12345.678901, "1.2345678901E4"); expect(new DecimalFormat("##0.###E0", US), 12345.0, "12.34E3"); expect(new DecimalFormat("##0.###E0", US), 12345.00001, "12.35E3"); expect2(new DecimalFormat("##0.####E0", US), 12345, "12.345E3"); // pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0" // so result = 1.234568E4 not 1.2345678901E4 expect2(NumberFormat.getScientificInstance(Locale.FRANCE), 12345.678901, "1,2345678901E4"); logln("Testing NumberFormat.getScientificInstance(ULocale) ..."); expect2(NumberFormat.getScientificInstance(ULocale.FRANCE), 12345.678901, "1,2345678901E4"); expect(new DecimalFormat("##0.####E0", US), 789.12345e-9, "789.12E-9"); expect2(new DecimalFormat("##0.####E0", US), 780.e-9, "780E-9"); expect(new DecimalFormat(".###E0", US), 45678.0, ".457E5"); expect2(new DecimalFormat(".###E0", US), 0, ".0E0"); /* expect(new DecimalFormat[] { new DecimalFormat("#E0", US), new DecimalFormat("##E0", US), new DecimalFormat("####E0", US), new DecimalFormat("0E0", US), new DecimalFormat("00E0", US), new DecimalFormat("000E0", US), }, new Long(45678000), new String[] { "4.5678E7", "45.678E6", "4567.8E4", "5E7", "46E6", "457E5", } ); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("#E0", US), 45678000, "4.5678E7"); expect2(new DecimalFormat("##E0", US), 45678000, "45.678E6"); expect2(new DecimalFormat("####E0", US), 45678000, "4567.8E4"); expect(new DecimalFormat("0E0", US), 45678000, "5E7"); expect(new DecimalFormat("00E0", US), 45678000, "46E6"); expect(new DecimalFormat("000E0", US), 45678000, "457E5"); /* expect(new DecimalFormat("###E0", US, status), new Object[] { new Double(0.0000123), "12.3E-6", new Double(0.000123), "123E-6", new Double(0.00123), "1.23E-3", new Double(0.0123), "12.3E-3", new Double(0.123), "123E-3", new Double(1.23), "1.23E0", new Double(12.3), "12.3E0", new Double(123), "123E0", new Double(1230), "1.23E3", }); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("###E0", US), 0.0000123, "12.3E-6"); expect2(new DecimalFormat("###E0", US), 0.000123, "123E-6"); expect2(new DecimalFormat("###E0", US), 0.00123, "1.23E-3"); expect2(new DecimalFormat("###E0", US), 0.0123, "12.3E-3"); expect2(new DecimalFormat("###E0", US), 0.123, "123E-3"); expect2(new DecimalFormat("###E0", US), 1.23, "1.23E0"); expect2(new DecimalFormat("###E0", US), 12.3, "12.3E0"); expect2(new DecimalFormat("###E0", US), 123.0, "123E0"); expect2(new DecimalFormat("###E0", US), 1230.0, "1.23E3"); /* expect(new DecimalFormat("0.#E+00", US, status), new Object[] { new Double(0.00012), "1.2E-04", new Long(12000), "1.2E+04", }); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("0.#E+00", US), 0.00012, "1.2E-04"); expect2(new DecimalFormat("0.#E+00", US), 12000, "1.2E+04"); } /** * Upgrade to alphaWorks */ @Test public void TestPad() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); expect2(new DecimalFormat("*^##.##", US), 0, "^^^^0"); expect2(new DecimalFormat("*^##.##", US), -1.3, "^-1.3"); expect2( new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US), 0, "0.0E0______ g-m/s^2"); expect( new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US), 1.0 / 3, "333.333E-3_ g-m/s^2"); expect2(new DecimalFormat("##0.0####*_ 'g-m/s^2'", US), 0, "0.0______ g-m/s^2"); expect( new DecimalFormat("##0.0####*_ 'g-m/s^2'", US), 1.0 / 3, "0.33333__ g-m/s^2"); // Test padding before a sign final String formatStr = "*x#,###,###,##0.0#;*x(###,###,##0.0#)"; expect2(new DecimalFormat(formatStr, US), -10, "xxxxxxxxxx(10.0)"); expect2(new DecimalFormat(formatStr, US), -1000, "xxxxxxx(1,000.0)"); expect2(new DecimalFormat(formatStr, US), -1000000, "xxx(1,000,000.0)"); expect2(new DecimalFormat(formatStr, US), -100.37, "xxxxxxxx(100.37)"); expect2(new DecimalFormat(formatStr, US), -10456.37, "xxxxx(10,456.37)"); expect2(new DecimalFormat(formatStr, US), -1120456.37, "xx(1,120,456.37)"); expect2(new DecimalFormat(formatStr, US), -112045600.37, "(112,045,600.37)"); expect2(new DecimalFormat(formatStr, US), -1252045600.37, "(1,252,045,600.37)"); expect2(new DecimalFormat(formatStr, US), 10, "xxxxxxxxxxxx10.0"); expect2(new DecimalFormat(formatStr, US), 1000, "xxxxxxxxx1,000.0"); expect2(new DecimalFormat(formatStr, US), 1000000, "xxxxx1,000,000.0"); expect2(new DecimalFormat(formatStr, US), 100.37, "xxxxxxxxxx100.37"); expect2(new DecimalFormat(formatStr, US), 10456.37, "xxxxxxx10,456.37"); expect2(new DecimalFormat(formatStr, US), 1120456.37, "xxxx1,120,456.37"); expect2(new DecimalFormat(formatStr, US), 112045600.37, "xx112,045,600.37"); expect2(new DecimalFormat(formatStr, US), 10252045600.37, "10,252,045,600.37"); // Test padding between a sign and a number final String formatStr2 = "#,###,###,##0.0#*x;(###,###,##0.0#*x)"; expect2(new DecimalFormat(formatStr2, US), -10, "(10.0xxxxxxxxxx)"); expect2(new DecimalFormat(formatStr2, US), -1000, "(1,000.0xxxxxxx)"); expect2(new DecimalFormat(formatStr2, US), -1000000, "(1,000,000.0xxx)"); expect2(new DecimalFormat(formatStr2, US), -100.37, "(100.37xxxxxxxx)"); expect2(new DecimalFormat(formatStr2, US), -10456.37, "(10,456.37xxxxx)"); expect2(new DecimalFormat(formatStr2, US), -1120456.37, "(1,120,456.37xx)"); expect2(new DecimalFormat(formatStr2, US), -112045600.37, "(112,045,600.37)"); expect2(new DecimalFormat(formatStr2, US), -1252045600.37, "(1,252,045,600.37)"); expect2(new DecimalFormat(formatStr2, US), 10, "10.0xxxxxxxxxxxx"); expect2(new DecimalFormat(formatStr2, US), 1000, "1,000.0xxxxxxxxx"); expect2(new DecimalFormat(formatStr2, US), 1000000, "1,000,000.0xxxxx"); expect2(new DecimalFormat(formatStr2, US), 100.37, "100.37xxxxxxxxxx"); expect2(new DecimalFormat(formatStr2, US), 10456.37, "10,456.37xxxxxxx"); expect2(new DecimalFormat(formatStr2, US), 1120456.37, "1,120,456.37xxxx"); expect2(new DecimalFormat(formatStr2, US), 112045600.37, "112,045,600.37xx"); expect2(new DecimalFormat(formatStr2, US), 10252045600.37, "10,252,045,600.37"); //testing the setPadCharacter(UnicodeString) and getPadCharacterString() DecimalFormat fmt = new DecimalFormat("#", US); char padString = 'P'; fmt.setPadCharacter(padString); expectPad(fmt, "*P##.##", DecimalFormat.PAD_BEFORE_PREFIX, 5, padString); fmt.setPadCharacter('^'); expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, '^'); //commented untill implementation is complete /* fmt.setPadCharacter((UnicodeString)"^^^"); expectPad(fmt, "*^^^#", DecimalFormat.kPadBeforePrefix, 3, (UnicodeString)"^^^"); padString.remove(); padString.append((UChar)0x0061); padString.append((UChar)0x0302); fmt.setPadCharacter(padString); UChar patternChars[]={0x002a, 0x0061, 0x0302, 0x0061, 0x0302, 0x0023, 0x0000}; UnicodeString pattern(patternChars); expectPad(fmt, pattern , DecimalFormat.kPadBeforePrefix, 4, padString); */ // Test multi-char padding sequence specified via pattern expect2(new DecimalFormat("*'😃'####.00", US), 1.1, "😃😃😃1.10"); } /** * Upgrade to alphaWorks */ @Test public void TestPatterns2() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt = new DecimalFormat("#", US); char hat = 0x005E; /*^*/ expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, hat); expectPad(fmt, "$*^#", DecimalFormat.PAD_AFTER_PREFIX, 2, hat); expectPad(fmt, "#*^", DecimalFormat.PAD_BEFORE_SUFFIX, 1, hat); expectPad(fmt, "#$*^", DecimalFormat.PAD_AFTER_SUFFIX, 2, hat); expectPad(fmt, "$*^$#", -1); expectPad(fmt, "#$*^$", -1); expectPad(fmt, "'pre'#,##0*x'post'", DecimalFormat.PAD_BEFORE_SUFFIX, 12, (char) 0x0078 /*x*/); expectPad(fmt, "''#0*x", DecimalFormat.PAD_BEFORE_SUFFIX, 3, (char) 0x0078 /*x*/); expectPad(fmt, "'I''ll'*a###.##", DecimalFormat.PAD_AFTER_PREFIX, 10, (char) 0x0061 /*a*/); fmt.applyPattern("AA#,##0.00ZZ"); fmt.setPadCharacter(hat); fmt.setFormatWidth(10); fmt.setPadPosition(DecimalFormat.PAD_BEFORE_PREFIX); expectPat(fmt, "*^AA#,##0.00ZZ"); fmt.setPadPosition(DecimalFormat.PAD_BEFORE_SUFFIX); expectPat(fmt, "AA#,##0.00*^ZZ"); fmt.setPadPosition(DecimalFormat.PAD_AFTER_SUFFIX); expectPat(fmt, "AA#,##0.00ZZ*^"); // 12 3456789012 String exp = "AA*^#,##0.00ZZ"; fmt.setFormatWidth(12); fmt.setPadPosition(DecimalFormat.PAD_AFTER_PREFIX); expectPat(fmt, exp); fmt.setFormatWidth(13); // 12 34567890123 expectPat(fmt, "AA*^##,##0.00ZZ"); fmt.setFormatWidth(14); // 12 345678901234 expectPat(fmt, "AA*^###,##0.00ZZ"); fmt.setFormatWidth(15); // 12 3456789012345 expectPat(fmt, "AA*^####,##0.00ZZ"); // This is the interesting case // The new implementation produces "AA*^#####,##0.00ZZ", which is functionally equivalent // to what the old implementation produced, "AA*^#,###,##0.00ZZ" fmt.setFormatWidth(16); // 12 34567890123456 //expectPat(fmt, "AA*^#,###,##0.00ZZ"); expectPat(fmt, "AA*^#####,##0.00ZZ"); } @Test public void TestRegistration() { final ULocale SRC_LOC = ULocale.FRANCE; final ULocale SWAP_LOC = ULocale.US; class TestFactory extends SimpleNumberFormatFactory { NumberFormat currencyStyle; TestFactory() { super(SRC_LOC, true); currencyStyle = NumberFormat.getIntegerInstance(SWAP_LOC); } @Override public NumberFormat createFormat(ULocale loc, int formatType) { if (formatType == FORMAT_CURRENCY) { return currencyStyle; } return null; } } NumberFormat f0 = NumberFormat.getIntegerInstance(SWAP_LOC); NumberFormat f1 = NumberFormat.getIntegerInstance(SRC_LOC); NumberFormat f2 = NumberFormat.getCurrencyInstance(SRC_LOC); Object key = NumberFormat.registerFactory(new TestFactory()); NumberFormat f3 = NumberFormat.getCurrencyInstance(SRC_LOC); NumberFormat f4 = NumberFormat.getIntegerInstance(SRC_LOC); NumberFormat.unregister(key); // restore for other tests NumberFormat f5 = NumberFormat.getCurrencyInstance(SRC_LOC); float n = 1234.567f; logln("f0 swap int: " + f0.format(n)); logln("f1 src int: " + f1.format(n)); logln("f2 src cur: " + f2.format(n)); logln("f3 reg cur: " + f3.format(n)); logln("f4 reg int: " + f4.format(n)); logln("f5 unreg cur: " + f5.format(n)); if (!f3.format(n).equals(f0.format(n))) { errln("registered service did not match"); } if (!f4.format(n).equals(f1.format(n))) { errln("registered service did not inherit"); } if (!f5.format(n).equals(f2.format(n))) { errln("unregistered service did not match original"); } } @Test public void TestScientific2() { // jb 2552 DecimalFormat fmt = (DecimalFormat)NumberFormat.getCurrencyInstance(); Number num = new Double(12.34); expect(fmt, num, "$12.34"); fmt.setScientificNotation(true); expect(fmt, num, "$1.23E1"); fmt.setScientificNotation(false); expect(fmt, num, "$12.34"); } @Test public void TestScientificGrouping() { // jb 2552 DecimalFormat fmt = new DecimalFormat("###.##E0"); expect(fmt, .01234, "12.3E-3"); expect(fmt, .1234, "123E-3"); expect(fmt, 1.234, "1.23E0"); expect(fmt, 12.34, "12.3E0"); expect(fmt, 123.4, "123E0"); expect(fmt, 1234, "1.23E3"); } // additional coverage tests // sigh, can't have static inner classes, why not? static final class PI extends Number { /** * For serialization */ private static final long serialVersionUID = -305601227915602172L; private PI() {} @Override public int intValue() { return (int)Math.PI; } @Override public long longValue() { return (long)Math.PI; } @Override public float floatValue() { return (float)Math.PI; } @Override public double doubleValue() { return Math.PI; } @Override public byte byteValue() { return (byte)Math.PI; } @Override public short shortValue() { return (short)Math.PI; } public static final Number INSTANCE = new PI(); } @Test public void TestCoverage() { NumberFormat fmt = NumberFormat.getNumberInstance(); // default locale logln(fmt.format(new BigInteger("1234567890987654321234567890987654321", 10))); fmt = NumberFormat.getScientificInstance(); // default locale logln(fmt.format(PI.INSTANCE)); try { logln(fmt.format("12345")); errln("numberformat of string did not throw exception"); } catch (Exception e) { logln("PASS: numberformat of string failed as expected"); } int hash = fmt.hashCode(); logln("hash code " + hash); logln("compare to string returns: " + fmt.equals("")); // For ICU 2.6 - alan DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat df = new DecimalFormat("'*&'' '\u00A4' ''&*' #,##0.00", US); df.setCurrency(Currency.getInstance("INR")); expect2(df, 1.0, "*&' \u20B9 '&* 1.00"); expect2(df, -2.0, "-*&' \u20B9 '&* 2.00"); df.applyPattern("#,##0.00 '*&'' '\u00A4' ''&*'"); expect2(df, 2.0, "2.00 *&' \u20B9 '&*"); expect2(df, -1.0, "-1.00 *&' \u20B9 '&*"); java.math.BigDecimal r; r = df.getRoundingIncrement(); if (r != null) { errln("FAIL: rounding = " + r + ", expect null"); } if (df.isScientificNotation()) { errln("FAIL: isScientificNotation = true, expect false"); } // Create a new instance to flush out currency info df = new DecimalFormat("0.00000", US); df.setScientificNotation(true); if (!df.isScientificNotation()) { errln("FAIL: isScientificNotation = false, expect true"); } df.setMinimumExponentDigits((byte)2); if (df.getMinimumExponentDigits() != 2) { errln("FAIL: getMinimumExponentDigits = " + df.getMinimumExponentDigits() + ", expect 2"); } df.setExponentSignAlwaysShown(true); if (!df.isExponentSignAlwaysShown()) { errln("FAIL: isExponentSignAlwaysShown = false, expect true"); } df.setSecondaryGroupingSize(0); if (df.getSecondaryGroupingSize() != 0) { errln("FAIL: getSecondaryGroupingSize = " + df.getSecondaryGroupingSize() + ", expect 0"); } expect2(df, 3.14159, "3.14159E+00"); // DecimalFormatSymbols#getInstance DecimalFormatSymbols decsym1 = DecimalFormatSymbols.getInstance(); DecimalFormatSymbols decsym2 = new DecimalFormatSymbols(); if (!decsym1.equals(decsym2)) { errln("FAIL: DecimalFormatSymbols returned by getInstance()" + "does not match new DecimalFormatSymbols()."); } decsym1 = DecimalFormatSymbols.getInstance(Locale.JAPAN); decsym2 = DecimalFormatSymbols.getInstance(ULocale.JAPAN); if (!decsym1.equals(decsym2)) { errln("FAIL: DecimalFormatSymbols returned by getInstance(Locale.JAPAN)" + "does not match the one returned by getInstance(ULocale.JAPAN)."); } // DecimalFormatSymbols#getAvailableLocales/#getAvailableULocales Locale[] allLocales = DecimalFormatSymbols.getAvailableLocales(); if (allLocales.length == 0) { errln("FAIL: Got a empty list for DecimalFormatSymbols.getAvailableLocales"); } else { logln("PASS: " + allLocales.length + " available locales returned by DecimalFormatSymbols.getAvailableLocales"); } ULocale[] allULocales = DecimalFormatSymbols.getAvailableULocales(); if (allULocales.length == 0) { errln("FAIL: Got a empty list for DecimalFormatSymbols.getAvailableLocales"); } else { logln("PASS: " + allULocales.length + " available locales returned by DecimalFormatSymbols.getAvailableULocales"); } } @Test public void TestLocalizedPatternSymbolCoverage() { String[] standardPatterns = { "#,##0.05+%;#,##0.05-%", "* @@@E0‰" }; String[] standardPatterns58 = { "#,##0.05+%;#,##0.05-%", "* @@@E0‰;* -@@@E0‰" }; String[] localizedPatterns = { "▰⁖▰▰໐⁘໐໕†⁜⁙▰⁖▰▰໐⁘໐໕‡⁜", "⁂ ⁕⁕⁕⁑⁑໐‱" }; String[] localizedPatterns58 = { "▰⁖▰▰໐⁘໐໕+⁜⁙▰⁖▰▰໐⁘໐໕‡⁜", "⁂ ⁕⁕⁕⁑⁑໐‱⁙⁂ ‡⁕⁕⁕⁑⁑໐‱" }; DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setGroupingSeparator('⁖'); dfs.setDecimalSeparator('⁘'); dfs.setPatternSeparator('⁙'); dfs.setDigit('▰'); dfs.setZeroDigit('໐'); dfs.setSignificantDigit('⁕'); dfs.setPlusSign('†'); dfs.setMinusSign('‡'); dfs.setPercent('⁜'); dfs.setPerMill('‱'); dfs.setExponentSeparator("⁑⁑"); // tests multi-char sequence dfs.setPadEscape('⁂'); for (int i=0; i<2; i++) { String standardPattern = standardPatterns[i]; String standardPattern58 = standardPatterns58[i]; String localizedPattern = localizedPatterns[i]; String localizedPattern58 = localizedPatterns58[i]; DecimalFormat df1 = new DecimalFormat("#", dfs); df1.applyPattern(standardPattern); DecimalFormat df2 = new DecimalFormat("#", dfs); df2.applyLocalizedPattern(localizedPattern); assertEquals("DecimalFormat instances should be equal", df1, df2); assertEquals("toPattern should match on localizedPattern instance", standardPattern, df2.toPattern()); assertEquals("toLocalizedPattern should match on standardPattern instance", localizedPattern, df1.toLocalizedPattern()); // Android can't access DecimalFormat_ICU58 for testing (ticket #13283). if (TestUtil.getJavaVendor() == TestUtil.JavaVendor.Android) continue; // Note: ICU 58 does not support plus signs in patterns // Note: ICU 58 always prints the negative part of scientific notation patterns, // even when the negative part is not necessary DecimalFormat_ICU58 df3 = new DecimalFormat_ICU58("#", dfs); df3.applyPattern(standardPattern); // Reading standardPattern is OK DecimalFormat_ICU58 df4 = new DecimalFormat_ICU58("#", dfs); df4.applyLocalizedPattern(localizedPattern58); // Note: DecimalFormat#equals() is broken on ICU 58 assertEquals("toPattern should match on ICU58 localizedPattern instance", standardPattern58, df4.toPattern()); assertEquals("toLocalizedPattern should match on ICU58 standardPattern instance", localizedPattern58, df3.toLocalizedPattern()); } } @Test public void TestParseNull() throws ParseException { DecimalFormat df = new DecimalFormat(); try { df.parse(null); fail("df.parse(null) didn't throw an exception"); } catch (IllegalArgumentException e){} try { df.parse(null, null); fail("df.parse(null) didn't throw an exception"); } catch (IllegalArgumentException e){} try { df.parseCurrency(null, null); fail("df.parse(null) didn't throw an exception"); } catch (IllegalArgumentException e){} } @Test public void TestWhiteSpaceParsing() { DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt = new DecimalFormat("a b#0c ", US); int n = 1234; expect(fmt, "a b1234c ", n); expect(fmt, "a b1234c ", n); expect(fmt, "ab1234", n); fmt.applyPattern("a b #"); expect(fmt, "ab1234", n); expect(fmt, "ab 1234", n); expect(fmt, "a b1234", n); expect(fmt, "a b1234", n); expect(fmt, " a b 1234", n); // Horizontal whitespace is allowed, but not vertical whitespace. expect(fmt, "\ta\u00A0b\u20001234", n); expect(fmt, "a \u200A b1234", n); expectParseException(fmt, "\nab1234", n); expectParseException(fmt, "a \n b1234", n); expectParseException(fmt, "a \u0085 b1234", n); expectParseException(fmt, "a \u2028 b1234", n); // Test all characters in the UTS 18 "blank" set stated in the API docstring. UnicodeSet blanks = new UnicodeSet("[[:Zs:][\\u0009]]").freeze(); for (String space : blanks) { String str = "a " + space + " b1234c "; expect(fmt, str, n); } // Arbitrary whitespace is not accepted in strict mode. fmt.setParseStrict(true); for (String space : blanks) { String str = "a " + space + " b1234c "; expectParseException(fmt, str, n); } // Test default ignorable characters. These should work in both lenient and strict. UnicodeSet defaultIgnorables = new UnicodeSet("[[:Bidi_Control:]]").freeze(); fmt.setParseStrict(false); for (String ignorable : defaultIgnorables) { String str = "a b " + ignorable + "1234c "; expect(fmt, str, n); } fmt.setParseStrict(true); for (String ignorable : defaultIgnorables) { String str = "a b " + ignorable + "1234c "; expect(fmt, str, n); } // Test that other whitespace characters do not work fmt.setParseStrict(false); UnicodeSet otherWhitespace = new UnicodeSet("[[:whitespace:]]").removeAll(blanks).freeze(); for (String space : otherWhitespace) { String str = "a " + space + " b1234"; expectParseException(fmt, str, n); } } /** * Test currencies whose display name is a ChoiceFormat. */ @Test public void TestComplexCurrency() { // CLDR No Longer uses complex currency symbols. // Skipping this test. // Locale loc = new Locale("kn", "IN", ""); // NumberFormat fmt = NumberFormat.getCurrencyInstance(loc); // expect2(fmt, 1.0, "Re.\u00a01.00"); // expect(fmt, 1.001, "Re.\u00a01.00"); // tricky // expect2(fmt, 12345678.0, "Rs.\u00a01,23,45,678.00"); // expect2(fmt, 0.5, "Rs.\u00a00.50"); // expect2(fmt, -1.0, "-Re.\u00a01.00"); // expect2(fmt, -10.0, "-Rs.\u00a010.00"); } @Test public void TestCurrencyKeyword() { ULocale locale = new ULocale("th_TH@currency=QQQ"); NumberFormat format = NumberFormat.getCurrencyInstance(locale); String result = format.format(12.34f); if (!"QQQ 12.34".equals(result)) { errln("got unexpected currency: " + result); } } /** * Test alternate numbering systems */ @Test public void TestNumberingSystems() { class TestNumberingSystemItem { private final String localeName; private final double value; private final boolean isRBNF; private final String expectedResult; TestNumberingSystemItem(String loc, double val, boolean rbnf, String exp) { localeName = loc; value = val; isRBNF = rbnf; expectedResult = exp; } } final TestNumberingSystemItem[] DATA = { new TestNumberingSystemItem( "en_US@numbers=thai", 1234.567, false, "\u0e51,\u0e52\u0e53\u0e54.\u0e55\u0e56\u0e57" ), new TestNumberingSystemItem( "en_US@numbers=thai", 1234.567, false, "\u0E51,\u0E52\u0E53\u0E54.\u0E55\u0E56\u0E57" ), new TestNumberingSystemItem( "en_US@numbers=hebr", 5678.0, true, "\u05D4\u05F3\u05EA\u05E8\u05E2\u05F4\u05D7" ), new TestNumberingSystemItem( "en_US@numbers=arabext", 1234.567, false, "\u06F1\u066c\u06F2\u06F3\u06F4\u066b\u06F5\u06F6\u06F7" ), new TestNumberingSystemItem( "de_DE@numbers=foobar", 1234.567, false, "1.234,567" ), new TestNumberingSystemItem( "ar_EG", 1234.567, false, "\u0661\u066c\u0662\u0663\u0664\u066b\u0665\u0666\u0667" ), new TestNumberingSystemItem( "th_TH@numbers=traditional", 1234.567, false, "\u0E51,\u0E52\u0E53\u0E54.\u0E55\u0E56\u0E57" ), // fall back to native per TR35 new TestNumberingSystemItem( "ar_MA", 1234.567, false, "1.234,567" ), new TestNumberingSystemItem( "en_US@numbers=hanidec", 1234.567, false, "\u4e00,\u4e8c\u4e09\u56db.\u4e94\u516d\u4e03" ), new TestNumberingSystemItem( "ta_IN@numbers=native", 1234.567, false, "\u0BE7,\u0BE8\u0BE9\u0BEA.\u0BEB\u0BEC\u0BED" ), new TestNumberingSystemItem( "ta_IN@numbers=traditional", 1235.0, true, "\u0BF2\u0BE8\u0BF1\u0BE9\u0BF0\u0BEB" ), new TestNumberingSystemItem( "ta_IN@numbers=finance", 1234.567, false, "1,234.567" ), // fall back to default per TR35 new TestNumberingSystemItem( "zh_TW@numbers=native", 1234.567, false, "\u4e00,\u4e8c\u4e09\u56db.\u4e94\u516d\u4e03" ), new TestNumberingSystemItem( "zh_TW@numbers=traditional", 1234.567, true, "\u4E00\u5343\u4E8C\u767E\u4E09\u5341\u56DB\u9EDE\u4E94\u516D\u4E03" ), new TestNumberingSystemItem( "zh_TW@numbers=finance", 1234.567, true, "\u58F9\u4EDF\u8CB3\u4F70\u53C3\u62FE\u8086\u9EDE\u4F0D\u9678\u67D2" ), new TestNumberingSystemItem( "en_US@numbers=mathsanb", 1234.567, false, "𝟭,𝟮𝟯𝟰.𝟱𝟲𝟳" ), // ticket #13286 }; for (TestNumberingSystemItem item : DATA) { ULocale loc = new ULocale(item.localeName); NumberFormat fmt = NumberFormat.getInstance(loc); if (item.isRBNF) { expect3(fmt,item.value,item.expectedResult); } else { expect2(fmt,item.value,item.expectedResult); } } } // Coverage tests for methods not being called otherwise. @Test public void TestNumberingSystemCoverage() { // Test getAvaliableNames String[] availableNames = NumberingSystem.getAvailableNames(); if (availableNames == null || availableNames.length <= 0) { errln("ERROR: NumberingSystem.getAvailableNames() returned a null or empty array."); } else { boolean latnFound = false; for (String name : availableNames){ if ("latn".equals(name)) { latnFound = true; break; } } if (!latnFound) { errln("ERROR: 'latn' numbering system not found on NumberingSystem.getAvailableNames()."); } } // Test NumberingSystem.getInstance() NumberingSystem ns1 = NumberingSystem.getInstance(); if (ns1 == null || ns1.isAlgorithmic()) { errln("ERROR: NumberingSystem.getInstance() returned a null or invalid NumberingSystem"); } // Test NumberingSystem.getInstance(int,boolean,String) /* Parameters used: the ones used in the default constructor * radix = 10; * algorithmic = false; * desc = "0123456789"; */ NumberingSystem ns2 = NumberingSystem.getInstance(10, false, "0123456789"); if (ns2 == null || ns2.isAlgorithmic()) { errln("ERROR: NumberingSystem.getInstance(int,boolean,String) returned a null or invalid NumberingSystem"); } // Test NumberingSystem.getInstance(Locale) NumberingSystem ns3 = NumberingSystem.getInstance(Locale.ENGLISH); if (ns3 == null || ns3.isAlgorithmic()) { errln("ERROR: NumberingSystem.getInstance(Locale) returned a null or invalid NumberingSystem"); } } @Test public void Test6816() { Currency cur1 = Currency.getInstance(new Locale("und", "PH")); NumberFormat nfmt = NumberFormat.getCurrencyInstance(new Locale("und", "PH")); DecimalFormatSymbols decsym = ((DecimalFormat)nfmt).getDecimalFormatSymbols(); Currency cur2 = decsym.getCurrency(); if ( !cur1.getCurrencyCode().equals("PHP") || !cur2.getCurrencyCode().equals("PHP")) { errln("FAIL: Currencies should match PHP: cur1 = "+cur1.getCurrencyCode()+"; cur2 = "+cur2.getCurrencyCode()); } } @Test public void TestThreadedFormat() { class FormatTask implements Runnable { DecimalFormat fmt; StringBuffer buf; boolean inc; float num; FormatTask(DecimalFormat fmt, int index) { this.fmt = fmt; this.buf = new StringBuffer(); this.inc = (index & 0x1) == 0; this.num = inc ? 0 : 10000; } @Override public void run() { if (inc) { while (num < 10000) { buf.append(fmt.format(num) + "\n"); num += 3.14159; } } else { while (num > 0) { buf.append(fmt.format(num) + "\n"); num -= 3.14159; } } } String result() { return buf.toString(); } } DecimalFormat fmt = new DecimalFormat("0.####"); FormatTask[] tasks = new FormatTask[8]; for (int i = 0; i < tasks.length; ++i) { tasks[i] = new FormatTask(fmt, i); } TestUtil.runUntilDone(tasks); for (int i = 2; i < tasks.length; i++) { String str1 = tasks[i].result(); String str2 = tasks[i-2].result(); if (!str1.equals(str2)) { System.out.println("mismatch at " + i); System.out.println(str1); System.out.println(str2); errln("decimal format thread mismatch"); break; } str1 = str2; } } @Test public void TestPerMill() { DecimalFormat fmt = new DecimalFormat("###.###\u2030"); assertEquals("0.4857 x ###.###\u2030", "485.7\u2030", fmt.format(0.4857)); DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.ENGLISH); sym.setPerMill('m'); DecimalFormat fmt2 = new DecimalFormat("", sym); fmt2.applyLocalizedPattern("###.###m"); assertEquals("0.4857 x ###.###m", "485.7m", fmt2.format(0.4857)); } @Test public void TestIllegalPatterns() { // Test cases: // Prefix with "-:" for illegal patterns // Prefix with "+:" for legal patterns String DATA[] = { // Unquoted special characters in the suffix are illegal "-:000.000|###", "+:000.000'|###'", }; for (int i=0; i<DATA.length; ++i) { String pat=DATA[i]; boolean valid = pat.charAt(0) == '+'; pat = pat.substring(2); Exception e = null; try { // locale doesn't matter here new DecimalFormat(pat); } catch (IllegalArgumentException e1) { e = e1; } catch (IndexOutOfBoundsException e1) { e = e1; } String msg = (e==null) ? "success" : e.getMessage(); if ((e==null) == valid) { logln("Ok: pattern \"" + pat + "\": " + msg); } else { errln("FAIL: pattern \"" + pat + "\" should have " + (valid?"succeeded":"failed") + "; got " + msg); } } } /** * Parse a CurrencyAmount using the given NumberFormat, with * the 'delim' character separating the number and the currency. */ private static CurrencyAmount parseCurrencyAmount(String str, NumberFormat fmt, char delim) throws ParseException { int i = str.indexOf(delim); return new CurrencyAmount(fmt.parse(str.substring(0,i)), Currency.getInstance(str.substring(i+1))); } /** * Return an integer representing the next token from this * iterator. The integer will be an index into the given list, or * -1 if there are no more tokens, or -2 if the token is not on * the list. */ private static int keywordIndex(String tok) { for (int i=0; i<KEYWORDS.length; ++i) { if (tok.equals(KEYWORDS[i])) { return i; } } return -1; } private static final String KEYWORDS[] = { /*0*/ "ref=", // <reference pattern to parse numbers> /*1*/ "loc=", // <locale for formats> /*2*/ "f:", // <pattern or '-'> <number> <exp. string> /*3*/ "fp:", // <pattern or '-'> <number> <exp. string> <exp. number> /*4*/ "rt:", // <pattern or '-'> <(exp.) number> <(exp.) string> /*5*/ "p:", // <pattern or '-'> <string> <exp. number> /*6*/ "perr:", // <pattern or '-'> <invalid string> /*7*/ "pat:", // <pattern or '-'> <exp. toPattern or '-' or 'err'> /*8*/ "fpc:", // <loc or '-'> <curr.amt> <exp. string> <exp. curr.amt> /*9*/ "strict=", // true or false }; @SuppressWarnings("resource") // InputStream is will be closed by the ResourceReader. @Test public void TestCases() { String caseFileName = "NumberFormatTestCases.txt"; java.io.InputStream is = NumberFormatTest.class.getResourceAsStream(caseFileName); ResourceReader reader = new ResourceReader(is, caseFileName, "utf-8"); TokenIterator tokens = new TokenIterator(reader); Locale loc = new Locale("en", "US", ""); DecimalFormat ref = null, fmt = null; MeasureFormat mfmt = null; String pat = null, str = null, mloc = null; boolean strict = false; try { for (;;) { String tok = tokens.next(); if (tok == null) { break; } String where = "(" + tokens.getLineNumber() + ") "; int cmd = keywordIndex(tok); switch (cmd) { case 0: // ref= <reference pattern> ref = new DecimalFormat(tokens.next(), new DecimalFormatSymbols(Locale.US)); ref.setParseStrict(strict); logln("Setting reference pattern to:\t" + ref); break; case 1: // loc= <locale> loc = LocaleUtility.getLocaleFromName(tokens.next()); pat = ((DecimalFormat) NumberFormat.getInstance(loc)).toPattern(); logln("Setting locale to:\t" + loc + ", \tand pattern to:\t" + pat); break; case 2: // f: case 3: // fp: case 4: // rt: case 5: // p: tok = tokens.next(); if (!tok.equals("-")) { pat = tok; } try { fmt = new DecimalFormat(pat, new DecimalFormatSymbols(loc)); fmt.setParseStrict(strict); } catch (IllegalArgumentException iae) { errln(where + "Pattern \"" + pat + '"'); iae.printStackTrace(); tokens.next(); // consume remaining tokens //tokens.next(); if (cmd == 3) tokens.next(); continue; } str = null; try { if (cmd == 2 || cmd == 3 || cmd == 4) { // f: <pattern or '-'> <number> <exp. string> // fp: <pattern or '-'> <number> <exp. string> <exp. number> // rt: <pattern or '-'> <number> <string> String num = tokens.next(); str = tokens.next(); Number n = ref.parse(num); assertEquals(where + '"' + pat + "\".format(" + num + ")", str, fmt.format(n)); if (cmd == 3) { // fp: n = ref.parse(tokens.next()); } if (cmd != 2) { // != f: assertEquals(where + '"' + pat + "\".parse(\"" + str + "\")", n, fmt.parse(str)); } } // p: <pattern or '-'> <string to parse> <exp. number> else { str = tokens.next(); String expstr = tokens.next(); Number parsed = fmt.parse(str); Number exp = ref.parse(expstr); assertEquals(where + '"' + pat + "\".parse(\"" + str + "\")", exp, parsed); } } catch (ParseException e) { errln(where + '"' + pat + "\".parse(\"" + str + "\") threw an exception"); e.printStackTrace(); } break; case 6: // perr: <pattern or '-'> <invalid string> errln("Under construction"); return; case 7: // pat: <pattern> <exp. toPattern, or '-' or 'err'> String testpat = tokens.next(); String exppat = tokens.next(); boolean err = exppat.equals("err"); if (testpat.equals("-")) { if (err) { errln("Invalid command \"pat: - err\" at " + tokens.describePosition()); continue; } testpat = pat; } if (exppat.equals("-")) exppat = testpat; try { DecimalFormat f = null; if (testpat == pat) { // [sic] f = fmt; } else { f = new DecimalFormat(testpat); f.setParseStrict(strict); } if (err) { errln(where + "Invalid pattern \"" + testpat + "\" was accepted"); } else { assertEquals(where + '"' + testpat + "\".toPattern()", exppat, f.toPattern()); } } catch (IllegalArgumentException iae2) { if (err) { logln("Ok: " + where + "Invalid pattern \"" + testpat + "\" threw an exception"); } else { errln(where + "Valid pattern \"" + testpat + "\" threw an exception"); iae2.printStackTrace(); } } break; case 8: // fpc: tok = tokens.next(); if (!tok.equals("-")) { mloc = tok; ULocale l = new ULocale(mloc); try { mfmt = MeasureFormat.getCurrencyFormat(l); } catch (IllegalArgumentException iae) { errln(where + "Loc \"" + tok + '"'); iae.printStackTrace(); tokens.next(); // consume remaining tokens tokens.next(); tokens.next(); continue; } } str = null; try { // fpc: <loc or '-'> <curr.amt> <exp. string> <exp. curr.amt> String currAmt = tokens.next(); str = tokens.next(); CurrencyAmount target = parseCurrencyAmount(currAmt, ref, '/'); String formatResult = mfmt.format(target); assertEquals(where + "getCurrencyFormat(" + mloc + ").format(" + currAmt + ")", str, formatResult); target = parseCurrencyAmount(tokens.next(), ref, '/'); CurrencyAmount parseResult = (CurrencyAmount) mfmt.parseObject(str); assertEquals(where + "getCurrencyFormat(" + mloc + ").parse(\"" + str + "\")", target, parseResult); } catch (ParseException e) { errln(where + '"' + pat + "\".parse(\"" + str + "\") threw an exception"); e.printStackTrace(); } break; case 9: // strict= true or false strict = "true".equalsIgnoreCase(tokens.next()); logln("Setting strict to:\t" + strict); break; case -1: errln("Unknown command \"" + tok + "\" at " + tokens.describePosition()); return; } } } catch (java.io.IOException e) { throw new RuntimeException(e); } finally { try { reader.close(); } catch (IOException ignored) { } } } @Test public void TestFieldPositionDecimal() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); nf.setPositivePrefix("FOO"); nf.setPositiveSuffix("BA"); StringBuffer buffer = new StringBuffer(); FieldPosition fp = new FieldPosition(NumberFormat.Field.DECIMAL_SEPARATOR); nf.format(35.47, buffer, fp); assertEquals("35.47", "FOO35.47BA", buffer.toString()); assertEquals("fp begin", 5, fp.getBeginIndex()); assertEquals("fp end", 6, fp.getEndIndex()); } @Test public void TestFieldPositionInteger() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); nf.setPositivePrefix("FOO"); nf.setPositiveSuffix("BA"); StringBuffer buffer = new StringBuffer(); FieldPosition fp = new FieldPosition(NumberFormat.Field.INTEGER); nf.format(35.47, buffer, fp); assertEquals("35.47", "FOO35.47BA", buffer.toString()); assertEquals("fp begin", 3, fp.getBeginIndex()); assertEquals("fp end", 5, fp.getEndIndex()); } @Test public void TestFieldPositionFractionButInteger() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); nf.setPositivePrefix("FOO"); nf.setPositiveSuffix("BA"); StringBuffer buffer = new StringBuffer(); FieldPosition fp = new FieldPosition(NumberFormat.Field.FRACTION); nf.format(35, buffer, fp); assertEquals("35", "FOO35BA", buffer.toString()); assertEquals("fp begin", 5, fp.getBeginIndex()); assertEquals("fp end", 5, fp.getEndIndex()); } @Test public void TestFieldPositionFraction() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); nf.setPositivePrefix("FOO"); nf.setPositiveSuffix("BA"); StringBuffer buffer = new StringBuffer(); FieldPosition fp = new FieldPosition(NumberFormat.Field.FRACTION); nf.format(35.47, buffer, fp); assertEquals("35.47", "FOO35.47BA", buffer.toString()); assertEquals("fp begin", 6, fp.getBeginIndex()); assertEquals("fp end", 8, fp.getEndIndex()); } @Test public void TestFieldPositionCurrency() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getCurrencyInstance(Locale.US); double amount = 35.47; double negAmount = -34.567; FieldPosition cp = new FieldPosition(NumberFormat.Field.CURRENCY); StringBuffer buffer0 = new StringBuffer(); nf.format(amount, buffer0, cp); assertEquals("$35.47", "$35.47", buffer0.toString()); assertEquals("cp begin", 0, cp.getBeginIndex()); assertEquals("cp end", 1, cp.getEndIndex()); StringBuffer buffer01 = new StringBuffer(); nf.format(negAmount, buffer01, cp); assertEquals("-$34.57", "-$34.57", buffer01.toString()); assertEquals("cp begin", 1, cp.getBeginIndex()); assertEquals("cp end", 2, cp.getEndIndex()); nf.setCurrency(Currency.getInstance(Locale.FRANCE)); StringBuffer buffer1 = new StringBuffer(); nf.format(amount, buffer1, cp); assertEquals("€35.47", "€35.47", buffer1.toString()); assertEquals("cp begin", 0, cp.getBeginIndex()); assertEquals("cp end", 1, cp.getEndIndex()); nf.setCurrency(Currency.getInstance(new Locale("fr", "ch", ""))); StringBuffer buffer2 = new StringBuffer(); nf.format(amount, buffer2, cp); assertEquals("CHF 35.47", "CHF 35.47", buffer2.toString()); assertEquals("cp begin", 0, cp.getBeginIndex()); assertEquals("cp end", 3, cp.getEndIndex()); StringBuffer buffer20 = new StringBuffer(); nf.format(negAmount, buffer20, cp); assertEquals("-CHF 34.57", "-CHF 34.57", buffer20.toString()); assertEquals("cp begin", 1, cp.getBeginIndex()); assertEquals("cp end", 4, cp.getEndIndex()); nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getCurrencyInstance(Locale.FRANCE); StringBuffer buffer3 = new StringBuffer(); nf.format(amount, buffer3, cp); assertEquals("35,47 €", "35,47 €", buffer3.toString()); assertEquals("cp begin", 6, cp.getBeginIndex()); assertEquals("cp end", 7, cp.getEndIndex()); StringBuffer buffer4 = new StringBuffer(); nf.format(negAmount, buffer4, cp); assertEquals("-34,57 €", "-34,57 €", buffer4.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 8, cp.getEndIndex()); nf.setCurrency(Currency.getInstance(new Locale("fr", "ch"))); StringBuffer buffer5 = new StringBuffer(); nf.format(negAmount, buffer5, cp); assertEquals("-34,57 CHF", "-34,57 CHF", buffer5.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 10, cp.getEndIndex()); NumberFormat plCurrencyFmt = NumberFormat.getInstance(new Locale("fr", "ch"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer6 = new StringBuffer(); plCurrencyFmt.format(negAmount, buffer6, cp); assertEquals("-34.57 francs suisses", "-34.57 francs suisses", buffer6.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 21, cp.getEndIndex()); // Positive value with PLURALCURRENCYSTYLE. plCurrencyFmt = NumberFormat.getInstance(new Locale("ja", "ch"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer7 = new StringBuffer(); plCurrencyFmt.format(amount, buffer7, cp); assertEquals("35.47 スイス フラン", "35.47 スイス フラン", buffer7.toString()); assertEquals("cp begin", 6, cp.getBeginIndex()); assertEquals("cp end", 13, cp.getEndIndex()); // PLURALCURRENCYSTYLE for non-ASCII. plCurrencyFmt = NumberFormat.getInstance(new Locale("ja", "de"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer8 = new StringBuffer(); plCurrencyFmt.format(negAmount, buffer8, cp); assertEquals("-34.57 ユーロ", "-34.57 ユーロ", buffer8.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 10, cp.getEndIndex()); nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getCurrencyInstance(Locale.JAPAN); nf.setCurrency(Currency.getInstance(new Locale("ja", "jp"))); StringBuffer buffer9 = new StringBuffer(); nf.format(negAmount, buffer9, cp); assertEquals("-¥35", "-¥35", buffer9.toString()); assertEquals("cp begin", 1, cp.getBeginIndex()); assertEquals("cp end", 2, cp.getEndIndex()); // Negative value with PLURALCURRENCYSTYLE. plCurrencyFmt = NumberFormat.getInstance(new Locale("ja", "ch"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer10 = new StringBuffer(); plCurrencyFmt.format(negAmount, buffer10, cp); assertEquals("-34.57 スイス フラン", "-34.57 スイス フラン", buffer10.toString()); assertEquals("cp begin", 7, cp.getBeginIndex()); assertEquals("cp end", 14, cp.getEndIndex()); // Nagative value with PLURALCURRENCYSTYLE, Arabic digits. nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getCurrencyInstance(new Locale("ar", "eg")); plCurrencyFmt = NumberFormat.getInstance(new Locale("ar", "eg"), NumberFormat.PLURALCURRENCYSTYLE); StringBuffer buffer11 = new StringBuffer(); plCurrencyFmt.format(negAmount, buffer11, cp); assertEquals("؜-٣٤٫٥٧ جنيه مصري", "؜-٣٤٫٥٧ جنيه مصري", buffer11.toString()); assertEquals("cp begin", 8, cp.getBeginIndex()); assertEquals("cp end", 17, cp.getEndIndex()); } @Test public void TestRounding() { DecimalFormat nf = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); if (false) { // for debugging specific value nf.setRoundingMode(BigDecimal.ROUND_HALF_UP); checkRounding(nf, new BigDecimal("300.0300000000"), 0, new BigDecimal("0.020000000")); } // full tests int[] roundingIncrements = {1, 2, 5, 20, 50, 100}; int[] testValues = {0, 300}; for (int j = 0; j < testValues.length; ++j) { for (int mode = BigDecimal.ROUND_UP; mode < BigDecimal.ROUND_HALF_EVEN; ++mode) { nf.setRoundingMode(mode); for (int increment = 0; increment < roundingIncrements.length; ++increment) { BigDecimal base = new BigDecimal(testValues[j]); BigDecimal rInc = new BigDecimal(roundingIncrements[increment]); checkRounding(nf, base, 20, rInc); rInc = new BigDecimal("1.000000000").divide(rInc); checkRounding(nf, base, 20, rInc); } } } } @Test public void TestRoundingPattern() { class TestRoundingPatternItem { String pattern; BigDecimal roundingIncrement; double testCase; String expected; TestRoundingPatternItem(String pattern, BigDecimal roundingIncrement, double testCase, String expected) { this.pattern = pattern; this.roundingIncrement = roundingIncrement; this.testCase = testCase; this.expected = expected; } }; TestRoundingPatternItem []tests = { new TestRoundingPatternItem("##0.65", new BigDecimal("0.65"), 1.234, "1.30"), new TestRoundingPatternItem("#50", new BigDecimal("50"), 1230, "1250") }; DecimalFormat df = (DecimalFormat) com.ibm.icu.text.NumberFormat.getInstance(ULocale.ENGLISH); String result; for (int i = 0; i < tests.length; i++) { df.applyPattern(tests[i].pattern); result = df.format(tests[i].testCase); if (!tests[i].expected.equals(result)) { errln("String Pattern Rounding Test Failed: Pattern: \"" + tests[i].pattern + "\" Number: " + tests[i].testCase + " - Got: " + result + " Expected: " + tests[i].expected); } df.setRoundingIncrement(tests[i].roundingIncrement); result = df.format(tests[i].testCase); if (!tests[i].expected.equals(result)) { errln("BigDecimal Rounding Test Failed: Pattern: \"" + tests[i].pattern + "\" Number: " + tests[i].testCase + " - Got: " + result + " Expected: " + tests[i].expected); } } } @Test public void TestBigDecimalRounding() { String figure = "50.000000004"; Double dbl = new Double(figure); BigDecimal dec = new BigDecimal(figure); DecimalFormat f = (DecimalFormat) NumberFormat.getInstance(); f.applyPattern("00.00######"); assertEquals("double format", "50.00", f.format(dbl)); assertEquals("bigdec format", "50.00", f.format(dec)); int maxFracDigits = f.getMaximumFractionDigits(); BigDecimal roundingIncrement = new BigDecimal("1").movePointLeft(maxFracDigits); f.setRoundingIncrement(roundingIncrement); f.setRoundingMode(BigDecimal.ROUND_DOWN); assertEquals("Rounding down", f.format(dbl), f.format(dec)); f.setRoundingIncrement(roundingIncrement); f.setRoundingMode(BigDecimal.ROUND_HALF_UP); assertEquals("Rounding half up", f.format(dbl), f.format(dec)); } void checkRounding(DecimalFormat nf, BigDecimal base, int iterations, BigDecimal increment) { nf.setRoundingIncrement(increment.toBigDecimal()); BigDecimal lastParsed = new BigDecimal(Integer.MIN_VALUE); // used to make sure that rounding is monotonic for (int i = -iterations; i <= iterations; ++i) { BigDecimal iValue = base.add(increment.multiply(new BigDecimal(i)).movePointLeft(1)); BigDecimal smallIncrement = new BigDecimal("0.00000001"); if (iValue.signum() != 0) { smallIncrement.multiply(iValue); // scale unless zero } // we not only test the value, but some values in a small range around it. lastParsed = checkRound(nf, iValue.subtract(smallIncrement), lastParsed); lastParsed = checkRound(nf, iValue, lastParsed); lastParsed = checkRound(nf, iValue.add(smallIncrement), lastParsed); } } private BigDecimal checkRound(DecimalFormat nf, BigDecimal iValue, BigDecimal lastParsed) { String formatedBigDecimal = nf.format(iValue); String formattedDouble = nf.format(iValue.doubleValue()); if (!equalButForTrailingZeros(formatedBigDecimal, formattedDouble)) { errln("Failure at: " + iValue + " (" + iValue.doubleValue() + ")" + ",\tRounding-mode: " + roundingModeNames[nf.getRoundingMode()] + ",\tRounding-increment: " + nf.getRoundingIncrement() + ",\tdouble: " + formattedDouble + ",\tBigDecimal: " + formatedBigDecimal); } else { logln("Value: " + iValue + ",\tRounding-mode: " + roundingModeNames[nf.getRoundingMode()] + ",\tRounding-increment: " + nf.getRoundingIncrement() + ",\tdouble: " + formattedDouble + ",\tBigDecimal: " + formatedBigDecimal); } try { // Number should have compareTo(...) BigDecimal parsed = toBigDecimal(nf.parse(formatedBigDecimal)); if (lastParsed.compareTo(parsed) > 0) { errln("Rounding wrong direction!: " + lastParsed + " > " + parsed); } lastParsed = parsed; } catch (ParseException e) { errln("Parse Failure with: " + formatedBigDecimal); } return lastParsed; } static BigDecimal toBigDecimal(Number number) { return number instanceof BigDecimal ? (BigDecimal) number : number instanceof BigInteger ? new BigDecimal((BigInteger)number) : number instanceof java.math.BigDecimal ? new BigDecimal((java.math.BigDecimal)number) : number instanceof Double ? new BigDecimal(number.doubleValue()) : number instanceof Float ? new BigDecimal(number.floatValue()) : new BigDecimal(number.longValue()); } static String[] roundingModeNames = { "ROUND_UP", "ROUND_DOWN", "ROUND_CEILING", "ROUND_FLOOR", "ROUND_HALF_UP", "ROUND_HALF_DOWN", "ROUND_HALF_EVEN", "ROUND_UNNECESSARY" }; private static boolean equalButForTrailingZeros(String formatted1, String formatted2) { if (formatted1.length() == formatted2.length()) return formatted1.equals(formatted2); return stripFinalZeros(formatted1).equals(stripFinalZeros(formatted2)); } private static String stripFinalZeros(String formatted) { int len1 = formatted.length(); char ch; while (len1 > 0 && ((ch = formatted.charAt(len1-1)) == '0' || ch == '.')) --len1; if (len1==1 && ((ch = formatted.charAt(len1-1)) == '-')) --len1; return formatted.substring(0,len1); } //------------------------------------------------------------------ // Support methods //------------------------------------------------------------------ /** Format-Parse test */ public void expect2(NumberFormat fmt, Number n, String exp) { // Don't round-trip format test, since we explicitly do it expect(fmt, n, exp, false); expect(fmt, exp, n); } /** Format-Parse test */ public void expect3(NumberFormat fmt, Number n, String exp) { // Don't round-trip format test, since we explicitly do it expect_rbnf(fmt, n, exp, false); expect_rbnf(fmt, exp, n); } /** Format-Parse test (convenience) */ public void expect2(NumberFormat fmt, double n, String exp) { expect2(fmt, new Double(n), exp); } /** RBNF Format-Parse test (convenience) */ public void expect3(NumberFormat fmt, double n, String exp) { expect3(fmt, new Double(n), exp); } /** Format-Parse test (convenience) */ public void expect2(NumberFormat fmt, long n, String exp) { expect2(fmt, new Long(n), exp); } /** RBNF Format-Parse test (convenience) */ public void expect3(NumberFormat fmt, long n, String exp) { expect3(fmt, new Long(n), exp); } /** Format test */ public void expect(NumberFormat fmt, Number n, String exp, boolean rt) { StringBuffer saw = new StringBuffer(); FieldPosition pos = new FieldPosition(0); fmt.format(n, saw, pos); String pat = ((DecimalFormat)fmt).toPattern(); if (saw.toString().equals(exp)) { logln("Ok " + n + " x " + pat + " = \"" + saw + "\""); // We should be able to round-trip the formatted string => // number => string (but not the other way around: number // => string => number2, might have number2 != number): if (rt) { try { Number n2 = fmt.parse(exp); StringBuffer saw2 = new StringBuffer(); fmt.format(n2, saw2, pos); if (!saw2.toString().equals(exp)) { errln("expect() format test rt, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL \"" + exp + "\" => " + n2 + " => \"" + saw2 + '"'); } } catch (ParseException e) { errln("expect() format test rt, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", " + e.getMessage()); return; } } } else { errln("expect() format test, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL " + n + " x " + pat + " = \"" + saw + "\", expected \"" + exp + "\""); } } /** RBNF format test */ public void expect_rbnf(NumberFormat fmt, Number n, String exp, boolean rt) { StringBuffer saw = new StringBuffer(); FieldPosition pos = new FieldPosition(0); fmt.format(n, saw, pos); if (saw.toString().equals(exp)) { logln("Ok " + n + " = \"" + saw + "\""); // We should be able to round-trip the formatted string => // number => string (but not the other way around: number // => string => number2, might have number2 != number): if (rt) { try { Number n2 = fmt.parse(exp); StringBuffer saw2 = new StringBuffer(); fmt.format(n2, saw2, pos); if (!saw2.toString().equals(exp)) { errln("expect_rbnf() format test rt, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL \"" + exp + "\" => " + n2 + " => \"" + saw2 + '"'); } } catch (ParseException e) { errln("expect_rbnf() format test rt, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", " + e.getMessage()); return; } } } else { errln("expect_rbnf() format test, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL " + n + " = \"" + saw + "\", expected \"" + exp + "\""); } } /** Format test (convenience) */ public void expect(NumberFormat fmt, Number n, String exp) { expect(fmt, n, exp, true); } /** Format test (convenience) */ public void expect(NumberFormat fmt, double n, String exp) { expect(fmt, new Double(n), exp); } /** Format test (convenience) */ public void expect(NumberFormat fmt, long n, String exp) { expect(fmt, new Long(n), exp); } /** Parse test */ public void expect(NumberFormat fmt, String str, Number n) { Number num = null; try { num = fmt.parse(str); } catch (ParseException e) { errln(e.getMessage()); return; } String pat = ((DecimalFormat)fmt).toPattern(); // A little tricky here -- make sure Double(12345.0) and // Long(12345) match. if (num.equals(n) || num.doubleValue() == n.doubleValue()) { logln("Ok \"" + str + "\" x " + pat + " = " + num); } else { errln("expect() parse test, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL \"" + str + "\" x " + pat + " = " + num + ", expected " + n); } } /** RBNF Parse test */ public void expect_rbnf(NumberFormat fmt, String str, Number n) { Number num = null; try { num = fmt.parse(str); } catch (ParseException e) { errln(e.getMessage()); return; } // A little tricky here -- make sure Double(12345.0) and // Long(12345) match. if (num.equals(n) || num.doubleValue() == n.doubleValue()) { logln("Ok \"" + str + " = " + num); } else { errln("expect_rbnf() parse test, locale " + fmt.getLocale(ULocale.VALID_LOCALE) + ", FAIL \"" + str + " = " + num + ", expected " + n); } } /** Parse test (convenience) */ public void expect(NumberFormat fmt, String str, double n) { expect(fmt, str, new Double(n)); } /** Parse test (convenience) */ public void expect(NumberFormat fmt, String str, long n) { expect(fmt, str, new Long(n)); } /** Parse test */ public void expectParseException(DecimalFormat fmt, String str, Number n) { Number num = null; try { num = fmt.parse(str); errln("Expected failure, but passed: " + n + " on " + fmt.toPattern() + " -> " + num); } catch (ParseException e) { } } private void expectCurrency(NumberFormat nf, Currency curr, double value, String string) { DecimalFormat fmt = (DecimalFormat) nf; if (curr != null) { fmt.setCurrency(curr); } String s = fmt.format(value).replace('\u00A0', ' '); if (s.equals(string)) { logln("Ok: " + value + " x " + curr + " => " + s); } else { errln("FAIL: " + value + " x " + curr + " => " + s + ", expected " + string); } } public void expectPad(DecimalFormat fmt, String pat, int pos) { expectPad(fmt, pat, pos, 0, (char)0); } public void expectPad(DecimalFormat fmt, final String pat, int pos, int width, final char pad) { int apos = 0, awidth = 0; char apadStr; try { fmt.applyPattern(pat); apos = fmt.getPadPosition(); awidth = fmt.getFormatWidth(); apadStr = fmt.getPadCharacter(); } catch (Exception e) { apos = -1; awidth = width; apadStr = pad; } if (apos == pos && awidth == width && apadStr == pad) { logln("Ok \"" + pat + "\" pos=" + apos + ((pos == -1) ? "" : " width=" + awidth + " pad=" + apadStr)); } else { errln("FAIL \"" + pat + "\" pos=" + apos + " width=" + awidth + " pad=" + apadStr + ", expected " + pos + " " + width + " " + pad); } } public void expectPat(DecimalFormat fmt, final String exp) { String pat = fmt.toPattern(); if (pat.equals(exp)) { logln("Ok \"" + pat + "\""); } else { errln("FAIL \"" + pat + "\", expected \"" + exp + "\""); } } private void expectParseCurrency(NumberFormat fmt, Currency expected, String text) { ParsePosition pos = new ParsePosition(0); CurrencyAmount currencyAmount = fmt.parseCurrency(text, pos); assertTrue("Parse of " + text + " should have succeeded.", pos.getIndex() > 0); assertEquals("Currency should be correct.", expected, currencyAmount.getCurrency()); } @Test public void TestJB3832(){ ULocale locale = new ULocale("pt_PT@currency=PTE"); NumberFormat format = NumberFormat.getCurrencyInstance(locale); Currency curr = Currency.getInstance(locale); logln("\nName of the currency is: " + curr.getName(locale, Currency.LONG_NAME, new boolean[] {false})); CurrencyAmount cAmt = new CurrencyAmount(1150.50, curr); logln("CurrencyAmount object's hashCode is: " + cAmt.hashCode()); //cover hashCode String str = format.format(cAmt); String expected = "1,150$50\u00a0\u200b"; if(!expected.equals(str)){ errln("Did not get the expected output Expected: "+expected+" Got: "+ str); } } @Test public void TestScientificWithGrouping() { // Grouping separators are not allowed in the pattern, but we can enable them via the API. DecimalFormat df = new DecimalFormat("###0.000E0"); df.setGroupingUsed(true); df.setGroupingSize(3); expect2(df, 123, "123.0E0"); expect2(df, 1234, "1,234E0"); expect2(df, 12340, "1.234E4"); } @Test public void TestStrictParse() { // Pass both strict and lenient: String[] pass = { "0", // single zero before end of text is not leading "0 ", // single zero at end of number is not leading "0.", // single zero before period (or decimal, it's ambiguous) is not leading "0,", // single zero before comma (not group separator) is not leading "0.0", // single zero before decimal followed by digit is not leading "0. ", // same as above before period (or decimal) is not leading "0.100,5", // comma stops parse of decimal (no grouping) "0.100,,5", // two commas also stops parse ".00", // leading decimal is ok, even with zeros "1234567", // group separators are not required "12345, ", // comma not followed by digit is not a group separator, but end of number "1,234, ", // if group separator is present, group sizes must be appropriate "1,234,567", // ...secondary too "0E", // an exponent not followed by zero or digits is not an exponent "00", // leading zero before zero - used to be error - see ticket #7913 "012", // leading zero before digit - used to be error - see ticket #7913 "0,456", // leading zero before group separator - used to be error - see ticket #7913 "999,999", // see ticket #6863 "-99,999", // see ticket #6863 "-999,999", // see ticket #6863 "-9,999,999", // see ticket #6863 }; // Pass lenient, fail strict: String[] fail = { "1,2", // wrong number of digits after group separator ",.02", // leading group separator before decimal "1,.02", // group separator before decimal ",0", // leading group separator before a single digit ",1", // leading group separator before a single digit "1,45", // wrong number of digits in primary group "1,45 that", // wrong number of digits in primary group "1,45.34", // wrong number of digits in primary group "1234,567", // wrong number of digits in secondary group "12,34,567", // wrong number of digits in secondary group "1,23,456,7890", // wrong number of digits in primary and secondary groups }; // Fail both lenient and strict: String[] failBoth = { }; DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); runStrictParseBatch(nf, pass, fail, failBoth); String[] scientificPass = { "0E2", // single zero before exponent is ok "1234E2", // any number of digits before exponent is ok "1,234E", // an exponent string not followed by zero or digits is not an exponent "00E2", // leading zeroes now allowed in strict mode - see ticket # }; String[] scientificFail = { }; String[] scientificFailBoth = { }; nf = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); runStrictParseBatch(nf, scientificPass, scientificFail, scientificFailBoth); String[] mixedPass = { "12,34,567", "12,34,567,", "12,34,567, that", "12,34,567 that", }; String[] mixedFail = { "12,34,56", "12,34,56,", "12,34,56, that ", "12,34,56 that", }; String[] mixedFailBoth = { }; nf = new DecimalFormat("#,##,##0.#"); runStrictParseBatch(nf, mixedPass, mixedFail, mixedFailBoth); } void runStrictParseBatch(DecimalFormat nf, String[] pass, String[] fail, String[] failBoth) { nf.setParseStrict(false); runStrictParseTests("should pass", nf, pass, true); runStrictParseTests("should also pass", nf, fail, true); runStrictParseTests("should fail", nf, failBoth, false); nf.setParseStrict(true); runStrictParseTests("should still pass", nf, pass, true); runStrictParseTests("should fail", nf, fail, false); runStrictParseTests("should still fail", nf, failBoth, false); } void runStrictParseTests(String msg, DecimalFormat nf, String[] tests, boolean pass) { logln(""); logln("pattern: '" + nf.toPattern() + "'"); logln(msg); for (int i = 0; i < tests.length; ++i) { String str = tests[i]; ParsePosition pp = new ParsePosition(0); Number n = nf.parse(str, pp); String formatted = n != null ? nf.format(n) : "null"; String err = pp.getErrorIndex() == -1 ? "" : "(error at " + pp.getErrorIndex() + ")"; if ((err.length() == 0) != pass) { errln("'" + str + "' parsed '" + str.substring(0, pp.getIndex()) + "' returned " + n + " formats to '" + formatted + "' " + err); } else { if (err.length() > 0) { err = "got expected " + err; } logln("'" + str + "' parsed '" + str.substring(0, pp.getIndex()) + "' returned " + n + " formats to '" + formatted + "' " + err); } } } @Test public void TestJB5251(){ //save default locale ULocale defaultLocale = ULocale.getDefault(); ULocale.setDefault(new ULocale("qr_QR")); try { NumberFormat.getInstance(); } catch (Exception e) { errln("Numberformat threw exception for non-existent locale. It should use the default."); } //reset default locale ULocale.setDefault(defaultLocale); } @Test public void TestParseReturnType() { String[] defaultLong = { "123", "123.0", "0.0", "-9223372036854775808", // Min Long "9223372036854775807" // Max Long }; String[] defaultNonLong = { "12345678901234567890", "9223372036854775808", "-9223372036854775809" }; String[] doubles = { "-0.0", "NaN", "\u221E" // Infinity }; DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); DecimalFormat nf = new DecimalFormat("#.#", sym); if (nf.isParseBigDecimal()) { errln("FAIL: isParseDecimal() must return false by default"); } // isParseBigDecimal() is false for (int i = 0; i < defaultLong.length; i++) { try { Number n = nf.parse(defaultLong[i]); if (!(n instanceof Long)) { errln("FAIL: parse does not return Long instance"); } } catch (ParseException e) { errln("parse of '" + defaultLong[i] + "' threw exception: " + e); } } for (int i = 0; i < defaultNonLong.length; i++) { try { Number n = nf.parse(defaultNonLong[i]); if (n instanceof Long) { errln("FAIL: parse returned a Long"); } } catch (ParseException e) { errln("parse of '" + defaultNonLong[i] + "' threw exception: " + e); } } // parse results for doubls must be always Double for (int i = 0; i < doubles.length; i++) { try { Number n = nf.parse(doubles[i]); if (!(n instanceof Double)) { errln("FAIL: parse does not return Double instance"); } } catch (ParseException e) { errln("parse of '" + doubles[i] + "' threw exception: " + e); } } // force this DecimalFormat to return BigDecimal nf.setParseBigDecimal(true); if (!nf.isParseBigDecimal()) { errln("FAIL: isParseBigDecimal() must return true"); } // isParseBigDecimal() is true for (int i = 0; i < defaultLong.length + defaultNonLong.length; i++) { String input = (i < defaultLong.length) ? defaultLong[i] : defaultNonLong[i - defaultLong.length]; try { Number n = nf.parse(input); if (!(n instanceof BigDecimal)) { errln("FAIL: parse does not return BigDecimal instance"); } } catch (ParseException e) { errln("parse of '" + input + "' threw exception: " + e); } } // parse results for doubls must be always Double for (int i = 0; i < doubles.length; i++) { try { Number n = nf.parse(doubles[i]); if (!(n instanceof Double)) { errln("FAIL: parse does not return Double instance"); } } catch (ParseException e) { errln("parse of '" + doubles[i] + "' threw exception: " + e); } } } @Test public void TestNonpositiveMultiplier() { DecimalFormat df = new DecimalFormat("0"); // test zero multiplier try { df.setMultiplier(0); // bad errln("DecimalFormat.setMultiplier(0) did not throw an IllegalArgumentException"); } catch (IllegalArgumentException ex) { // good } // test negative multiplier try { df.setMultiplier(-1); if (df.getMultiplier() != -1) { errln("DecimalFormat.setMultiplier(-1) did not change the multiplier to -1"); return; } // good } catch (IllegalArgumentException ex) { // bad errln("DecimalFormat.setMultiplier(-1) threw an IllegalArgumentException"); return; } expect(df, "1122.123", -1122.123); expect(df, "-1122.123", 1122.123); expect(df, "1.2", -1.2); expect(df, "-1.2", 1.2); expect2(df, Long.MAX_VALUE, BigInteger.valueOf(Long.MAX_VALUE).negate().toString()); expect2(df, Long.MIN_VALUE, BigInteger.valueOf(Long.MIN_VALUE).negate().toString()); expect2(df, Long.MAX_VALUE / 2, BigInteger.valueOf(Long.MAX_VALUE / 2).negate().toString()); expect2(df, Long.MIN_VALUE / 2, BigInteger.valueOf(Long.MIN_VALUE / 2).negate().toString()); expect2(df, BigDecimal.valueOf(Long.MAX_VALUE), BigDecimal.valueOf(Long.MAX_VALUE).negate().toString()); expect2(df, BigDecimal.valueOf(Long.MIN_VALUE), BigDecimal.valueOf(Long.MIN_VALUE).negate().toString()); expect2(df, java.math.BigDecimal.valueOf(Long.MAX_VALUE), java.math.BigDecimal.valueOf(Long.MAX_VALUE).negate().toString()); expect2(df, java.math.BigDecimal.valueOf(Long.MIN_VALUE), java.math.BigDecimal.valueOf(Long.MIN_VALUE).negate().toString()); } @Test public void TestJB5358() { int numThreads = 10; String numstr = "12345"; double expected = 12345; DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt = new DecimalFormat("#.#", sym); ArrayList errors = new ArrayList(); ParseThreadJB5358[] threads = new ParseThreadJB5358[numThreads]; for (int i = 0; i < numThreads; i++) { threads[i] = new ParseThreadJB5358((DecimalFormat)fmt.clone(), numstr, expected, errors); threads[i].start(); } for (int i = 0; i < numThreads; i++) { try { threads[i].join(); } catch (InterruptedException ie) { ie.printStackTrace(); } } if (errors.size() != 0) { StringBuffer errBuf = new StringBuffer(); for (int i = 0; i < errors.size(); i++) { errBuf.append((String)errors.get(i)); errBuf.append("\n"); } errln("FAIL: " + errBuf); } } static private class ParseThreadJB5358 extends Thread { private final DecimalFormat decfmt; private final String numstr; private final double expect; private final ArrayList errors; public ParseThreadJB5358(DecimalFormat decfmt, String numstr, double expect, ArrayList errors) { this.decfmt = decfmt; this.numstr = numstr; this.expect = expect; this.errors = errors; } @Override public void run() { for (int i = 0; i < 10000; i++) { try { Number n = decfmt.parse(numstr); if (n.doubleValue() != expect) { synchronized(errors) { errors.add(new String("Bad parse result - expected:" + expect + " actual:" + n.doubleValue())); } } } catch (Throwable t) { synchronized(errors) { errors.add(new String(t.getClass().getName() + " - " + t.getMessage())); } } } } } @Test public void TestSetCurrency() { DecimalFormatSymbols decf1 = DecimalFormatSymbols.getInstance(ULocale.US); DecimalFormatSymbols decf2 = DecimalFormatSymbols.getInstance(ULocale.US); decf2.setCurrencySymbol("UKD"); DecimalFormat format1 = new DecimalFormat("000.000", decf1); DecimalFormat format2 = new DecimalFormat("000.000", decf2); Currency euro = Currency.getInstance("EUR"); format1.setCurrency(euro); format2.setCurrency(euro); assertEquals("Reset with currency symbol", format1, format2); } /* * Testing the method public StringBuffer format(Object number, ...) */ @Test public void TestFormat() { NumberFormat nf = NumberFormat.getInstance(); StringBuffer sb = new StringBuffer("dummy"); FieldPosition fp = new FieldPosition(0); // Tests when "if (number instanceof Long)" is true try { nf.format(new Long("0"), sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a Long object. Error: " + e); } // Tests when "else if (number instanceof BigInteger)" is true try { nf.format((Object)new BigInteger("0"), sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a BigInteger object. Error: " + e); } // Tests when "else if (number instanceof java.math.BigDecimal)" is true try { nf.format((Object)new java.math.BigDecimal("0"), sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a java.math.BigDecimal object. Error: " + e); } // Tests when "else if (number instanceof com.ibm.icu.math.BigDecimal)" is true try { nf.format((Object)new com.ibm.icu.math.BigDecimal("0"), sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a com.ibm.icu.math.BigDecimal object. Error: " + e); } // Tests when "else if (number instanceof CurrencyAmount)" is true try { CurrencyAmount ca = new CurrencyAmount(0.0, Currency.getInstance(new ULocale("en_US"))); nf.format((Object)ca, sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "return an exception for a CurrencyAmount object. Error: " + e); } // Tests when "else if (number instanceof Number)" is true try { nf.format(0.0, sb, fp); } catch (Exception e) { errln("NumberFormat.format(Object number, ...) was not suppose to " + "to return an exception for a Number object. Error: " + e); } // Tests when "else" is true try { nf.format(new Object(), sb, fp); errln("NumberFormat.format(Object number, ...) was suppose to " + "return an exception for an invalid object."); } catch (Exception e) { } try { nf.format(new String("dummy"), sb, fp); errln("NumberFormat.format(Object number, ...) was suppose to " + "return an exception for an invalid object."); } catch (Exception e) { } } /* * Coverage tests for the implementation of abstract format methods not being called otherwise */ @Test public void TestFormatAbstractImplCoverage() { NumberFormat df = DecimalFormat.getInstance(Locale.ENGLISH); NumberFormat cdf = CompactDecimalFormat.getInstance(Locale.ENGLISH, CompactDecimalFormat.CompactStyle.SHORT); NumberFormat rbf = new RuleBasedNumberFormat(ULocale.ENGLISH, RuleBasedNumberFormat.SPELLOUT); /* * Test NumberFormat.format(BigDecimal,StringBuffer,FieldPosition) */ StringBuffer sb = new StringBuffer(); String result = df.format(new BigDecimal(2000.43), sb, new FieldPosition(0)).toString(); if (!"2,000.43".equals(result)) { errln("DecimalFormat failed. Expected: 2,000.43 - Actual: " + result); } sb.delete(0, sb.length()); result = cdf.format(new BigDecimal(2000.43), sb, new FieldPosition(0)).toString(); if (!"2K".equals(result)) { errln("DecimalFormat failed. Expected: 2K - Actual: " + result); } sb.delete(0, sb.length()); result = rbf.format(new BigDecimal(2000.43), sb, new FieldPosition(0)).toString(); if (!"two thousand point four three".equals(result)) { errln("DecimalFormat failed. Expected: 'two thousand point four three' - Actual: '" + result + "'"); } } /* * Tests the method public final static NumberFormat getInstance(int style) public static NumberFormat * getInstance(Locale inLocale, int style) public static NumberFormat getInstance(ULocale desiredLocale, int choice) */ @Test public void TestGetInstance() { // Tests "public final static NumberFormat getInstance(int style)" int maxStyle = NumberFormat.STANDARDCURRENCYSTYLE; int[] invalid_cases = { NumberFormat.NUMBERSTYLE - 1, NumberFormat.NUMBERSTYLE - 2, maxStyle + 1, maxStyle + 2 }; for (int i = NumberFormat.NUMBERSTYLE; i < maxStyle; i++) { try { NumberFormat.getInstance(i); } catch (Exception e) { errln("NumberFormat.getInstance(int style) was not suppose to " + "return an exception for passing value of " + i); } } for (int i = 0; i < invalid_cases.length; i++) { try { NumberFormat.getInstance(invalid_cases[i]); errln("NumberFormat.getInstance(int style) was suppose to " + "return an exception for passing value of " + invalid_cases[i]); } catch (Exception e) { } } // Tests "public static NumberFormat getInstance(Locale inLocale, int style)" String[] localeCases = { "en_US", "fr_FR", "de_DE", "jp_JP" }; for (int i = NumberFormat.NUMBERSTYLE; i < maxStyle; i++) { for (int j = 0; j < localeCases.length; j++) { try { NumberFormat.getInstance(new Locale(localeCases[j]), i); } catch (Exception e) { errln("NumberFormat.getInstance(Locale inLocale, int style) was not suppose to " + "return an exception for passing value of " + localeCases[j] + ", " + i); } } } // Tests "public static NumberFormat getInstance(ULocale desiredLocale, int choice)" // Tests when "if (choice < NUMBERSTYLE || choice > PLURALCURRENCYSTYLE)" is true for (int i = 0; i < invalid_cases.length; i++) { try { NumberFormat.getInstance((ULocale) null, invalid_cases[i]); errln("NumberFormat.getInstance(ULocale inLocale, int choice) was not suppose to " + "return an exception for passing value of " + invalid_cases[i]); } catch (Exception e) { } } } /* * Tests the class public static abstract class NumberFormatFactory */ @Test public void TestNumberFormatFactory() { /* * The following class allows the method public NumberFormat createFormat(Locale loc, int formatType) to be * tested. */ class TestFactory extends NumberFormatFactory { @Override public Set<String> getSupportedLocaleNames() { return null; } @Override public NumberFormat createFormat(ULocale loc, int formatType) { return null; } } /* * The following class allows the method public NumberFormat createFormat(ULocale loc, int formatType) to be * tested. */ class TestFactory1 extends NumberFormatFactory { @Override public Set<String> getSupportedLocaleNames() { return null; } @Override public NumberFormat createFormat(Locale loc, int formatType) { return null; } } TestFactory tf = new TestFactory(); TestFactory1 tf1 = new TestFactory1(); /* * Tests the method public boolean visible() */ if (tf.visible() != true) { errln("NumberFormatFactory.visible() was suppose to return true."); } /* * Tests the method public NumberFormat createFormat(Locale loc, int formatType) */ if (tf.createFormat(new Locale(""), 0) != null) { errln("NumberFormatFactory.createFormat(Locale loc, int formatType) " + "was suppose to return null"); } /* * Tests the method public NumberFormat createFormat(ULocale loc, int formatType) */ if (tf1.createFormat(new ULocale(""), 0) != null) { errln("NumberFormatFactory.createFormat(ULocale loc, int formatType) " + "was suppose to return null"); } } /* * Tests the class public static abstract class SimpleNumberFormatFactory extends NumberFormatFactory */ @Test public void TestSimpleNumberFormatFactory() { class TestSimpleNumberFormatFactory extends SimpleNumberFormatFactory { /* * Tests the method public SimpleNumberFormatFactory(Locale locale) */ TestSimpleNumberFormatFactory() { super(new Locale("")); } } @SuppressWarnings("unused") TestSimpleNumberFormatFactory tsnff = new TestSimpleNumberFormatFactory(); } /* * Tests the method public static ULocale[] getAvailableLocales() */ @SuppressWarnings("static-access") @Test public void TestGetAvailableLocales() { // Tests when "if (shim == null)" is true @SuppressWarnings("serial") class TestGetAvailableLocales extends NumberFormat { @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(java.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public Number parse(String text, ParsePosition parsePosition) { return null; } } try { TestGetAvailableLocales test = new TestGetAvailableLocales(); test.getAvailableLocales(); } catch (Exception e) { errln("NumberFormat.getAvailableLocales() was not suppose to " + "return an exception when getting getting available locales."); } } /* * Tests the method public void setMinimumIntegerDigits(int newValue) */ @Test public void TestSetMinimumIntegerDigits() { NumberFormat nf = NumberFormat.getInstance(); // For valid array, it is displayed as {min value, max value} // Tests when "if (minimumIntegerDigits > maximumIntegerDigits)" is true int[][] cases = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 2, 0 }, { 2, 1 }, { 10, 0 } }; int[] expectedMax = { 1, 1, 0, 0, 1, 0 }; if (cases.length != expectedMax.length) { errln("Can't continue test case method TestSetMinimumIntegerDigits " + "since the test case arrays are unequal."); } else { for (int i = 0; i < cases.length; i++) { nf.setMinimumIntegerDigits(cases[i][0]); nf.setMaximumIntegerDigits(cases[i][1]); if (nf.getMaximumIntegerDigits() != expectedMax[i]) { errln("NumberFormat.setMinimumIntegerDigits(int newValue " + "did not return an expected result for parameter " + cases[i][0] + " and " + cases[i][1] + " and expected " + expectedMax[i] + " but got " + nf.getMaximumIntegerDigits()); } } } } /* * Tests the method public int getRoundingMode() public void setRoundingMode(int roundingMode) */ @Test public void TestRoundingMode() { @SuppressWarnings("serial") class TestRoundingMode extends NumberFormat { @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(java.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public StringBuffer format(BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) { return null; } @Override public Number parse(String text, ParsePosition parsePosition) { return null; } } TestRoundingMode tgrm = new TestRoundingMode(); // Tests the function 'public void setRoundingMode(int roundingMode)' try { tgrm.setRoundingMode(0); errln("NumberFormat.setRoundingMode(int) was suppose to return an exception"); } catch (Exception e) { } // Tests the function 'public int getRoundingMode()' try { tgrm.getRoundingMode(); errln("NumberFormat.getRoundingMode() was suppose to return an exception"); } catch (Exception e) { } } /* * Testing lenient decimal/grouping separator parsing */ @Test public void TestLenientSymbolParsing() { DecimalFormat fmt = new DecimalFormat(); DecimalFormatSymbols sym = new DecimalFormatSymbols(); expect(fmt, "12\u300234", 12.34); // Ticket#7345 - case 1 // Even strict parsing, the decimal separator set in the symbols // should be successfully parsed. sym.setDecimalSeparator('\u3002'); // non-strict fmt.setDecimalFormatSymbols(sym); // strict - failed before the fix for #7345 fmt.setParseStrict(true); expect(fmt, "23\u300245", 23.45); fmt.setParseStrict(false); // Ticket#7345 - case 2 // Decimal separator variants other than DecimalFormatSymbols.decimalSeparator // should not hide the grouping separator DecimalFormatSymbols.groupingSeparator. sym.setDecimalSeparator('.'); sym.setGroupingSeparator(','); fmt.setDecimalFormatSymbols(sym); expect(fmt, "1,234.56", 1234.56); sym.setGroupingSeparator('\uFF61'); fmt.setDecimalFormatSymbols(sym); expect(fmt, "2\uFF61345.67", 2345.67); // Ticket#7128 // sym.setGroupingSeparator(','); fmt.setDecimalFormatSymbols(sym); String skipExtSepParse = ICUConfig.get("com.ibm.icu.text.DecimalFormat.SkipExtendedSeparatorParsing", "false"); if (skipExtSepParse.equals("true")) { // When the property SkipExtendedSeparatorParsing is true, // DecimalFormat does not use the extended equivalent separator // data and only uses the one in DecimalFormatSymbols. expect(fmt, "23 456", 23); } else { // Lenient separator parsing is enabled by default. // A space character below is interpreted as a // group separator, even ',' is used as grouping // separator in the symbols. expect(fmt, "12 345", 12345); } } /* * Testing currency driven max/min fraction digits problem * reported by ticket#7282 */ @Test public void TestCurrencyFractionDigits() { double value = 99.12345; // Create currency instance NumberFormat cfmt = NumberFormat.getCurrencyInstance(new ULocale("ja_JP")); String text1 = cfmt.format(value); // Reset the same currency and format the test value again cfmt.setCurrency(cfmt.getCurrency()); String text2 = cfmt.format(value); // output1 and output2 must be identical if (!text1.equals(text2)) { errln("NumberFormat.format() should return the same result - text1=" + text1 + " text2=" + text2); } } /* * Testing rounding to negative zero problem * reported by ticket#7609 */ @Test public void TestNegZeroRounding() { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(); df.setRoundingMode(MathContext.ROUND_HALF_UP); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(1); String text1 = df.format(-0.01); df.setRoundingIncrement(0.1); String text2 = df.format(-0.01); // output1 and output2 must be identical if (!text1.equals(text2)) { errln("NumberFormat.format() should return the same result - text1=" + text1 + " text2=" + text2); } } @Test public void TestCurrencyAmountCoverage() { CurrencyAmount ca, cb; try { ca = new CurrencyAmount(null, (Currency) null); errln("NullPointerException should have been thrown."); } catch (NullPointerException ex) { } try { ca = new CurrencyAmount(new Integer(0), (Currency) null); errln("NullPointerException should have been thrown."); } catch (NullPointerException ex) { } ca = new CurrencyAmount(new Integer(0), Currency.getInstance(new ULocale("ja_JP"))); cb = new CurrencyAmount(new Integer(1), Currency.getInstance(new ULocale("ja_JP"))); if (ca.equals(null)) { errln("Comparison should return false."); } if (!ca.equals(ca)) { errln("Comparision should return true."); } if (ca.equals(cb)) { errln("Comparison should return false."); } } @Test public void TestExponentParse() { ParsePosition parsePos = new ParsePosition(0); DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US); DecimalFormat fmt = new DecimalFormat("#####", symbols); Number result = fmt.parse("5.06e-27", parsePos); if ( result.doubleValue() != 5.06E-27 || parsePos.getIndex() != 8) { errln("ERROR: ERROR: parse failed - expected 5.06E-27, 8; got " + result.doubleValue() + ", " + parsePos.getIndex()); } } @Test public void TestExplicitParents() { // We use these for testing because decimal and grouping separators will be inherited from es_419 // starting with CLDR 2.0 String[] DATA = { "es", "CO", "", "1.250,75", "es", "ES", "", "1.250,75", "es", "GQ", "", "1.250,75", "es", "MX", "", "1,250.75", "es", "US", "", "1,250.75", "es", "VE", "", "1.250,75", }; for (int i=0; i<DATA.length; i+=4) { Locale locale = new Locale(DATA[i], DATA[i+1], DATA[i+2]); NumberFormat fmt = NumberFormat.getInstance(locale); String s = fmt.format(1250.75); if (s.equals(DATA[i+3])) { logln("Ok: 1250.75 x " + locale + " => " + s); } else { errln("FAIL: 1250.75 x " + locale + " => " + s + ", expected " + DATA[i+3]); } } } /* * Test case for #9240 * ICU4J 49.1 DecimalFormat did not clone the internal object holding * formatted text attribute information properly. Therefore, DecimalFormat * created by cloning may return incorrect results or may throw an exception * when formatToCharacterIterator is invoked from multiple threads. */ @Test public void TestFormatToCharacterIteratorThread() { final int COUNT = 10; DecimalFormat fmt1 = new DecimalFormat("#0"); DecimalFormat fmt2 = (DecimalFormat)fmt1.clone(); int[] res1 = new int[COUNT]; int[] res2 = new int[COUNT]; Thread t1 = new Thread(new FormatCharItrTestThread(fmt1, 1, res1)); Thread t2 = new Thread(new FormatCharItrTestThread(fmt2, 100, res2)); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { //TODO } int val1 = res1[0]; int val2 = res2[0]; for (int i = 0; i < COUNT; i++) { if (res1[i] != val1) { errln("Inconsistent first run limit in test thread 1"); } if (res2[i] != val2) { errln("Inconsistent first run limit in test thread 2"); } } } /* * This feature had to do with a limitation in DigitList.java that no longer exists in the * new implementation. * @Test public void TestParseMaxDigits() { DecimalFormat fmt = new DecimalFormat(); String number = "100000000000"; int newParseMax = number.length() - 1; fmt.setParseMaxDigits(-1); // Default value is 1000 if (fmt.getParseMaxDigits() != 1000) { errln("Fail valid value checking in setParseMaxDigits."); } try { if (fmt.parse(number).doubleValue() == Float.POSITIVE_INFINITY) { errln("Got Infinity but should NOT when parsing number: " + number); } fmt.setParseMaxDigits(newParseMax); if (fmt.parse(number).doubleValue() != Float.POSITIVE_INFINITY) { errln("Did not get Infinity but should when parsing number: " + number); } } catch (ParseException ex) { } } */ private static class FormatCharItrTestThread implements Runnable { private final NumberFormat fmt; private final int num; private final int[] result; FormatCharItrTestThread(NumberFormat fmt, int num, int[] result) { this.fmt = fmt; this.num = num; this.result = result; } @Override public void run() { for (int i = 0; i < result.length; i++) { AttributedCharacterIterator acitr = fmt.formatToCharacterIterator(num); acitr.first(); result[i] = acitr.getRunLimit(); } } } @Test public void TestRoundingBehavior() { final Object[][] TEST_CASES = { { ULocale.US, // ULocale - null for default locale "#.##", // Pattern Integer.valueOf(BigDecimal.ROUND_DOWN), // Rounding Mode or null (implicit) Double.valueOf(0.0d), // Rounding increment, Double or BigDecimal, or null (implicit) Double.valueOf(123.4567d), // Input value, Long, Double, BigInteger or BigDecimal "123.45" // Expected result, null for exception }, { ULocale.US, "#.##", null, Double.valueOf(0.1d), Double.valueOf(123.4567d), "123.5" }, { ULocale.US, "#.##", Integer.valueOf(BigDecimal.ROUND_DOWN), Double.valueOf(0.1d), Double.valueOf(123.4567d), "123.4" }, { ULocale.US, "#.##", Integer.valueOf(BigDecimal.ROUND_UNNECESSARY), null, Double.valueOf(123.4567d), null }, { ULocale.US, "#.##", Integer.valueOf(BigDecimal.ROUND_DOWN), null, Long.valueOf(1234), "1234" }, }; int testNum = 1; for (Object[] testCase : TEST_CASES) { // 0: locale // 1: pattern ULocale locale = testCase[0] == null ? ULocale.getDefault() : (ULocale)testCase[0]; String pattern = (String)testCase[1]; DecimalFormat fmt = new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(locale)); // 2: rounding mode Integer roundingMode = null; if (testCase[2] != null) { roundingMode = (Integer)testCase[2]; fmt.setRoundingMode(roundingMode); } // 3: rounding increment if (testCase[3] != null) { if (testCase[3] instanceof Double) { fmt.setRoundingIncrement((Double)testCase[3]); } else if (testCase[3] instanceof BigDecimal) { fmt.setRoundingIncrement((BigDecimal)testCase[3]); } else if (testCase[3] instanceof java.math.BigDecimal) { fmt.setRoundingIncrement((java.math.BigDecimal)testCase[3]); } } // 4: input number String s = null; boolean bException = false; try { s = fmt.format(testCase[4]); } catch (ArithmeticException e) { bException = true; } if (bException) { if (testCase[5] != null) { errln("Test case #" + testNum + ": ArithmeticException was thrown."); } } else { if (testCase[5] == null) { errln("Test case #" + testNum + ": ArithmeticException must be thrown, but got formatted result: " + s); } else { assertEquals("Test case #" + testNum, testCase[5], s); } } testNum++; } } @Test public void TestSignificantDigits() { double input[] = { 0, 0, 123, -123, 12345, -12345, 123.45, -123.45, 123.44501, -123.44501, 0.001234, -0.001234, 0.00000000123, -0.00000000123, 0.0000000000000000000123, -0.0000000000000000000123, 1.2, -1.2, 0.0000000012344501, -0.0000000012344501, 123445.01, -123445.01, 12344501000000000000000000000000000.0, -12344501000000000000000000000000000.0, }; String[] expected = { "0.00", "0.00", "123", "-123", "12345", "-12345", "123.45", "-123.45", "123.45", "-123.45", "0.001234", "-0.001234", "0.00000000123", "-0.00000000123", "0.0000000000000000000123", "-0.0000000000000000000123", "1.20", "-1.20", "0.0000000012345", "-0.0000000012345", "123450", "-123450", "12345000000000000000000000000000000", "-12345000000000000000000000000000000", }; DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(ULocale.US); numberFormat.setSignificantDigitsUsed(true); numberFormat.setMinimumSignificantDigits(3); numberFormat.setMaximumSignificantDigits(5); numberFormat.setGroupingUsed(false); for (int i = 0; i < input.length; i++) { assertEquals("TestSignificantDigits", expected[i], numberFormat.format(input[i])); } // Test for ICU-20063 { DecimalFormat df = new DecimalFormat("0.######", DecimalFormatSymbols.getInstance(ULocale.US)); df.setSignificantDigitsUsed(true); expect(df, 9.87654321, "9.87654"); df.setMaximumSignificantDigits(3); expect(df, 9.87654321, "9.88"); // setSignificantDigitsUsed with maxSig only df.setSignificantDigitsUsed(true); expect(df, 9.87654321, "9.88"); df.setMinimumSignificantDigits(2); expect(df, 9, "9.0"); // setSignificantDigitsUsed with both minSig and maxSig df.setSignificantDigitsUsed(true); expect(df, 9, "9.0"); // setSignificantDigitsUsed to false: should revert to fraction rounding df.setSignificantDigitsUsed(false); expect(df, 9.87654321, "9.876543"); expect(df, 9, "9"); df.setSignificantDigitsUsed(true); df.setMinimumSignificantDigits(2); expect(df, 9.87654321, "9.87654"); expect(df, 9, "9.0"); // setSignificantDigitsUsed with minSig only df.setSignificantDigitsUsed(true); expect(df, 9.87654321, "9.87654"); expect(df, 9, "9.0"); } } @Test public void TestBug9936() { DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(ULocale.US); assertFalse("", numberFormat.areSignificantDigitsUsed()); numberFormat.setSignificantDigitsUsed(true); assertTrue("", numberFormat.areSignificantDigitsUsed()); numberFormat.setSignificantDigitsUsed(false); assertFalse("", numberFormat.areSignificantDigitsUsed()); numberFormat.setMinimumSignificantDigits(3); assertTrue("", numberFormat.areSignificantDigitsUsed()); numberFormat.setSignificantDigitsUsed(false); numberFormat.setMaximumSignificantDigits(6); assertTrue("", numberFormat.areSignificantDigitsUsed()); } @Test public void TestShowZero() { DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(ULocale.US); numberFormat.setSignificantDigitsUsed(true); numberFormat.setMaximumSignificantDigits(3); assertEquals("TestShowZero", "0", numberFormat.format(0.0)); } @Test public void TestCurrencyPlurals() { String[][] tests = { {"en", "USD", "1", "1 US dollar"}, {"en", "USD", "1.0", "1.0 US dollars"}, {"en", "USD", "1.00", "1.00 US dollars"}, {"en", "USD", "1.99", "1.99 US dollars"}, {"en", "AUD", "1", "1 Australian dollar"}, {"en", "AUD", "1.00", "1.00 Australian dollars"}, {"sl", "USD", "1", "1 ameri\u0161ki dolar"}, {"sl", "USD", "2", "2 ameri\u0161ka dolarja"}, {"sl", "USD", "3", "3 ameri\u0161ki dolarji"}, {"sl", "USD", "5", "5 ameriških dolarjev"}, {"fr", "USD", "1.99", "1,99 dollar des États-Unis"}, {"ru", "RUB", "1", "1 \u0440\u043E\u0441\u0441\u0438\u0439\u0441\u043A\u0438\u0439 \u0440\u0443\u0431\u043B\u044C"}, {"ru", "RUB", "2", "2 \u0440\u043E\u0441\u0441\u0438\u0439\u0441\u043A\u0438\u0445 \u0440\u0443\u0431\u043B\u044F"}, {"ru", "RUB", "5", "5 \u0440\u043E\u0441\u0441\u0438\u0439\u0441\u043A\u0438\u0445 \u0440\u0443\u0431\u043B\u0435\u0439"}, }; for (String test[] : tests) { DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getInstance(new ULocale(test[0]), NumberFormat.PLURALCURRENCYSTYLE); numberFormat.setCurrency(Currency.getInstance(test[1])); double number = Double.parseDouble(test[2]); int dotPos = test[2].indexOf('.'); int decimals = dotPos < 0 ? 0 : test[2].length() - dotPos - 1; int digits = dotPos < 0 ? test[2].length() : test[2].length() - 1; numberFormat.setMaximumFractionDigits(decimals); numberFormat.setMinimumFractionDigits(decimals); String actual = numberFormat.format(number); assertEquals(test[0] + "\t" + test[1] + "\t" + test[2], test[3], actual); numberFormat.setMaximumSignificantDigits(digits); numberFormat.setMinimumSignificantDigits(digits); actual = numberFormat.format(number); assertEquals(test[0] + "\t" + test[1] + "\t" + test[2], test[3], actual); } } @Test public void TestCustomCurrencySignAndSeparator() { DecimalFormatSymbols custom = new DecimalFormatSymbols(ULocale.US); custom.setCurrencySymbol("*"); custom.setMonetaryGroupingSeparator('^'); custom.setMonetaryDecimalSeparator(':'); DecimalFormat fmt = new DecimalFormat("\u00A4 #,##0.00", custom); final String numstr = "* 1^234:56"; expect2(fmt, 1234.56, numstr); } @Test public void TestParseSignsAndMarks() { class SignsAndMarksItem { public String locale; public boolean lenient; public String numString; public double value; // Simple constructor public SignsAndMarksItem(String loc, boolean lnt, String numStr, double val) { locale = loc; lenient = lnt; numString = numStr; value = val; } }; final SignsAndMarksItem[] items = { // *** Note, ICU4J lenient number parsing does not handle arbitrary whitespace, but can // treat some whitespace as a grouping separator. The cases marked *** below depend // on isGroupingUsed() being set for the locale, which in turn depends on grouping // separators being present in the decimalFormat pattern for the locale (& num sys). // // locale lenient numString value new SignsAndMarksItem("en", false, "12", 12 ), new SignsAndMarksItem("en", true, "12", 12 ), new SignsAndMarksItem("en", false, "-23", -23 ), new SignsAndMarksItem("en", true, "-23", -23 ), new SignsAndMarksItem("en", true, "- 23", -23 ), // *** new SignsAndMarksItem("en", false, "\u200E-23", -23 ), new SignsAndMarksItem("en", true, "\u200E-23", -23 ), new SignsAndMarksItem("en", true, "\u200E- 23", -23 ), // *** new SignsAndMarksItem("en@numbers=arab", false, "\u0663\u0664", 34 ), new SignsAndMarksItem("en@numbers=arab", true, "\u0663\u0664", 34 ), new SignsAndMarksItem("en@numbers=arab", false, "-\u0664\u0665", -45 ), new SignsAndMarksItem("en@numbers=arab", true, "-\u0664\u0665", -45 ), new SignsAndMarksItem("en@numbers=arab", true, "- \u0664\u0665", -45 ), // *** new SignsAndMarksItem("en@numbers=arab", false, "\u200F-\u0664\u0665", -45 ), new SignsAndMarksItem("en@numbers=arab", true, "\u200F-\u0664\u0665", -45 ), new SignsAndMarksItem("en@numbers=arab", true, "\u200F- \u0664\u0665", -45 ), // *** new SignsAndMarksItem("en@numbers=arabext", false, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("en@numbers=arabext", true, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("en@numbers=arabext", false, "-\u06F6\u06F7", -67 ), new SignsAndMarksItem("en@numbers=arabext", true, "-\u06F6\u06F7", -67 ), new SignsAndMarksItem("en@numbers=arabext", true, "- \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("en@numbers=arabext", false, "\u200E-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("en@numbers=arabext", true, "\u200E-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("en@numbers=arabext", true, "\u200E-\u200E \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("he", false, "12", 12 ), new SignsAndMarksItem("he", true, "12", 12 ), new SignsAndMarksItem("he", false, "-23", -23 ), new SignsAndMarksItem("he", true, "-23", -23 ), new SignsAndMarksItem("he", true, "- 23", -23 ), // *** new SignsAndMarksItem("he", false, "\u200E-23", -23 ), new SignsAndMarksItem("he", true, "\u200E-23", -23 ), new SignsAndMarksItem("he", true, "\u200E- 23", -23 ), // *** new SignsAndMarksItem("ar", false, "\u0663\u0664", 34 ), new SignsAndMarksItem("ar", true, "\u0663\u0664", 34 ), new SignsAndMarksItem("ar", false, "-\u0664\u0665", -45 ), new SignsAndMarksItem("ar", true, "-\u0664\u0665", -45 ), new SignsAndMarksItem("ar", true, "- \u0664\u0665", -45 ), // *** new SignsAndMarksItem("ar", false, "\u200F-\u0664\u0665", -45 ), new SignsAndMarksItem("ar", true, "\u200F-\u0664\u0665", -45 ), new SignsAndMarksItem("ar", true, "\u200F- \u0664\u0665", -45 ), // *** new SignsAndMarksItem("ar_MA", false, "12", 12 ), new SignsAndMarksItem("ar_MA", true, "12", 12 ), new SignsAndMarksItem("ar_MA", false, "-23", -23 ), new SignsAndMarksItem("ar_MA", true, "-23", -23 ), new SignsAndMarksItem("ar_MA", true, "- 23", -23 ), // *** new SignsAndMarksItem("ar_MA", false, "\u200E-23", -23 ), new SignsAndMarksItem("ar_MA", true, "\u200E-23", -23 ), new SignsAndMarksItem("ar_MA", true, "\u200E- 23", -23 ), // *** new SignsAndMarksItem("fa", false, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("fa", true, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("fa", false, "\u2212\u06F6\u06F7", -67 ), new SignsAndMarksItem("fa", true, "\u2212\u06F6\u06F7", -67 ), new SignsAndMarksItem("fa", true, "\u2212 \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("fa", false, "\u200E\u2212\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("fa", true, "\u200E\u2212\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("fa", true, "\u200E\u2212\u200E \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("ps", false, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("ps", true, "\u06F5\u06F6", 56 ), new SignsAndMarksItem("ps", false, "-\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "-\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "- \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("ps", false, "\u200E-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "\u200E-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "\u200E-\u200E \u06F6\u06F7", -67 ), // *** new SignsAndMarksItem("ps", false, "-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "-\u200E\u06F6\u06F7", -67 ), new SignsAndMarksItem("ps", true, "-\u200E \u06F6\u06F7", -67 ), // *** }; for (SignsAndMarksItem item: items) { ULocale locale = new ULocale(item.locale); NumberFormat numfmt = NumberFormat.getInstance(locale); if (numfmt != null) { numfmt.setParseStrict(!item.lenient); ParsePosition ppos = new ParsePosition(0); Number num = numfmt.parse(item.numString, ppos); if (num != null && ppos.getIndex() == item.numString.length()) { double parsedValue = num.doubleValue(); if (parsedValue != item.value) { errln("FAIL: locale " + item.locale + ", lenient " + item.lenient + ", parse of \"" + item.numString + "\" gives value " + parsedValue); } } else { errln("FAIL: locale " + item.locale + ", lenient " + item.lenient + ", parse of \"" + item.numString + "\" gives position " + ppos.getIndex()); } } else { errln("FAIL: NumberFormat.getInstance for locale " + item.locale); } } } @Test public void TestContext() { // just a minimal sanity check for now NumberFormat nfmt = NumberFormat.getInstance(); DisplayContext context = nfmt.getContext(DisplayContext.Type.CAPITALIZATION); if (context != DisplayContext.CAPITALIZATION_NONE) { errln("FAIL: Initial NumberFormat.getContext() is not CAPITALIZATION_NONE"); } nfmt.setContext(DisplayContext.CAPITALIZATION_FOR_STANDALONE); context = nfmt.getContext(DisplayContext.Type.CAPITALIZATION); if (context != DisplayContext.CAPITALIZATION_FOR_STANDALONE) { errln("FAIL: NumberFormat.getContext() does not return the value set, CAPITALIZATION_FOR_STANDALONE"); } } @Test public void TestAccountingCurrency() { String[][] tests = { //locale num curr fmt per loc curr std fmt curr acct fmt rt {"en_US", "1234.5", "$1,234.50", "$1,234.50", "$1,234.50", "true"}, {"en_US@cf=account", "1234.5", "$1,234.50", "$1,234.50", "$1,234.50", "true"}, {"en_US", "-1234.5", "-$1,234.50", "-$1,234.50", "($1,234.50)", "true"}, {"en_US@cf=standard", "-1234.5", "-$1,234.50", "-$1,234.50", "($1,234.50)", "true"}, {"en_US@cf=account", "-1234.5", "($1,234.50)", "-$1,234.50", "($1,234.50)", "true"}, {"en_US", "0", "$0.00", "$0.00", "$0.00", "true"}, {"en_US", "-0.2", "-$0.20", "-$0.20", "($0.20)", "true"}, {"en_US@cf=standard", "-0.2", "-$0.20", "-$0.20", "($0.20)", "true"}, {"en_US@cf=account", "-0.2", "($0.20)", "-$0.20", "($0.20)", "true"}, {"ja_JP", "10000", "¥10,000", "¥10,000", "¥10,000", "true" }, {"ja_JP", "-1000.5", "-¥1,000", "-¥1,000", "(¥1,000)", "false"}, {"ja_JP@cf=account", "-1000.5", "(¥1,000)", "-¥1,000", "(¥1,000)", "false"}, {"de_DE", "-23456.7", "-23.456,70\u00A0€", "-23.456,70\u00A0€", "-23.456,70\u00A0€", "true" }, }; for (String[] data : tests) { ULocale loc = new ULocale(data[0]); double num = Double.parseDouble(data[1]); String fmtPerLocExpected = data[2]; String fmtStandardExpected = data[3]; String fmtAccountExpected = data[4]; boolean rt = Boolean.parseBoolean(data[5]); NumberFormat fmtPerLoc = NumberFormat.getInstance(loc, NumberFormat.CURRENCYSTYLE); expect(fmtPerLoc, num, fmtPerLocExpected, rt); NumberFormat fmtStandard = NumberFormat.getInstance(loc, NumberFormat.STANDARDCURRENCYSTYLE); expect(fmtStandard, num, fmtStandardExpected, rt); NumberFormat fmtAccount = NumberFormat.getInstance(loc, NumberFormat.ACCOUNTINGCURRENCYSTYLE); expect(fmtAccount, num, fmtAccountExpected, rt); } } @Test public void TestCurrencyUsage() { // the 1st one is checking setter/getter, while the 2nd one checks for getInstance // compare the Currency and Currency Cash Digits // Note that as of CLDR 26: // * TWD and PKR switched from 0 decimals to 2; ISK still has 0, so change test to that // * CAD rounds to .05 in the cash style only. for (int i = 0; i < 2; i++) { String original_expected = "ISK 124"; DecimalFormat custom = null; if (i == 0) { custom = (DecimalFormat) DecimalFormat.getInstance(new ULocale("en_US@currency=ISK"), DecimalFormat.CURRENCYSTYLE); String original = custom.format(123.567); assertEquals("Test Currency Context", original_expected, original); // test the getter assertEquals("Test Currency Context Purpose", custom.getCurrencyUsage(), Currency.CurrencyUsage.STANDARD); custom.setCurrencyUsage(Currency.CurrencyUsage.CASH); assertEquals("Test Currency Context Purpose", custom.getCurrencyUsage(), Currency.CurrencyUsage.CASH); } else { custom = (DecimalFormat) DecimalFormat.getInstance(new ULocale("en_US@currency=ISK"), DecimalFormat.CASHCURRENCYSTYLE); // test the getter assertEquals("Test Currency Context Purpose", custom.getCurrencyUsage(), Currency.CurrencyUsage.CASH); } String cash_currency = custom.format(123.567); String cash_currency_expected = "ISK 124"; assertEquals("Test Currency Context", cash_currency_expected, cash_currency); } // the 1st one is checking setter/getter, while the 2nd one checks for getInstance // compare the Currency and Currency Cash Rounding for (int i = 0; i < 2; i++) { String original_rounding_expected = "CA$123.57"; DecimalFormat fmt = null; if (i == 0) { fmt = (DecimalFormat) DecimalFormat.getInstance(new ULocale("en_US@currency=CAD"), DecimalFormat.CURRENCYSTYLE); String original_rounding = fmt.format(123.566); assertEquals("Test Currency Context", original_rounding_expected, original_rounding); fmt.setCurrencyUsage(Currency.CurrencyUsage.CASH); } else { fmt = (DecimalFormat) DecimalFormat.getInstance(new ULocale("en_US@currency=CAD"), DecimalFormat.CASHCURRENCYSTYLE); } String cash_rounding_currency = fmt.format(123.567); String cash__rounding_currency_expected = "CA$123.55"; assertEquals("Test Currency Context", cash__rounding_currency_expected, cash_rounding_currency); } // the 1st one is checking setter/getter, while the 2nd one checks for getInstance // Test the currency change for (int i = 0; i < 2; i++) { DecimalFormat fmt2 = null; if (i == 1) { fmt2 = (DecimalFormat) NumberFormat.getInstance(new ULocale("en_US@currency=JPY"), NumberFormat.CURRENCYSTYLE); fmt2.setCurrencyUsage(Currency.CurrencyUsage.CASH); } else { fmt2 = (DecimalFormat) NumberFormat.getInstance(new ULocale("en_US@currency=JPY"), NumberFormat.CASHCURRENCYSTYLE); } fmt2.setCurrency(Currency.getInstance("PKR")); String PKR_changed = fmt2.format(123.567); String PKR_changed_expected = "PKR 124"; assertEquals("Test Currency Context", PKR_changed_expected, PKR_changed); } } @Test public void TestCurrencyWithMinMaxFractionDigits() { DecimalFormat df = new DecimalFormat(); df.applyPattern("¤#,##0.00"); df.setCurrency(Currency.getInstance("USD")); assertEquals("Basic currency format fails", "$1.23", df.format(1.234)); df.setMaximumFractionDigits(4); assertEquals("Currency with max fraction == 4", "$1.234", df.format(1.234)); df.setMinimumFractionDigits(4); assertEquals("Currency with min fraction == 4", "$1.2340", df.format(1.234)); } @Test public void TestParseRequiredDecimalPoint() { String[] testPattern = { "00.####", "00.0", "00" }; String value2Parse = "99"; String value2ParseWithDecimal = "99.9"; double parseValue = 99; double parseValueWithDecimal = 99.9; DecimalFormat parser = new DecimalFormat(); double result; boolean hasDecimalPoint; for (int i = 0; i < testPattern.length; i++) { parser.applyPattern(testPattern[i]); hasDecimalPoint = testPattern[i].contains("."); parser.setDecimalPatternMatchRequired(false); try { result = parser.parse(value2Parse).doubleValue(); assertEquals("wrong parsed value", parseValue, result); } catch (ParseException e) { TestFmwk.errln("Parsing " + value2Parse + " should have succeeded with " + testPattern[i] + " and isDecimalPointMatchRequired set to: " + parser.isDecimalPatternMatchRequired()); } try { result = parser.parse(value2ParseWithDecimal).doubleValue(); assertEquals("wrong parsed value", parseValueWithDecimal, result); } catch (ParseException e) { TestFmwk.errln("Parsing " + value2ParseWithDecimal + " should have succeeded with " + testPattern[i] + " and isDecimalPointMatchRequired set to: " + parser.isDecimalPatternMatchRequired()); } parser.setDecimalPatternMatchRequired(true); try { result = parser.parse(value2Parse).doubleValue(); if(hasDecimalPoint){ TestFmwk.errln("Parsing " + value2Parse + " should NOT have succeeded with " + testPattern[i] + " and isDecimalPointMatchRequired set to: " + parser.isDecimalPatternMatchRequired()); } } catch (ParseException e) { // OK, should fail } try { result = parser.parse(value2ParseWithDecimal).doubleValue(); if(!hasDecimalPoint){ TestFmwk.errln("Parsing " + value2ParseWithDecimal + " should NOT have succeeded with " + testPattern[i] + " and isDecimalPointMatchRequired set to: " + parser.isDecimalPatternMatchRequired() + " (got: " + result + ")"); } } catch (ParseException e) { // OK, should fail } } } @Test public void TestCurrFmtNegSameAsPositive() { DecimalFormatSymbols decfmtsym = DecimalFormatSymbols.getInstance(Locale.US); decfmtsym.setMinusSign('\u200B'); // ZERO WIDTH SPACE, in ICU4J cannot set to empty string DecimalFormat decfmt = new DecimalFormat("\u00A4#,##0.00;-\u00A4#,##0.00", decfmtsym); String currFmtResult = decfmt.format(-100.0); if (!currFmtResult.equals("\u200B$100.00")) { errln("decfmt.toPattern results wrong, expected \u200B$100.00, got " + currFmtResult); } } @Test public void TestNumberFormatTestDataToString() { new DataDrivenNumberFormatTestData().toString(); } // Testing for Issue 11805. @Test public void TestFormatToCharacterIteratorIssue11805 () { final double number = -350.76; DecimalFormat dfUS = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.US); String strUS = dfUS.format(number); Set<AttributedCharacterIterator.Attribute> resultUS = dfUS.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative US Results: " + strUS, 5, resultUS.size()); // For each test, add assert that all the fields are present and in the right spot. // TODO: Add tests for identify and position of each field, as in IntlTestDecimalFormatAPIC. DecimalFormat dfDE = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.GERMANY); String strDE = dfDE.format(number); Set<AttributedCharacterIterator.Attribute> resultDE = dfDE.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative DE Results: " + strDE, 5, resultDE.size()); DecimalFormat dfIN = (DecimalFormat) DecimalFormat.getCurrencyInstance(new Locale("hi", "in")); String strIN = dfIN.format(number); Set<AttributedCharacterIterator.Attribute> resultIN = dfIN.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative IN Results: " + strIN, 5, resultIN.size()); DecimalFormat dfJP = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.JAPAN); String strJP = dfJP.format(number); Set<AttributedCharacterIterator.Attribute> resultJP = dfJP.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative JA Results: " + strJP, 3, resultJP.size()); DecimalFormat dfGB = (DecimalFormat) DecimalFormat.getCurrencyInstance(new Locale("en", "gb")); String strGB = dfGB.format(number); Set<AttributedCharacterIterator.Attribute> resultGB = dfGB.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative GB Results: " + strGB , 5, resultGB.size()); DecimalFormat dfPlural = (DecimalFormat) NumberFormat.getInstance(new Locale("en", "gb"), NumberFormat.PLURALCURRENCYSTYLE); strGB = dfPlural.format(number); resultGB = dfPlural.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative GB Results: " + strGB , 5, resultGB.size()); strGB = dfPlural.format(1); resultGB = dfPlural.formatToCharacterIterator(1).getAllAttributeKeys(); assertEquals("Negative GB Results: " + strGB , 4, resultGB.size()); // Test output with unit value. DecimalFormat auPlural = (DecimalFormat) NumberFormat.getInstance(new Locale("en", "au"), NumberFormat.PLURALCURRENCYSTYLE); String strAU = auPlural.format(1L); Set<AttributedCharacterIterator.Attribute> resultAU = auPlural.formatToCharacterIterator(1L).getAllAttributeKeys(); assertEquals("Unit AU Result: " + strAU , 4, resultAU.size()); // Verify Permille fields. DecimalFormatSymbols sym = new DecimalFormatSymbols(new Locale("en", "gb")); DecimalFormat dfPermille = new DecimalFormat("####0.##\u2030", sym); strGB = dfPermille.format(number); resultGB = dfPermille.formatToCharacterIterator(number).getAllAttributeKeys(); assertEquals("Negative GB Permille Results: " + strGB , 3, resultGB.size()); } // Testing for Issue 11808. @Test public void TestRoundUnnecessarytIssue11808 () { DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(); StringBuffer result = new StringBuffer(""); df.setRoundingMode(BigDecimal.ROUND_UNNECESSARY); df.applyPattern("00.0#E0"); try { df.format(99999.0, result, new FieldPosition(0)); fail("Missing ArithmeticException for double: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } try { result = df.format(99999, result, new FieldPosition(0)); fail("Missing ArithmeticException for int: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } try { result = df.format(new BigInteger("999999"), result, new FieldPosition(0)); fail("Missing ArithmeticException for BigInteger: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } try { result = df.format(new BigDecimal("99999"), result, new FieldPosition(0)); fail("Missing ArithmeticException for BigDecimal: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } try { result = df.format(new BigDecimal("-99999"), result, new FieldPosition(0)); fail("Missing ArithmeticException for BigDecimal: " + result); } catch (ArithmeticException expected) { // The exception should be thrown, since rounding is needed. } } // Testing for Issue 11735. @Test public void TestNPEIssue11735() { DecimalFormat fmt = new DecimalFormat("0", new DecimalFormatSymbols(new ULocale("en"))); ParsePosition ppos = new ParsePosition(0); assertEquals("Currency symbol missing in parse. Expect null result.", fmt.parseCurrency("53.45", ppos), null); } private void CompareAttributedCharacterFormatOutput(AttributedCharacterIterator iterator, List<FieldContainer> expected, String formattedOutput) { List<FieldContainer> result = new ArrayList<>(); while (iterator.getIndex() != iterator.getEndIndex()) { int start = iterator.getRunStart(); int end = iterator.getRunLimit(); Iterator it = iterator.getAttributes().keySet().iterator(); AttributedCharacterIterator.Attribute attribute = (AttributedCharacterIterator.Attribute) it.next(); // For positions with both INTEGER and GROUPING attributes, we want the GROUPING attribute. if (it.hasNext() && attribute.equals(NumberFormat.Field.INTEGER)) { attribute = (AttributedCharacterIterator.Attribute) it.next(); } Object value = iterator.getAttribute(attribute); result.add(new FieldContainer(start, end, attribute, value)); iterator.setIndex(end); } assertEquals("Comparing vector length for " + formattedOutput, expected.size(), result.size()); if (!expected.containsAll(result)) { // Print information on the differences. for (int i = 0; i < expected.size(); i++) { System.out.println(" expected[" + i + "] =" + expected.get(i).start + " " + expected.get(i).end + " " + expected.get(i).attribute + " " + expected.get(i).value); System.out.println(" result[" + i + "] =" + result.get(i).start + " " + result.get(i).end + " " + result.get(i).attribute + " " + result.get(i).value); } } assertTrue("Comparing vector results for " + formattedOutput, expected.containsAll(result)); } // Testing for Issue 11914, missing FieldPositions for some field types. @Test public void TestNPEIssue11914() { // First test: Double value with grouping separators. List<FieldContainer> v1 = new ArrayList<>(7); v1.add(new FieldContainer(0, 3, NumberFormat.Field.INTEGER)); v1.add(new FieldContainer(3, 4, NumberFormat.Field.GROUPING_SEPARATOR)); v1.add(new FieldContainer(4, 7, NumberFormat.Field.INTEGER)); v1.add(new FieldContainer(7, 8, NumberFormat.Field.GROUPING_SEPARATOR)); v1.add(new FieldContainer(8, 11, NumberFormat.Field.INTEGER)); v1.add(new FieldContainer(11, 12, NumberFormat.Field.DECIMAL_SEPARATOR)); v1.add(new FieldContainer(12, 15, NumberFormat.Field.FRACTION)); Number number = new Double(123456789.9753); ULocale usLoc = new ULocale("en-US"); DecimalFormatSymbols US = new DecimalFormatSymbols(usLoc); NumberFormat outFmt = NumberFormat.getNumberInstance(usLoc); String numFmtted = outFmt.format(number); AttributedCharacterIterator iterator = outFmt.formatToCharacterIterator(number); CompareAttributedCharacterFormatOutput(iterator, v1, numFmtted); // Second test: Double with scientific notation formatting. List<FieldContainer> v2 = new ArrayList<>(7); v2.add(new FieldContainer(0, 1, NumberFormat.Field.INTEGER)); v2.add(new FieldContainer(1, 2, NumberFormat.Field.DECIMAL_SEPARATOR)); v2.add(new FieldContainer(2, 5, NumberFormat.Field.FRACTION)); v2.add(new FieldContainer(5, 6, NumberFormat.Field.EXPONENT_SYMBOL)); v2.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT_SIGN)); v2.add(new FieldContainer(7, 8, NumberFormat.Field.EXPONENT)); DecimalFormat fmt2 = new DecimalFormat("0.###E+0", US); numFmtted = fmt2.format(number); iterator = fmt2.formatToCharacterIterator(number); CompareAttributedCharacterFormatOutput(iterator, v2, numFmtted); // Third test. BigInteger with grouping separators. List<FieldContainer> v3 = new ArrayList<>(7); v3.add(new FieldContainer(0, 1, NumberFormat.Field.SIGN)); v3.add(new FieldContainer(1, 2, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(2, 3, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(3, 6, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(6, 7, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(7, 10, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(10, 11, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(11, 14, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(14, 15, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(15, 18, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(18, 19, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(19, 22, NumberFormat.Field.INTEGER)); v3.add(new FieldContainer(22, 23, NumberFormat.Field.GROUPING_SEPARATOR)); v3.add(new FieldContainer(23, 26, NumberFormat.Field.INTEGER)); BigInteger bigNumberInt = new BigInteger("-1234567890246813579"); String fmtNumberBigInt = outFmt.format(bigNumberInt); iterator = outFmt.formatToCharacterIterator(bigNumberInt); CompareAttributedCharacterFormatOutput(iterator, v3, fmtNumberBigInt); // Fourth test: BigDecimal with exponential formatting. List<FieldContainer> v4 = new ArrayList<>(7); v4.add(new FieldContainer(0, 1, NumberFormat.Field.SIGN)); v4.add(new FieldContainer(1, 2, NumberFormat.Field.INTEGER)); v4.add(new FieldContainer(2, 3, NumberFormat.Field.DECIMAL_SEPARATOR)); v4.add(new FieldContainer(3, 6, NumberFormat.Field.FRACTION)); v4.add(new FieldContainer(6, 7, NumberFormat.Field.EXPONENT_SYMBOL)); v4.add(new FieldContainer(7, 8, NumberFormat.Field.EXPONENT_SIGN)); v4.add(new FieldContainer(8, 9, NumberFormat.Field.EXPONENT)); java.math.BigDecimal numberBigD = new java.math.BigDecimal(-123456789); String fmtNumberBigDExp = fmt2.format(numberBigD); iterator = fmt2.formatToCharacterIterator(numberBigD); CompareAttributedCharacterFormatOutput(iterator, v4, fmtNumberBigDExp); } // Test that the decimal is shown even when there are no fractional digits @Test public void Test11621() throws Exception { String pat = "0.##E0"; DecimalFormatSymbols icuSym = new DecimalFormatSymbols(Locale.US); DecimalFormat icuFmt = new DecimalFormat(pat, icuSym); icuFmt.setDecimalSeparatorAlwaysShown(true); String icu = ((NumberFormat)icuFmt).format(299792458); java.text.DecimalFormatSymbols jdkSym = new java.text.DecimalFormatSymbols(Locale.US); java.text.DecimalFormat jdkFmt = new java.text.DecimalFormat(pat,jdkSym); jdkFmt.setDecimalSeparatorAlwaysShown(true); String jdk = ((java.text.NumberFormat)jdkFmt).format(299792458); assertEquals("ICU and JDK placement of decimal in exponent", jdk, icu); } private void checkFormatWithField(String testInfo, Format format, Object object, String expected, Format.Field field, int begin, int end) { StringBuffer buffer = new StringBuffer(); FieldPosition pos = new FieldPosition(field); format.format(object, buffer, pos); assertEquals("Test " + testInfo + ": incorrect formatted text", expected, buffer.toString()); if (begin != pos.getBeginIndex() || end != pos.getEndIndex()) { assertEquals("Index mismatch", field + " " + begin + ".." + end, pos.getFieldAttribute() + " " + pos.getBeginIndex() + ".." + pos.getEndIndex()); } } @Test public void TestMissingFieldPositionsCurrency() { DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(ULocale.US); Number number = new Double(92314587.66); String result = "$92,314,587.66"; checkFormatWithField("currency", formatter, number, result, NumberFormat.Field.CURRENCY, 0, 1); checkFormatWithField("integer", formatter, number, result, NumberFormat.Field.INTEGER, 1, 11); checkFormatWithField("grouping separator", formatter, number, result, NumberFormat.Field.GROUPING_SEPARATOR, 3, 4); checkFormatWithField("decimal separator", formatter, number, result, NumberFormat.Field.DECIMAL_SEPARATOR, 11, 12); checkFormatWithField("fraction", formatter, number, result, NumberFormat.Field.FRACTION, 12, 14); } @Test public void TestMissingFieldPositionsNegativeDouble() { // test for exponential fields with double DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); Number number = new Double(-12345678.90123); DecimalFormat formatter = new DecimalFormat("0.#####E+00", us_symbols); String numFmtted = formatter.format(number); checkFormatWithField("sign", formatter, number, numFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", formatter, number, numFmtted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", formatter, number, numFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("exponent symbol", formatter, number, numFmtted, NumberFormat.Field.EXPONENT_SYMBOL, 8, 9); checkFormatWithField("exponent sign", formatter, number, numFmtted, NumberFormat.Field.EXPONENT_SIGN, 9, 10); checkFormatWithField("exponent", formatter, number, numFmtted, NumberFormat.Field.EXPONENT, 10, 12); } @Test public void TestMissingFieldPositionsPerCent() { // Check PERCENT DecimalFormat percentFormat = (DecimalFormat) NumberFormat.getPercentInstance(ULocale.US); Number number = new Double(-0.986); String numberFormatted = percentFormat.format(number); checkFormatWithField("sign", percentFormat, number, numberFormatted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", percentFormat, number, numberFormatted, NumberFormat.Field.INTEGER, 1, 3); checkFormatWithField("percent", percentFormat, number, numberFormatted, NumberFormat.Field.PERCENT, 3, 4); } @Test public void TestMissingFieldPositionsPerCentPattern() { // Check PERCENT with more digits DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat fmtPercent = new DecimalFormat("0.#####%", us_symbols); Number number = new Double(-0.986); String numFmtted = fmtPercent.format(number); checkFormatWithField("sign", fmtPercent, number, numFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", fmtPercent, number, numFmtted, NumberFormat.Field.INTEGER, 1, 3); checkFormatWithField("decimal separator", fmtPercent, number, numFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 3, 4); checkFormatWithField("fraction", fmtPercent, number, numFmtted, NumberFormat.Field.FRACTION, 4, 5); checkFormatWithField("percent", fmtPercent, number, numFmtted, NumberFormat.Field.PERCENT, 5, 6); } @Test public void TestMissingFieldPositionsPerMille() { // Check PERMILLE DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat fmtPerMille = new DecimalFormat("0.######‰", us_symbols); Number numberPermille = new Double(-0.98654); String numFmtted = fmtPerMille.format(numberPermille); checkFormatWithField("sign", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.INTEGER, 1, 4); checkFormatWithField("decimal separator", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 4, 5); checkFormatWithField("fraction", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.FRACTION, 5, 7); checkFormatWithField("permille", fmtPerMille, numberPermille, numFmtted, NumberFormat.Field.PERMILLE, 7, 8); } @Test public void TestMissingFieldPositionsNegativeBigInt() { DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat formatter = new DecimalFormat("0.#####E+0", us_symbols); Number number = new BigDecimal("-123456789987654321"); String bigDecFmtted = formatter.format(number); checkFormatWithField("sign", formatter, number, bigDecFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", formatter, number, bigDecFmtted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", formatter, number, bigDecFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("exponent symbol", formatter, number, bigDecFmtted, NumberFormat.Field.EXPONENT_SYMBOL, 8, 9); checkFormatWithField("exponent sign", formatter, number, bigDecFmtted, NumberFormat.Field.EXPONENT_SIGN, 9, 10); checkFormatWithField("exponent", formatter, number, bigDecFmtted, NumberFormat.Field.EXPONENT, 10, 12); } @Test public void TestMissingFieldPositionsNegativeLong() { Number number = new Long("-123456789987654321"); DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat formatter = new DecimalFormat("0.#####E+0", us_symbols); String longFmtted = formatter.format(number); checkFormatWithField("sign", formatter, number, longFmtted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", formatter, number, longFmtted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", formatter, number, longFmtted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("exponent symbol", formatter, number, longFmtted, NumberFormat.Field.EXPONENT_SYMBOL, 8, 9); checkFormatWithField("exponent sign", formatter, number, longFmtted, NumberFormat.Field.EXPONENT_SIGN, 9, 10); checkFormatWithField("exponent", formatter, number, longFmtted, NumberFormat.Field.EXPONENT, 10, 12); } @Test public void TestMissingFieldPositionsPositiveBigDec() { // Check complex positive;negative pattern. DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat fmtPosNegSign = new DecimalFormat("+0.####E+00;-0.#######E+0", us_symbols); Number positiveExp = new Double("9876543210"); String posExpFormatted = fmtPosNegSign.format(positiveExp); checkFormatWithField("sign", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("fraction", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.FRACTION, 3, 7); checkFormatWithField("exponent symbol", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.EXPONENT_SYMBOL, 7, 8); checkFormatWithField("exponent sign", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.EXPONENT_SIGN, 8, 9); checkFormatWithField("exponent", fmtPosNegSign, positiveExp, posExpFormatted, NumberFormat.Field.EXPONENT, 9, 11); } @Test public void TestMissingFieldPositionsNegativeBigDec() { // Check complex positive;negative pattern. DecimalFormatSymbols us_symbols = new DecimalFormatSymbols(ULocale.US); DecimalFormat fmtPosNegSign = new DecimalFormat("+0.####E+00;-0.#######E+0", us_symbols); Number negativeExp = new BigDecimal("-0.000000987654321083"); String negExpFormatted = fmtPosNegSign.format(negativeExp); checkFormatWithField("sign", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.SIGN, 0, 1); checkFormatWithField("integer", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.INTEGER, 1, 2); checkFormatWithField("decimal separator", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3); checkFormatWithField("fraction", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.FRACTION, 3, 7); checkFormatWithField("exponent symbol", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.EXPONENT_SYMBOL, 7, 8); checkFormatWithField("exponent sign", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.EXPONENT_SIGN, 8, 9); checkFormatWithField("exponent", fmtPosNegSign, negativeExp, negExpFormatted, NumberFormat.Field.EXPONENT, 9, 11); } @Test public void TestStringSymbols() { DecimalFormatSymbols symbols = new DecimalFormatSymbols(ULocale.US); // Attempt digits with multiple code points. String[] customDigits = {"(0)", "(1)", "(2)", "(3)", "(4)", "(5)", "(6)", "(7)", "(8)", "(9)"}; symbols.setDigitStrings(customDigits); DecimalFormat fmt = new DecimalFormat("#,##0.0#", symbols); expect2(fmt, 1234567.89, "(1),(2)(3)(4),(5)(6)(7).(8)(9)"); // Scientific notation should work. fmt.applyPattern("@@@E0"); expect2(fmt, 1230000, "(1).(2)(3)E(6)"); // Grouping and decimal with multiple code points (supported in parsing since ICU 61) symbols.setDecimalSeparatorString("~~"); symbols.setGroupingSeparatorString("^^"); fmt.setDecimalFormatSymbols(symbols); fmt.applyPattern("#,##0.0#"); expect2(fmt, 1234567.89, "(1)^^(2)(3)(4)^^(5)(6)(7)~~(8)(9)"); // Digits starting at U+1D7CE MATHEMATICAL BOLD DIGIT ZERO // These are all single code points, so parsing will work. for (int i=0; i<10; i++) customDigits[i] = new String(Character.toChars(0x1D7CE+i)); symbols.setDigitStrings(customDigits); symbols.setDecimalSeparatorString("😁"); symbols.setGroupingSeparatorString("😎"); fmt.setDecimalFormatSymbols(symbols); expect2(fmt, 1234.56, "𝟏😎𝟐𝟑𝟒😁𝟓𝟔"); } @Test public void TestArabicCurrencyPatternInfo() { ULocale arLocale = new ULocale("ar"); DecimalFormatSymbols symbols = new DecimalFormatSymbols(arLocale); String currSpacingPatn = symbols.getPatternForCurrencySpacing(DecimalFormatSymbols.CURRENCY_SPC_CURRENCY_MATCH, true); if (currSpacingPatn==null || currSpacingPatn.length() == 0) { errln("locale ar, getPatternForCurrencySpacing returns null or 0-length string"); } DecimalFormat currAcctFormat = (DecimalFormat)NumberFormat.getInstance(arLocale, NumberFormat.ACCOUNTINGCURRENCYSTYLE); String currAcctPatn = currAcctFormat.toPattern(); if (currAcctPatn==null || currAcctPatn.length() == 0) { errln("locale ar, toPattern for ACCOUNTINGCURRENCYSTYLE returns null or 0-length string"); } } @Test public void TestMinMaxOverrides() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Class<?>[] baseClasses = {NumberFormat.class, NumberFormat.class, DecimalFormat.class}; String[] names = {"Integer", "Fraction", "Significant"}; for (int i = 0; i < 3; i++) { DecimalFormat df = new DecimalFormat(); Class<?> base = baseClasses[i]; String name = names[i]; Method getMinimum = base.getDeclaredMethod("getMinimum" + name + "Digits"); Method setMinimum = base.getDeclaredMethod("setMinimum" + name + "Digits", Integer.TYPE); Method getMaximum = base.getDeclaredMethod("getMaximum" + name + "Digits"); Method setMaximum = base.getDeclaredMethod("setMaximum" + name + "Digits", Integer.TYPE); // Check max overrides min setMinimum.invoke(df, 2); assertEquals(name + " getMin A", 2, getMinimum.invoke(df)); setMaximum.invoke(df, 3); assertEquals(name + " getMin B", 2, getMinimum.invoke(df)); assertEquals(name + " getMax B", 3, getMaximum.invoke(df)); setMaximum.invoke(df, 2); assertEquals(name + " getMin C", 2, getMinimum.invoke(df)); assertEquals(name + " getMax C", 2, getMaximum.invoke(df)); setMaximum.invoke(df, 1); assertEquals(name + " getMin D", 1, getMinimum.invoke(df)); assertEquals(name + " getMax D", 1, getMaximum.invoke(df)); // Check min overrides max setMaximum.invoke(df, 2); assertEquals(name + " getMax E", 2, getMaximum.invoke(df)); setMinimum.invoke(df, 1); assertEquals(name + " getMin F", 1, getMinimum.invoke(df)); assertEquals(name + " getMax F", 2, getMaximum.invoke(df)); setMinimum.invoke(df, 2); assertEquals(name + " getMin G", 2, getMinimum.invoke(df)); assertEquals(name + " getMax G", 2, getMaximum.invoke(df)); setMinimum.invoke(df, 3); assertEquals(name + " getMin H", 3, getMinimum.invoke(df)); assertEquals(name + " getMax H", 3, getMaximum.invoke(df)); } } @Test public void TestSetMathContext() throws ParseException { java.math.MathContext fourDigits = new java.math.MathContext(4); java.math.MathContext unlimitedCeiling = new java.math.MathContext(0, RoundingMode.CEILING); // Test rounding DecimalFormat df = new DecimalFormat(); assertEquals("Default format", "9,876.543", df.format(9876.5432)); df.setMathContext(fourDigits); assertEquals("Format with fourDigits", "9,877", df.format(9876.5432)); df.setMathContext(unlimitedCeiling); assertEquals("Format with unlimitedCeiling", "9,876.544", df.format(9876.5432)); // Test multiplication df = new DecimalFormat("0.000%"); assertEquals("Default multiplication", "12.001%", df.format(0.120011)); df.setMathContext(fourDigits); assertEquals("Multiplication with fourDigits", "12.000%", df.format(0.120011)); df.setMathContext(unlimitedCeiling); assertEquals("Multiplication with unlimitedCeiling", "12.002%", df.format(0.120011)); // Test simple division df = new DecimalFormat("0%"); assertEquals("Default division", 0.12001, df.parse("12.001%").doubleValue()); df.setMathContext(fourDigits); // NOTE: Since ICU 61, division no longer occurs with percentage parsing. // assertEquals("Division with fourDigits", 0.12, df.parse("12.001%").doubleValue()); assertEquals("Division with fourDigits", 0.12001, df.parse("12.001%").doubleValue()); df.setMathContext(unlimitedCeiling); assertEquals("Division with unlimitedCeiling", 0.12001, df.parse("12.001%").doubleValue()); // Test extreme division df = new DecimalFormat(); df.setMultiplier(1000000007); // prime number String hugeNumberString = "9876543212345678987654321234567898765432123456789"; // 49 digits BigInteger huge34Digits = new BigInteger("9876543143209876985185182338271622000000"); BigInteger huge4Digits = new BigInteger("9877000000000000000000000000000000000000"); BigInteger actual34Digits = ((BigDecimal) df.parse(hugeNumberString)).toBigIntegerExact(); assertEquals("Default extreme division", huge34Digits, actual34Digits); df.setMathContext(fourDigits); BigInteger actual4Digits = ((BigDecimal) df.parse(hugeNumberString)).toBigIntegerExact(); assertEquals("Extreme division with fourDigits", huge4Digits, actual4Digits); } /** * ArithmeticException is thrown when inverting multiplier produces a non-terminating * decimal result in conjunction with MathContext of unlimited precision. */ @Test public void testSetMathContextArithmeticException() { DecimalFormat df = new DecimalFormat(); df.setMultiplier(7); try { df.setMathContext(java.math.MathContext.UNLIMITED); fail("Extreme division with unlimited precision should throw ArithmeticException"); } catch (ArithmeticException e) { // expected } } /** * ArithmeticException is thrown when inverting multiplier produces a non-terminating * decimal result in conjunction with MathContext of unlimited precision. */ @Test public void testSetMathContextICUArithmeticException() { DecimalFormat df = new DecimalFormat(); df.setMultiplier(7); try { df.setMathContextICU(new MathContext(0)); fail("Extreme division with unlimited precision should throw ArithmeticException"); } catch (ArithmeticException e) { // expected } } /** * ArithmeticException is thrown when inverting multiplier produces a non-terminating * decimal result in conjunction with MathContext of unlimited precision. */ @Test public void testSetMultiplierArithmeticException() { DecimalFormat df = new DecimalFormat(); df.setMathContext(java.math.MathContext.UNLIMITED); try { df.setMultiplier(7); fail("Extreme division with unlimited precision should throw ArithmeticException"); } catch (ArithmeticException e) { // expected } } @Test public void Test10436() { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH); df.setRoundingMode(MathContext.ROUND_CEILING); df.setMinimumFractionDigits(0); df.setMaximumFractionDigits(0); assertEquals("-.99 should round toward infinity", "-0", df.format(-0.99)); } @Test public void Test10765() { NumberFormat fmt = NumberFormat.getInstance(new ULocale("en")); fmt.setMinimumIntegerDigits(10); FieldPosition pos = new FieldPosition(NumberFormat.Field.GROUPING_SEPARATOR); StringBuffer sb = new StringBuffer(); fmt.format(1234567, sb, pos); assertEquals("Should have multiple grouping separators", "0,001,234,567", sb.toString()); assertEquals("FieldPosition should report the first occurence", 1, pos.getBeginIndex()); assertEquals("FieldPosition should report the first occurence", 2, pos.getEndIndex()); } @Test public void Test10997() { NumberFormat fmt = NumberFormat.getCurrencyInstance(new ULocale("en-US")); fmt.setMinimumFractionDigits(4); fmt.setMaximumFractionDigits(4); String str1 = fmt.format(new CurrencyAmount(123.45, Currency.getInstance("USD"))); String str2 = fmt.format(new CurrencyAmount(123.45, Currency.getInstance("EUR"))); assertEquals("minFrac 4 should be respected in default currency", "$123.4500", str1); assertEquals("minFrac 4 should be respected in different currency", "€123.4500", str2); } @Test public void Test11020() { DecimalFormatSymbols sym = new DecimalFormatSymbols(ULocale.FRANCE); DecimalFormat fmt = new DecimalFormat("0.05E0", sym); String result = fmt.format(12301.2).replace('\u00a0', ' '); assertEquals("Rounding increment should be applied after magnitude scaling", "1,25E4", result); } @Test public void Test11025() { String pattern = "¤¤ **####0.00"; DecimalFormatSymbols sym = new DecimalFormatSymbols(ULocale.FRANCE); DecimalFormat fmt = new DecimalFormat(pattern, sym); String result = fmt.format(433.0); assertEquals("Number should be padded to 11 characters", "EUR *433,00", result); } @Test public void Test11640_TripleCurrencySymbol() { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(); df.applyPattern("¤¤¤ 0"); String result = df.getPositivePrefix(); assertEquals("Triple-currency should give long name on getPositivePrefix", "US dollars ", result); } @Test public void Test11645() { String pattern = "#,##0.0#"; DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(); fmt.applyPattern(pattern); DecimalFormat fmtCopy; final int newMultiplier = 37; fmtCopy = (DecimalFormat) fmt.clone(); assertNotEquals("Value before setter", fmtCopy.getMultiplier(), newMultiplier); fmtCopy.setMultiplier(newMultiplier); assertEquals("Value after setter", fmtCopy.getMultiplier(), newMultiplier); fmtCopy.applyPattern(pattern); assertEquals("Value after applyPattern", fmtCopy.getMultiplier(), newMultiplier); assertFalse("multiplier", fmt.equals(fmtCopy)); final int newRoundingMode = RoundingMode.CEILING.ordinal(); fmtCopy = (DecimalFormat) fmt.clone(); assertNotEquals("Value before setter", fmtCopy.getRoundingMode(), newRoundingMode); fmtCopy.setRoundingMode(newRoundingMode); assertEquals("Value after setter", fmtCopy.getRoundingMode(), newRoundingMode); fmtCopy.applyPattern(pattern); assertEquals("Value after applyPattern", fmtCopy.getRoundingMode(), newRoundingMode); assertFalse("roundingMode", fmt.equals(fmtCopy)); final Currency newCurrency = Currency.getInstance("EAT"); fmtCopy = (DecimalFormat) fmt.clone(); assertNotEquals("Value before setter", fmtCopy.getCurrency(), newCurrency); fmtCopy.setCurrency(newCurrency); assertEquals("Value after setter", fmtCopy.getCurrency(), newCurrency); fmtCopy.applyPattern(pattern); assertEquals("Value after applyPattern", fmtCopy.getCurrency(), newCurrency); assertFalse("currency", fmt.equals(fmtCopy)); final CurrencyUsage newCurrencyUsage = CurrencyUsage.CASH; fmtCopy = (DecimalFormat) fmt.clone(); assertNotEquals("Value before setter", fmtCopy.getCurrencyUsage(), newCurrencyUsage); fmtCopy.setCurrencyUsage(CurrencyUsage.CASH); assertEquals("Value after setter", fmtCopy.getCurrencyUsage(), newCurrencyUsage); fmtCopy.applyPattern(pattern); assertEquals("Value after applyPattern", fmtCopy.getCurrencyUsage(), newCurrencyUsage); assertFalse("currencyUsage", fmt.equals(fmtCopy)); } @Test public void Test11646() { DecimalFormatSymbols symbols = new DecimalFormatSymbols(new ULocale("en_US")); String pattern = "\u00a4\u00a4\u00a4 0.00 %\u00a4\u00a4"; DecimalFormat fmt = new DecimalFormat(pattern, symbols); // Test equality with affixes. set affix methods can't capture special // characters which is why equality should fail. { DecimalFormat fmtCopy = (DecimalFormat) fmt.clone(); assertEquals("", fmt, fmtCopy); fmtCopy.setPositivePrefix(fmtCopy.getPositivePrefix()); assertNotEquals("", fmt, fmtCopy); } { DecimalFormat fmtCopy = (DecimalFormat) fmt.clone(); assertEquals("", fmt, fmtCopy); fmtCopy.setPositiveSuffix(fmtCopy.getPositiveSuffix()); assertNotEquals("", fmt, fmtCopy); } { DecimalFormat fmtCopy = (DecimalFormat) fmt.clone(); assertEquals("", fmt, fmtCopy); fmtCopy.setNegativePrefix(fmtCopy.getNegativePrefix()); assertNotEquals("", fmt, fmtCopy); } { DecimalFormat fmtCopy = (DecimalFormat) fmt.clone(); assertEquals("", fmt, fmtCopy); fmtCopy.setNegativeSuffix(fmtCopy.getNegativeSuffix()); assertNotEquals("", fmt, fmtCopy); } } @Test public void Test11648() { DecimalFormat df = new DecimalFormat("0.00"); df.setScientificNotation(true); String pat = df.toPattern(); assertEquals("A valid scientific notation pattern should be produced", "0.00E0", pat); } @Test public void Test11649() { String pattern = "\u00a4\u00a4\u00a4 0.00"; DecimalFormat fmt = new DecimalFormat(pattern); fmt.setCurrency(Currency.getInstance("USD")); assertEquals("Triple currency sign should format long name", "US dollars 12.34", fmt.format(12.34)); String newPattern = fmt.toPattern(); assertEquals("Should produce a valid pattern", pattern, newPattern); DecimalFormat fmt2 = new DecimalFormat(newPattern); fmt2.setCurrency(Currency.getInstance("USD")); assertEquals("Triple currency sign pattern should round-trip", "US dollars 12.34", fmt2.format(12.34)); String quotedPattern = "\u00a4\u00a4'\u00a4' 0.00"; DecimalFormat fmt3 = new DecimalFormat(quotedPattern); assertEquals("Should be treated as double currency sign", "USD\u00a4 12.34", fmt3.format(12.34)); String outQuotedPattern = fmt3.toPattern(); assertEquals("Double currency sign with quoted sign should round-trip", quotedPattern, outQuotedPattern); } @Test @Ignore public void Test11686() { // Only passes with slow mode. // TODO: Re-enable this test with slow mode. DecimalFormat df = new DecimalFormat(); df.setPositiveSuffix("0K"); df.setNegativeSuffix("0N"); expect2(df, 123, "1230K"); expect2(df, -123, "-1230N"); } @Test public void Test11839() { DecimalFormatSymbols dfs = new DecimalFormatSymbols(ULocale.ENGLISH); dfs.setMinusSignString("a∸"); dfs.setPlusSignString("b∔"); // ∔ U+2214 DOT PLUS DecimalFormat df = new DecimalFormat("0.00+;0.00-", dfs); String result = df.format(-1.234); assertEquals("Locale-specific minus sign should be used", "1.23a∸", result); result = df.format(1.234); assertEquals("Locale-specific plus sign should be used", "1.23b∔", result); // Test round-trip with parse expect2(df, -456, "456.00a∸"); expect2(df, 456, "456.00b∔"); } @Test public void Test12753() { ULocale locale = new ULocale("en-US"); DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); symbols.setDecimalSeparator('*'); DecimalFormat df = new DecimalFormat("0.00", symbols); df.setDecimalPatternMatchRequired(true); try { df.parse("123"); fail("Parsing integer succeeded even though setDecimalPatternMatchRequired was set"); } catch (ParseException e) { // Parse failed (expected) } } @Test public void Test12962() { String pat = "**0.00"; DecimalFormat df = new DecimalFormat(pat); String newPat = df.toPattern(); assertEquals("Format width changed upon calling applyPattern", pat.length(), newPat.length()); } @Test public void Test10354() { DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setNaN(""); DecimalFormat df = new DecimalFormat(); df.setDecimalFormatSymbols(dfs); try { df.formatToCharacterIterator(Double.NaN); // pass } catch (IllegalArgumentException e) { throw new AssertionError(e); } } @Test public void Test11913() { NumberFormat df = DecimalFormat.getInstance(); String result = df.format(new BigDecimal("1.23456789E400")); assertEquals("Should format more than 309 digits", "12,345,678", result.substring(0, 10)); assertEquals("Should format more than 309 digits", 534, result.length()); } @Test public void Test12045() { if (logKnownIssue("12045", "XSU is missing from fr")) { return; } NumberFormat nf = NumberFormat.getInstance(new ULocale("fr"), NumberFormat.PLURALCURRENCYSTYLE); ParsePosition ppos = new ParsePosition(0); try { CurrencyAmount result = nf.parseCurrency("2,34 XSU", ppos); assertEquals("Parsing should succeed on XSU", new CurrencyAmount(2.34, Currency.getInstance("XSU")), result); // pass } catch (Exception e) { //throw new AssertionError("Should have been able to parse XSU", e); throw new AssertionError("Should have been able to parse XSU: " + e.getMessage()); } } @Test public void Test11739() { NumberFormat nf = NumberFormat.getCurrencyInstance(new ULocale("sr_BA")); ((DecimalFormat) nf).applyPattern("#,##0.0 ¤¤¤"); ParsePosition ppos = new ParsePosition(0); CurrencyAmount result = nf.parseCurrency("1.500 амерички долар", ppos); assertEquals("Should parse to 1500 USD", new CurrencyAmount(1500, Currency.getInstance("USD")), result); } @Test public void Test11647() { DecimalFormat df = new DecimalFormat(); df.applyPattern("¤¤¤¤#"); String actual = df.format(123); assertEquals("Should replace 4 currency signs with U+FFFD", "\uFFFD123", actual); } @Test public void Test12567() { DecimalFormat df1 = (DecimalFormat) NumberFormat.getInstance(NumberFormat.PLURALCURRENCYSTYLE); DecimalFormat df2 = (DecimalFormat) NumberFormat.getInstance(NumberFormat.NUMBERSTYLE); df2.setCurrency(df1.getCurrency()); df2.setCurrencyPluralInfo(df1.getCurrencyPluralInfo()); df1.applyPattern("0.00"); df2.applyPattern("0.00"); assertEquals("df1 == df2", df1, df2); assertEquals("df2 == df1", df2, df1); df2.setPositivePrefix("abc"); assertNotEquals("df1 != df2", df1, df2); assertNotEquals("df2 != df1", df2, df1); } @Test public void Test11897_LocalizedPatternSeparator() { // In a locale with a different <list> symbol, like arabic, // kPatternSeparatorSymbol should still be ';' { DecimalFormatSymbols dfs = new DecimalFormatSymbols(new ULocale("ar")); assertEquals("pattern separator symbol should be ;", ';', dfs.getPatternSeparator()); } // However, the custom symbol should be used in localized notation // when set manually via API { DecimalFormatSymbols dfs = new DecimalFormatSymbols(new ULocale("en")); dfs.setPatternSeparator('!'); DecimalFormat df = new DecimalFormat("0", dfs); df.applyPattern("a0;b0"); // should not throw assertEquals("should apply the normal pattern", df.getNegativePrefix(), "b"); df.applyLocalizedPattern("c0!d0"); // should not throw assertEquals("should apply the localized pattern", df.getNegativePrefix(), "d"); } } @Test public void Test13055() { DecimalFormat df = (DecimalFormat) NumberFormat.getPercentInstance(); df.setMaximumFractionDigits(0); df.setRoundingMode(BigDecimal.ROUND_HALF_EVEN); assertEquals("Should round percent toward even number", "216%", df.format(2.155)); } @Test public void Test13056() { DecimalFormat df = new DecimalFormat("#,##0"); assertEquals("Primary grouping should return 3", 3, df.getGroupingSize()); assertEquals("Secondary grouping should return 0", 0, df.getSecondaryGroupingSize()); df.setSecondaryGroupingSize(3); assertEquals("Primary grouping should still return 3", 3, df.getGroupingSize()); assertEquals("Secondary grouping should round-trip", 3, df.getSecondaryGroupingSize()); df.setGroupingSize(4); assertEquals("Primary grouping should return 4", 4, df.getGroupingSize()); assertEquals("Secondary should remember explicit setting and return 3", 3, df.getSecondaryGroupingSize()); } @Test public void Test13074() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(new ULocale("bg-BG")); String result = df.format(987654.321); assertEquals("Locale 'bg' should not use monetary grouping", "987654,32 лв.", result); } @Test public void Test13088and13162() { ULocale loc = new ULocale("fa"); String pattern1 = "%\u00A0#,##0;%\u00A0-#,##0"; double num = -12.34; DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(loc); // If the symbols ever change in locale data, please call the setters so that this test // continues to use the old symbols. // The fa percent symbol does change in CLDR 32, so.... symbols.setPercentString("‎٪"); assertEquals("Checking for expected symbols", "‎−", symbols.getMinusSignString()); assertEquals("Checking for expected symbols", "‎٪", symbols.getPercentString()); DecimalFormat numfmt = new DecimalFormat(pattern1, symbols); expect2(numfmt, num, "‎٪ ‎−۱٬۲۳۴"); String pattern2 = "%#,##0;%-#,##0"; numfmt = new DecimalFormat(pattern2, symbols); expect2(numfmt, num, "‎٪‎−۱٬۲۳۴"); } @Test public void Test13113_MalformedPatterns() { String[][] cases = { {"'", "quoted literal"}, {"ab#c'd", "quoted literal"}, {"ab#c*", "unquoted literal"}, {"0#", "# cannot follow 0"}, {".#0", "0 cannot follow #"}, {"@0", "Cannot mix @ and 0"}, {"0@", "Cannot mix 0 and @"}, {"#x#", "unquoted special character"}, {"@#@", "# inside of a run of @"}, }; for (String[] cas : cases) { try { new DecimalFormat(cas[0]); fail("Should have thrown on malformed pattern"); } catch (IllegalArgumentException ex) { assertTrue("Exception should contain \"Malformed pattern\": " + ex.getMessage(), ex.getMessage().contains("Malformed pattern")); assertTrue("Exception should contain \"" + cas[1] + "\"" + ex.getMessage(), ex.getMessage().contains(cas[1])); } } } @Test public void Test13118() { DecimalFormat df = new DecimalFormat("@@@"); df.setScientificNotation(true); for (double d=12345.67; d>1e-6; d/=10) { String result = df.format(d); assertEquals("Should produce a string of expected length on " + d, d > 1 ? 6 : 7, result.length()); } } @Test public void Test13289() { DecimalFormat df = new DecimalFormat("#00.0#E0"); String result = df.format(0.00123); assertEquals("Should ignore scientific minInt if maxInt>minInt", "1.23E-3", result); } @Test public void Test13310() { // Note: if minInt > 8, then maxInt can be greater than 8. assertEquals("Should not throw an assertion error", "100000007.6E-1", new DecimalFormat("000000000.0#E0").format(10000000.76d)); } @Test public void Test13391() throws ParseException { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(new ULocale("ccp")); df.setParseStrict(true); String expected = "\uD804\uDD37\uD804\uDD38,\uD804\uDD39\uD804\uDD3A\uD804\uDD3B"; assertEquals("Should produce expected output in ccp", expected, df.format(12345)); Number result = df.parse(expected); assertEquals("Should parse to 12345 in ccp", 12345, result.longValue()); df = (DecimalFormat) NumberFormat.getScientificInstance(new ULocale("ccp")); df.setParseStrict(true); String expectedScientific = "\uD804\uDD37.\uD804\uDD39E\uD804\uDD38"; assertEquals("Should produce expected scientific output in ccp", expectedScientific, df.format(130)); Number resultScientific = df.parse(expectedScientific); assertEquals("Should parse scientific to 130 in ccp", 130, resultScientific.longValue()); } @Test public void Test13453_AffixContent() { DecimalFormat df = (DecimalFormat) DecimalFormat.getScientificInstance(); assertEquals("Scientific should NOT be included", "", df.getPositiveSuffix()); df = CompactDecimalFormat.getInstance(ULocale.ENGLISH, CompactDecimalFormat.CompactStyle.SHORT); assertEquals("Compact should NOT be included", "", df.getPositiveSuffix()); df = (DecimalFormat) DecimalFormat.getInstance(NumberFormat.ISOCURRENCYSTYLE); df.setCurrency(Currency.getInstance("GBP")); assertEquals("ISO currency SHOULD be included", "GBP", df.getPositivePrefix()); df = (DecimalFormat) DecimalFormat.getInstance(NumberFormat.PLURALCURRENCYSTYLE); df.setCurrency(Currency.getInstance("GBP")); assertEquals("Plural name SHOULD be included", " British pounds", df.getPositiveSuffix()); } @Test public void Test11035_FormatCurrencyAmount() { double amount = 12345.67; String expected = "12,345$67 ​"; Currency cur = Currency.getInstance("PTE"); // Test three ways to set currency via API ULocale loc1 = new ULocale("pt_PT"); NumberFormat fmt1 = NumberFormat.getCurrencyInstance(loc1); fmt1.setCurrency(cur); String actualSetCurrency = fmt1.format(amount); ULocale loc2 = new ULocale("pt_PT@currency=PTE"); NumberFormat fmt2 = NumberFormat.getCurrencyInstance(loc2); String actualLocaleString = fmt2.format(amount); ULocale loc3 = new ULocale("pt_PT"); NumberFormat fmt3 = NumberFormat.getCurrencyInstance(loc3); CurrencyAmount curAmt = new CurrencyAmount(amount, cur); String actualCurrencyAmount = fmt3.format(curAmt); assertEquals("Custom Currency Pattern, Set Currency", expected, actualSetCurrency); assertEquals("Custom Currency Pattern, Locale String", expected, actualCurrencyAmount); assertEquals("Custom Currency Pattern, CurrencyAmount", expected, actualLocaleString); } @Test public void testPercentZero() { DecimalFormat df = (DecimalFormat) NumberFormat.getPercentInstance(); String actual = df.format(0); assertEquals("Should have one zero digit", "0%", actual); } @Test public void testCurrencyZeroRounding() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(); df.setMaximumFractionDigits(0); String actual = df.format(0); assertEquals("Should have zero fraction digits", "$0", actual); } @Test public void testCustomCurrencySymbol() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(); df.setCurrency(Currency.getInstance("USD")); DecimalFormatSymbols symbols = df.getDecimalFormatSymbols(); symbols.setCurrencySymbol("#"); df.setDecimalFormatSymbols(symbols); String actual = df.format(123); assertEquals("Should use '#' instad of '$'", "# 123.00", actual); } @Test public void TestBasicSerializationRoundTrip() throws IOException, ClassNotFoundException { DecimalFormat df0 = new DecimalFormat("A-**#####,#00.00b¤"); // Write to byte stream ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(df0); oos.flush(); baos.close(); byte[] bytes = baos.toByteArray(); // Read from byte stream ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes)); Object obj = ois.readObject(); ois.close(); DecimalFormat df1 = (DecimalFormat) obj; // Test equality assertEquals("Did not round-trip through serialization", df0, df1); // Test basic functionality String str0 = df0.format(12345.67); String str1 = df1.format(12345.67); assertEquals("Serialized formatter does not produce same output", str0, str1); } @Test public void testGetSetCurrency() { DecimalFormat df = new DecimalFormat("¤#", DecimalFormatSymbols.getInstance(ULocale.US)); assertEquals("Currency should start out as the locale default", Currency.getInstance("USD"), df.getCurrency()); Currency curr = Currency.getInstance("EUR"); df.setCurrency(curr); assertEquals("Currency should equal EUR after set", curr, df.getCurrency()); String result = df.format(123); assertEquals("Currency should format as expected in EUR", "€123.00", result); } @Test public void testRoundingModeSetters() { DecimalFormat df1 = new DecimalFormat(); DecimalFormat df2 = new DecimalFormat(); df1.setRoundingMode(java.math.BigDecimal.ROUND_CEILING); assertNotEquals("Rounding mode was set to a non-default", df1, df2); df2.setRoundingMode(com.ibm.icu.math.BigDecimal.ROUND_CEILING); assertEquals("Rounding mode from icu.math and java.math should be the same", df1, df2); df2.setRoundingMode(java.math.RoundingMode.CEILING.ordinal()); assertEquals("Rounding mode ordinal from java.math.RoundingMode should be the same", df1, df2); } @Test public void testCurrencySignificantDigits() { ULocale locale = new ULocale("en-US"); DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(locale); df.setMaximumSignificantDigits(2); String result = df.format(1234); assertEquals("Currency rounding should obey significant digits", "$1,200", result); } @Test public void testParseStrictScientific() { // See ticket #13057 DecimalFormat df = (DecimalFormat) NumberFormat.getScientificInstance(); df.setParseStrict(true); ParsePosition ppos = new ParsePosition(0); Number result0 = df.parse("123E4", ppos); assertEquals("Should accept number with exponent", 1230000L, result0); assertEquals("Should consume the whole number", 5, ppos.getIndex()); ppos.setIndex(0); result0 = df.parse("123", ppos); // #13737: For backwards compatibility, do NOT require the exponent. assertEquals("Should NOT reject number without exponent", 123L, result0); ppos.setIndex(0); CurrencyAmount result1 = df.parseCurrency("USD123", ppos); assertEquals("Should NOT reject currency without exponent", new CurrencyAmount(123L, Currency.getInstance("USD")), result1); } @Test public void testParseLenientScientific() { DecimalFormat df = (DecimalFormat) NumberFormat.getScientificInstance(); ParsePosition ppos = new ParsePosition(0); Number result0 = df.parse("123E", ppos); assertEquals("Should parse the number in lenient mode", 123L, result0); assertEquals("Should stop before the E", 3, ppos.getIndex()); DecimalFormatSymbols dfs = df.getDecimalFormatSymbols(); dfs.setExponentSeparator("EE"); df.setDecimalFormatSymbols(dfs); ppos.setIndex(0); result0 = df.parse("123EE", ppos); assertEquals("Should parse the number in lenient mode", 123L, result0); assertEquals("Should stop before the EE", 3, ppos.getIndex()); } @Test public void testParseAcceptAsciiPercentPermilleFallback() { ULocale loc = new ULocale("ar"); DecimalFormat df = (DecimalFormat) NumberFormat.getPercentInstance(loc); ParsePosition ppos = new ParsePosition(0); Number result = df.parse("42%", ppos); assertEquals("Should parse as 0.42 even in ar", new BigDecimal("0.42"), result); assertEquals("Should consume the entire string even in ar", 3, ppos.getIndex()); // TODO: Is there a better way to make a localized permille formatter? df.applyPattern(df.toPattern().replace("%", "‰")); ppos.setIndex(0); result = df.parse("42‰", ppos); assertEquals("Should parse as 0.042 even in ar", new BigDecimal("0.042"), result); assertEquals("Should consume the entire string even in ar", 3, ppos.getIndex()); } @Test public void testParseSubtraction() { // TODO: Is this a case we need to support? It prevents us from automatically parsing // minus signs that appear after the number, like in "12-" vs "-12". DecimalFormat df = new DecimalFormat(); String str = "12 - 5"; ParsePosition ppos = new ParsePosition(0); Number n1 = df.parse(str, ppos); Number n2 = df.parse(str, ppos); assertEquals("Should parse 12 and -5", 12, n1.intValue()); assertEquals("Should parse 12 and -5", -5, n2.intValue()); } @Test public void testSetPrefixDefaultSuffix() { DecimalFormat df = (DecimalFormat) NumberFormat.getPercentInstance(); df.setPositivePrefix("+"); assertEquals("Should have manual plus sign and auto percent sign", "+100%", df.format(1)); } @Test public void testMultiCodePointPaddingInPattern() { DecimalFormat df = new DecimalFormat("a*'நி'###0b"); String result = df.format(12); assertEquals("Multi-codepoint padding should not be split", "aநிநி12b", result); df = new DecimalFormat("a*😁###0b"); result = df.format(12); assertEquals("Single-codepoint padding should not be split", "a😁😁12b", result); df = new DecimalFormat("a*''###0b"); result = df.format(12); assertEquals("Quote should be escapable in padding syntax", "a''12b", result); } @Test public void Test13737_ParseScientificStrict() { NumberFormat df = NumberFormat.getScientificInstance(ULocale.ENGLISH); df.setParseStrict(true); // Parse Test: exponent is not required, even in strict mode expect(df, "1.2", 1.2); } // TODO: Investigate this test and re-enable if appropriate. @Test @Ignore public void testParseAmbiguousAffixes() { BigDecimal positive = new BigDecimal("0.0567"); BigDecimal negative = new BigDecimal("-0.0567"); DecimalFormat df = new DecimalFormat(); df.setParseBigDecimal(true); String[] patterns = { "+0.00%;-0.00%", "+0.00%;0.00%", "0.00%;-0.00%" }; String[] inputs = { "+5.67%", "-5.67%", "5.67%" }; boolean[][] expectedPositive = { { true, false, true }, { true, false, false }, { true, false, true } }; for (int i=0; i<patterns.length; i++) { String pattern = patterns[i]; df.applyPattern(pattern); for (int j=0; j<inputs.length; j++) { String input = inputs[j]; ParsePosition ppos = new ParsePosition(0); Number actual = df.parse(input, ppos); BigDecimal expected = expectedPositive[i][j] ? positive : negative; String message = "Pattern " + pattern + " with input " + input; assertEquals(message, expected, actual); assertEquals(message, input.length(), ppos.getIndex()); } } } @Test public void testParseIgnorables() { // Also see the test case "test parse ignorables" in numberformattestspecification.txt DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); dfs.setPercentString("\u200E%\u200E"); DecimalFormat df = new DecimalFormat("0 %;-0a", dfs); ParsePosition ppos = new ParsePosition(0); Number result = df.parse("42\u200E%\u200E ", ppos); assertEquals("Should parse as percentage", new BigDecimal("0.42"), result); assertEquals("Should consume the trailing bidi since it is in the symbol", 5, ppos.getIndex()); ppos.setIndex(0); result = df.parse("-42a\u200E ", ppos); assertEquals("Should parse as percent", -0.42, result.doubleValue()); assertEquals("Should not consume the trailing bidi or whitespace", 4, ppos.getIndex()); // A few more cases based on the docstring: expect(df, "42%", 0.42); expect(df, "42 %", 0.42); expect(df, "42 %", 0.42); expect(df, "42\u00A0%", 0.42); } @Test public void testCustomCurrencyUsageOverridesPattern() { DecimalFormat df = new DecimalFormat("#,##0.###"); expect2(df, 1234, "1,234"); df.setCurrencyUsage(CurrencyUsage.STANDARD); expect2(df, 1234, "1,234.00"); df.setCurrencyUsage(null); expect2(df, 1234, "1,234"); } @Test public void testCurrencyUsageFractionOverrides() { NumberFormat df = DecimalFormat.getCurrencyInstance(ULocale.US); expect2(df, 35.0, "$35.00"); df.setMinimumFractionDigits(3); expect2(df, 35.0, "$35.000"); df.setMaximumFractionDigits(3); expect2(df, 35.0, "$35.000"); df.setMinimumFractionDigits(-1); expect2(df, 35.0, "$35.00"); df.setMaximumFractionDigits(-1); expect2(df, 35.0, "$35.00"); } @Test public void testParseVeryVeryLargeExponent() { DecimalFormat df = new DecimalFormat(); ParsePosition ppos = new ParsePosition(0); Object[][] cases = { {"1.2E+1234567890", Double.POSITIVE_INFINITY}, {"1.2E+999999999", new com.ibm.icu.math.BigDecimal("1.2E+999999999")}, {"1.2E+1000000000", Double.POSITIVE_INFINITY}, {"-1.2E+999999999", new com.ibm.icu.math.BigDecimal("-1.2E+999999999")}, {"-1.2E+1000000000", Double.NEGATIVE_INFINITY}, {"1.2E-999999999", new com.ibm.icu.math.BigDecimal("1.2E-999999999")}, {"1.2E-1000000000", 0.0}, {"-1.2E-999999999", new com.ibm.icu.math.BigDecimal("-1.2E-999999999")}, {"-1.2E-1000000000", -0.0}, }; for (Object[] cas : cases) { ppos.setIndex(0); String input = (String) cas[0]; Number expected = (Number) cas[1]; Number actual = df.parse(input, ppos); assertEquals(input, expected, actual); } } @Test public void testStringMethodsNPE() { String[] npeMethods = { "applyLocalizedPattern", "applyPattern", "setNegativePrefix", "setNegativeSuffix", "setPositivePrefix", "setPositiveSuffix" }; for (String npeMethod : npeMethods) { DecimalFormat df = new DecimalFormat(); try { DecimalFormat.class.getDeclaredMethod(npeMethod, String.class).invoke(df, (String) null); fail("NullPointerException not thrown in method " + npeMethod); } catch (InvocationTargetException e) { assertTrue("Exception should be NullPointerException in method " + npeMethod, e.getCause() instanceof NullPointerException); } catch (Exception e) { // Other reflection exceptions throw new AssertionError("Reflection error in method " + npeMethod + ": " + e.getMessage()); } } // Also test the constructors try { new DecimalFormat(null); fail("NullPointerException not thrown in 1-parameter constructor"); } catch (NullPointerException e) { // Expected } try { new DecimalFormat(null, new DecimalFormatSymbols()); fail("NullPointerException not thrown in 2-parameter constructor"); } catch (NullPointerException e) { // Expected } try { new DecimalFormat(null, new DecimalFormatSymbols(), CurrencyPluralInfo.getInstance(), 0); fail("NullPointerException not thrown in 4-parameter constructor"); } catch (NullPointerException e) { // Expected } } @Test public void testParseNoExponent() throws ParseException { DecimalFormat df = new DecimalFormat(); assertEquals("Parse no exponent has wrong default", false, df.getParseNoExponent()); Number result1 = df.parse("123E4"); df.setParseNoExponent(true); assertEquals("Parse no exponent getter is broken", true, df.getParseNoExponent()); Number result2 = df.parse("123E4"); assertEquals("Exponent did not parse before setParseNoExponent", result1, new Long(1230000)); assertEquals("Exponent parsed after setParseNoExponent", result2, new Long(123)); } @Test public void testMinimumGroupingDigits() { String[][] allExpected = { {"123", "123"}, {"1,230", "1230"}, {"12,300", "12,300"}, {"1,23,000", "1,23,000"} }; DecimalFormat df = new DecimalFormat("#,##,##0"); assertEquals("Minimum grouping digits has wrong default", 1, df.getMinimumGroupingDigits()); for (int l = 123, i=0; l <= 123000; l *= 10, i++) { df.setMinimumGroupingDigits(1); assertEquals("Minimum grouping digits getter is broken", 1, df.getMinimumGroupingDigits()); String actual = df.format(l); assertEquals("Output is wrong for 1, "+i, allExpected[i][0], actual); df.setMinimumGroupingDigits(2); assertEquals("Minimum grouping digits getter is broken", 2, df.getMinimumGroupingDigits()); actual = df.format(l); assertEquals("Output is wrong for 2, "+i, allExpected[i][1], actual); } } @Test public void testParseCaseSensitive() { String[] patterns = {"a#b", "A#B"}; String[] inputs = {"a500b", "A500b", "a500B", "a500e10b", "a500E10b"}; int[][] expectedParsePositions = { {5, 5, 5, 8, 8}, // case insensitive, pattern 0 {5, 0, 4, 4, 8}, // case sensitive, pattern 0 {5, 5, 5, 8, 8}, // case insensitive, pattern 1 {0, 4, 0, 0, 0}, // case sensitive, pattern 1 }; for (int p = 0; p < patterns.length; p++) { String pat = patterns[p]; DecimalFormat df = new DecimalFormat(pat); assertEquals("parseCaseSensitive default is wrong", false, df.getParseCaseSensitive()); for (int i = 0; i < inputs.length; i++) { String inp = inputs[i]; df.setParseCaseSensitive(false); assertEquals("parseCaseSensitive getter is broken", false, df.getParseCaseSensitive()); ParsePosition actualInsensitive = new ParsePosition(0); df.parse(inp, actualInsensitive); assertEquals("Insensitive, pattern "+p+", input "+i, expectedParsePositions[p*2][i], actualInsensitive.getIndex()); df.setParseCaseSensitive(true); assertEquals("parseCaseSensitive getter is broken", true, df.getParseCaseSensitive()); ParsePosition actualSensitive = new ParsePosition(0); df.parse(inp, actualSensitive); assertEquals("Sensitive, pattern "+p+", input "+i, expectedParsePositions[p*2+1][i], actualSensitive.getIndex()); } } } @Test public void testPlusSignAlwaysShown() throws ParseException { double[] numbers = {0.012, 5.78, 0, -0.012, -5.78}; ULocale[] locs = {new ULocale("en-US"), new ULocale("ar-EG"), new ULocale("es-CL")}; String[][][] expecteds = { // en-US { // decimal { "+0.012", "+5.78", "+0", "-0.012", "-5.78" }, // currency { "+$0.01", "+$5.78", "+$0.00", "-$0.01", "-$5.78" } }, // ar-EG (interesting because the plus sign string starts with \u061C) { // decimal { "\u061C+\u0660\u066B\u0660\u0661\u0662", // "؜+٠٫٠١٢" "\u061C+\u0665\u066B\u0667\u0668", // "؜+٥٫٧٨" "\u061C+\u0660", // "؜+٠" "\u061C-\u0660\u066B\u0660\u0661\u0662", // "؜-٠٫٠١٢" "\u061C-\u0665\u066B\u0667\u0668", // "؜-٥٫٧٨" }, // currency (\062C.\0645.\200F is the currency sign in ar for EGP) { "\u061C+\u0660\u066B\u0660\u0661\u00A0\u062C.\u0645.\u200F", "\u061C+\u0665\u066B\u0667\u0668\u00A0\u062C.\u0645.\u200F", "\u061C+\u0660\u066B\u0660\u0660\u00A0\u062C.\u0645.\u200F", "\u061C-\u0660\u066B\u0660\u0661\u00A0\u062C.\u0645.\u200F", "\u061C-\u0665\u066B\u0667\u0668\u00A0\u062C.\u0645.\u200F" } }, // es-CL (interesting because of position of sign in currency) { // decimal { "+0,012", "+5,78", "+0", "-0,012", "-5,78" }, // currency (note: rounding for es-CL's currency, CLP, is 0 fraction digits) { "$+0", "$+6", "$+0", "$-0", "$-6" } } }; for (int i=0; i<locs.length; i++) { ULocale loc = locs[i]; DecimalFormat df1 = (DecimalFormat) NumberFormat.getNumberInstance(loc); assertFalse("Default should be false", df1.getSignAlwaysShown()); df1.setSignAlwaysShown(true); assertTrue("Getter should now return true", df1.getSignAlwaysShown()); DecimalFormat df2 = (DecimalFormat) NumberFormat.getCurrencyInstance(loc); assertFalse("Default should be false", df2.getSignAlwaysShown()); df2.setSignAlwaysShown(true); assertTrue("Getter should now return true", df2.getSignAlwaysShown()); for (int j=0; j<2; j++) { DecimalFormat df = (j == 0) ? df1 : df2; for (int k=0; k<numbers.length; k++) { double d = numbers[k]; String exp = expecteds[i][j][k]; String act = df.format(d); assertEquals("Locale " + loc + ", type " + j + ", " + d, exp, act); BigDecimal parsedExp = BigDecimal.valueOf(d); if (j == 1) { // Currency-round expected parse output int scale = (i == 2) ? 0 : 2; parsedExp = parsedExp.setScale(scale, BigDecimal.ROUND_HALF_EVEN); } Number parsedNum = df.parse(exp); BigDecimal parsedAct = (parsedNum.getClass() == BigDecimal.class) ? (BigDecimal) parsedNum : BigDecimal.valueOf(parsedNum.doubleValue()); assertEquals( "Locale " + loc + ", type " + j + ", " + d + ", " + parsedExp + " => " + parsedAct, 0, parsedExp.compareTo(parsedAct)); } } } } @Test public void Test20073_StrictPercentParseErrorIndex() { ParsePosition parsePosition = new ParsePosition(0); DecimalFormat df = new DecimalFormat("0%", DecimalFormatSymbols.getInstance(Locale.US)); df.setParseStrict(true); Number number = df.parse("%2%", parsePosition); assertNull("", number); assertEquals("", 0, parsePosition.getIndex()); assertEquals("", 0, parsePosition.getErrorIndex()); } @Test public void Test11626_CustomizeCurrencyPluralInfo() throws ParseException { // Use locale sr because it has interesting plural rules. ULocale locale = ULocale.forLanguageTag("sr"); DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale); CurrencyPluralInfo info = CurrencyPluralInfo.getInstance(locale); info.setCurrencyPluralPattern("one", "0 qwerty"); info.setCurrencyPluralPattern("few", "0 dvorak"); DecimalFormat df = new DecimalFormat("#", symbols, info, NumberFormat.CURRENCYSTYLE); df.setCurrency(Currency.getInstance("USD")); df.setMaximumFractionDigits(0); assertEquals("Plural one", "1 qwerty", df.format(1)); assertEquals("Plural few", "3 dvorak", df.format(3)); assertEquals("Plural other", "99 америчких долара", df.format(99)); info.setPluralRules("few: n is 1; one: n in 2..4"); df.setCurrencyPluralInfo(info); assertEquals("Plural one", "1 dvorak", df.format(1)); assertEquals("Plural few", "3 qwerty", df.format(3)); assertEquals("Plural other", "99 америчких долара", df.format(99)); } @Test public void TestNarrowCurrencySymbols() { DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(ULocale.CANADA); df.setCurrency(Currency.getInstance("USD")); expect2(df, 123.45, "US$123.45"); String pattern = df.toPattern(); pattern = pattern.replace("¤", "¤¤¤¤¤"); df.applyPattern(pattern); // Note: Narrow currency is not parseable because of ambiguity. assertEquals("Narrow currency symbol for USD in en_CA is $", "$123.45", df.format(123.45)); } @Test public void TestAffixOverrideBehavior() { DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(ULocale.ENGLISH); expect2(df, 100, "100"); expect2(df, -100, "-100"); // This is not the right way to set an override plus sign, but we need to support it for compatibility. df.setPositivePrefix("+"); expect2(df, 100, "+100"); expect2(df, -100, "-100"); // note: the positive prefix does not affect the negative prefix df.applyPattern("a0"); expect2(df, 100, "a100"); expect2(df, -100, "-a100"); } @Test public void TestCurrencyRoundingMinWithoutMax() { NumberFormat currencyFormat = DecimalFormat.getCurrencyInstance(Locale.US); currencyFormat.setCurrency(Currency.getInstance("AUD")); currencyFormat.setMinimumFractionDigits(0); expect(currencyFormat, 0.001, "A$0"); // NOTE: The size of the increment takes precedent over minFrac since ICU 59. // CAD-Cash uses nickel rounding. currencyFormat = DecimalFormat.getCurrencyInstance(Locale.US); currencyFormat.setCurrency(Currency.getInstance("CAD")); ((DecimalFormat)currencyFormat).setCurrencyUsage(CurrencyUsage.CASH); currencyFormat.setMinimumFractionDigits(0); // expect(currencyFormat, 0.08, "CA$0.1"); // ICU 58 and down expect(currencyFormat, 0.08, "CA$0.10"); // ICU 59 and up } @Test public void testParsePositionIncrease() { String input = "123\n456\n$789"; ParsePosition ppos = new ParsePosition(0); DecimalFormat df = new DecimalFormat(); df.parse(input, ppos); assertEquals("Should stop after first entry", 3, ppos.getIndex()); ppos.setIndex(ppos.getIndex() + 1); df.parse(input, ppos); assertEquals("Should stop after second entry", 7, ppos.getIndex()); ppos.setIndex(ppos.getIndex() + 1); df.parseCurrency(input, ppos); // test parseCurrency API as well assertEquals("Should stop after third entry", 12, ppos.getIndex()); } @Test public void testTrailingMinusSign() { String input = "52-"; DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(ULocale.ENGLISH); ParsePosition ppos = new ParsePosition(0); Number result = df.parse(input, ppos); assertEquals("Trailing sign should NOT be accepted after the number in English by default", 52.0, result.doubleValue(), 0.0); df.applyPattern("#;#-"); ppos.setIndex(0); result = df.parse(input, ppos); assertEquals("Trailing sign SHOULD be accepted if there is one in the pattern", -52.0, result.doubleValue(), 0.0); } @Test public void testScientificCustomSign() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); dfs.setMinusSignString("nnn"); dfs.setPlusSignString("ppp"); DecimalFormat df = new DecimalFormat("0E0", dfs); df.setExponentSignAlwaysShown(true); expect2(df, 0.5, "5Ennn1"); expect2(df, 50, "5Eppp1"); } @Test public void testParsePercentInPattern() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); DecimalFormat df = new DecimalFormat("0x%", dfs); df.setParseStrict(true); expect2(df, 0.5, "50x%"); } @Test public void testParseIsoStrict() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); DecimalFormat df = new DecimalFormat("¤¤0;-0¤¤", dfs); df.setCurrency(Currency.getInstance("USD")); df.setParseStrict(true); expect2(df, 45, "USD 45.00"); expect2(df, -45, "-45.00 USD"); } @Test public void test13684_FrenchPercentParsing() { NumberFormat numberFormat = NumberFormat.getPercentInstance(ULocale.FRENCH); numberFormat.setParseStrict(true); ParsePosition ppos = new ParsePosition(0); Number percentage = numberFormat.parse("8\u00A0%", ppos); assertEquals("Should parse successfully", 0.08, percentage.doubleValue()); assertEquals("Should consume whole string", 3, ppos.getIndex()); } @Test public void testStrictParseCurrencyLongNames() { DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(ULocale.ENGLISH, DecimalFormat.PLURALCURRENCYSTYLE); df.setParseStrict(true); df.setCurrency(Currency.getInstance("USD")); double input = 514.23; String formatted = df.format(input); String expected = "514.23 US dollars"; assertEquals("Should format as expected", expected, formatted); ParsePosition ppos = new ParsePosition(0); CurrencyAmount ca = df.parseCurrency(formatted, ppos); assertEquals("Should consume whole number", ppos.getIndex(), 17); assertEquals("Number should round-trip", ca.getNumber().doubleValue(), input); assertEquals("Should get correct currency", ca.getCurrency().getCurrencyCode(), "USD"); // Should also round-trip in non-currency parsing expect2(df, input, expected); } @Test public void testStrictParseCurrencySpacing() { DecimalFormat df = new DecimalFormat("¤ 0", DecimalFormatSymbols.getInstance(ULocale.ROOT)); df.setCurrency(Currency.getInstance("USD")); df.setParseStrict(true); expect2(df, -51.42, "-US$ 51.42"); } @Test public void testCaseSensitiveCustomIsoCurrency() { DecimalFormat df = new DecimalFormat("¤¤0", DecimalFormatSymbols.getInstance(ULocale.ENGLISH)); df.setCurrency(Currency.getInstance("ICU")); ParsePosition ppos = new ParsePosition(0); df.parseCurrency("icu123", ppos); assertEquals("Should succeed", 6, ppos.getIndex()); assertEquals("Should succeed", -1, ppos.getErrorIndex()); } @Test public void testCurrencyPluralAffixOverrides() { // The affix setters should override CurrencyPluralInfo, used in the plural currency constructor. DecimalFormat df = (DecimalFormat) NumberFormat.getInstance(ULocale.ENGLISH, NumberFormat.PLURALCURRENCYSTYLE); assertEquals("Defaults to unknown currency", " (unknown currency)", df.getPositiveSuffix()); df.setCurrency(Currency.getInstance("USD")); assertEquals("Should resolve to CurrencyPluralInfo", " US dollars", df.getPositiveSuffix()); df.setPositiveSuffix("lala"); assertEquals("Custom suffix should round-trip", "lala", df.getPositiveSuffix()); assertEquals("Custom suffix should be used in formatting", "123.00lala", df.format(123)); } @Test public void testParseDoubleMinus() { DecimalFormat df = new DecimalFormat("-0", DecimalFormatSymbols.getInstance(ULocale.ENGLISH)); expect2(df, -5, "--5"); } @Test public void testParsePercentRegression() { DecimalFormat df1 = (DecimalFormat) NumberFormat.getInstance(ULocale.ENGLISH); DecimalFormat df2 = (DecimalFormat) NumberFormat.getPercentInstance(ULocale.ENGLISH); df1.setParseStrict(false); df2.setParseStrict(false); { ParsePosition ppos = new ParsePosition(0); Number result = df1.parse("50%", ppos); assertEquals("df1 should accept a number but not the percent sign", 2, ppos.getIndex()); assertEquals("df1 should return the number as 50", 50.0, result.doubleValue()); } { ParsePosition ppos = new ParsePosition(0); Number result = df2.parse("50%", ppos); assertEquals("df2 should accept the percent sign", 3, ppos.getIndex()); assertEquals("df2 should return the number as 0.5", 0.5, result.doubleValue()); } { ParsePosition ppos = new ParsePosition(0); Number result = df2.parse("50", ppos); assertEquals("df2 should return the number as 0.5 even though the percent sign is missing", 0.5, result.doubleValue()); } } @Test public void test13148_GroupingSeparatorOverride() throws Exception { DecimalFormat fmt = (DecimalFormat)NumberFormat.getInstance(new ULocale("en", "ZA")); DecimalFormatSymbols symbols = fmt.getDecimalFormatSymbols(); symbols.setDecimalSeparator('.'); symbols.setGroupingSeparator(','); fmt.setDecimalFormatSymbols(symbols); Number number = fmt.parse("300,000"); assertEquals("Should use custom symbols and not monetary symbols", 300000L, number); } @Test public void test11897_LocalizedPatternSeparator() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); dfs.setPatternSeparator('!'); DecimalFormat df = new DecimalFormat("0", dfs); df.applyPattern("a0;b0"); // should not throw assertEquals("should apply the normal pattern", df.getNegativePrefix(), "b"); df.applyLocalizedPattern("c0!d0"); // should not throw assertEquals("should apply the localized pattern", df.getNegativePrefix(), "d"); } @Test public void test13777_ParseLongNameNonCurrencyMode() { // Currency long name should round-trip even when non-currency parsing is used. NumberFormat df = NumberFormat.getInstance(ULocale.US, NumberFormat.PLURALCURRENCYSTYLE); expect2(df, 1.5, "1.50 US dollars"); } @Test public void test13804_EmptyStringsWhenParsing() { DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(ULocale.ENGLISH); dfs.setCurrencySymbol(""); dfs.setDecimalSeparatorString(""); dfs.setDigitStrings(new String[] { "", "", "", "", "", "", "", "", "", "" }); dfs.setExponentMultiplicationSign(""); dfs.setExponentSeparator(""); dfs.setGroupingSeparatorString(""); dfs.setInfinity(""); dfs.setInternationalCurrencySymbol(""); dfs.setMinusSignString(""); dfs.setMonetaryDecimalSeparatorString(""); dfs.setMonetaryGroupingSeparatorString(""); dfs.setNaN(""); dfs.setPatternForCurrencySpacing(DecimalFormatSymbols.CURRENCY_SPC_INSERT, false, ""); dfs.setPatternForCurrencySpacing(DecimalFormatSymbols.CURRENCY_SPC_INSERT, true, ""); dfs.setPercentString(""); dfs.setPerMillString(""); dfs.setPlusSignString(""); DecimalFormat df = new DecimalFormat("0", dfs); df.setGroupingUsed(true); df.setScientificNotation(true); df.setParseStrict(false); // enable all matchers df.format(0); // should not throw or hit infinite loop String[] samples = new String[] { "", "123", "$123", "-", "+", "44%", "1E+2.3" }; for (String sample : samples) { logln("Attempting parse on: " + sample); // We don't care about the results, only that we don't throw and don't loop. ParsePosition ppos = new ParsePosition(0); df.parse(sample, ppos); ppos = new ParsePosition(0); df.parseCurrency(sample, ppos); } // Test with a nonempty exponent separator symbol to cover more code dfs.setExponentSeparator("E"); df.setDecimalFormatSymbols(dfs); { ParsePosition ppos = new ParsePosition(0); df.parse("1E+2.3", ppos); } } @Test public void Test20037_ScientificIntegerOverflow() throws ParseException { NumberFormat nf = NumberFormat.getInstance(ULocale.US); // Test overflow of exponent Number result = nf.parse("1E-2147483648"); assertEquals("Should snap to zero", "0", result.toString()); // Test edge case overflow of exponent // Note: the behavior is different from C++; this is probably due to the // intermediate BigDecimal form, which has its own restrictions result = nf.parse("1E-2147483647E-1"); assertEquals("Should not overflow and should parse only the first exponent", "0.0", result.toString()); // For Java, we should get *pretty close* to 2^31. result = nf.parse("1E-547483647"); assertEquals("Should *not* snap to zero", "1E-547483647", result.toString()); // Test edge case overflow of exponent result = nf.parse(".0003e-2147483644"); assertEquals("Should not overflow", "0", result.toString()); } @Test public void test13840_ParseLongStringCrash() throws ParseException { NumberFormat nf = NumberFormat.getInstance(ULocale.ENGLISH); String bigString = "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111" + "111111111111111111111111111111111111111111111111111111111111111111111"; Number result = nf.parse(bigString); // Normalize the input string: BigDecimal expectedBigDecimal = new BigDecimal(bigString); String expectedUString = expectedBigDecimal.toString(); // Get the output string: BigDecimal actualBigDecimal = (BigDecimal) result; String actualUString = actualBigDecimal.toString(); assertEquals("Should round-trip without crashing", expectedUString, actualUString); } }
./CrossVul/dataset_final_sorted/CWE-190/java/good_434_5
crossvul-java_data_bad_4445_0
/* Copyright (c) 2008-2015, Avian Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. There is NO WARRANTY for this software. See license.txt for details. */ package java.io; public class FileOutputStream extends OutputStream { // static { // System.loadLibrary("natives"); // } private int fd; public FileOutputStream(FileDescriptor fd) { this.fd = fd.value; } public FileOutputStream(String path) throws IOException { this(path, false); } public FileOutputStream(String path, boolean append) throws IOException { fd = open(path, append); } public FileOutputStream(File file) throws IOException { this(file.getPath()); } private static native int open(String path, boolean append) throws IOException; private static native void write(int fd, int c) throws IOException; private static native void write(int fd, byte[] b, int offset, int length) throws IOException; private static native void close(int fd) throws IOException; public void write(int c) throws IOException { write(fd, c); } public void write(byte[] b, int offset, int length) throws IOException { if (b == null) { throw new NullPointerException(); } if (offset < 0 || offset + length > b.length) { throw new ArrayIndexOutOfBoundsException(); } write(fd, b, offset, length); } public void close() throws IOException { if (fd != -1) { close(fd); fd = -1; } } }
./CrossVul/dataset_final_sorted/CWE-190/java/bad_4445_0
crossvul-java_data_good_2093_0
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Yahoo! Inc., Stephen Connolly, Tom Huybrechts, Alan Harder, Manufacture * Francaise des Pneumatiques Michelin, Romain Seguy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import hudson.cli.CLICommand; import hudson.console.ConsoleAnnotationDescriptor; import hudson.console.ConsoleAnnotatorFactory; import hudson.model.*; import hudson.model.ParameterDefinition.ParameterDescriptor; import hudson.search.SearchableModelObject; import hudson.security.AccessControlled; import hudson.security.AuthorizationStrategy; import hudson.security.GlobalSecurityConfiguration; import hudson.security.Permission; import hudson.security.SecurityRealm; import hudson.security.captcha.CaptchaSupport; import hudson.security.csrf.CrumbIssuer; import hudson.slaves.Cloud; import hudson.slaves.ComputerLauncher; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.RetentionStrategy; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildWrapper; import hudson.tasks.BuildWrappers; import hudson.tasks.Builder; import hudson.tasks.Publisher; import hudson.tasks.UserAvatarResolver; import hudson.util.Area; import hudson.util.Iterators; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.util.Secret; import hudson.views.MyViewsTabBar; import hudson.views.ViewsTabBar; import hudson.widgets.RenderOnDemandClosure; import jenkins.model.GlobalConfiguration; import jenkins.model.GlobalConfigurationCategory; import jenkins.model.GlobalConfigurationCategory.Unclassified; import jenkins.model.Jenkins; import jenkins.model.ModelObjectWithContextMenu; import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken; import org.apache.commons.jelly.JellyContext; import org.apache.commons.jelly.JellyTagException; import org.apache.commons.jelly.Script; import org.apache.commons.jelly.XMLOutput; import org.apache.commons.jexl.parser.ASTSizeFunction; import org.apache.commons.jexl.util.Introspector; import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; import org.jvnet.tiger_types.Types; import org.kohsuke.stapler.Ancestor; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.jelly.InternationalizedStringExpression.RawHtmlArgument; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.Date; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Utility functions used in views. * * <p> * An instance of this class is created for each request and made accessible * from view pages via the variable 'h' (h stands for Hudson.) * * @author Kohsuke Kawaguchi */ public class Functions { private static volatile int globalIota = 0; private int iota; public Functions() { iota = globalIota; // concurrent requests can use the same ID --- we are just trying to // prevent the same user from seeing the same ID repeatedly. globalIota+=1000; } /** * Generates an unique ID. */ public String generateId() { return "id"+iota++; } public static boolean isModel(Object o) { return o instanceof ModelObject; } public static boolean isModelWithContextMenu(Object o) { return o instanceof ModelObjectWithContextMenu; } public static String xsDate(Calendar cal) { return Util.XS_DATETIME_FORMATTER.format(cal.getTime()); } public static String rfc822Date(Calendar cal) { return Util.RFC822_DATETIME_FORMATTER.format(cal.getTime()); } public static void initPageVariables(JellyContext context) { String rootURL = Stapler.getCurrentRequest().getContextPath(); Functions h = new Functions(); context.setVariable("h", h); // The path starts with a "/" character but does not end with a "/" character. context.setVariable("rootURL", rootURL); /* load static resources from the path dedicated to a specific version. This "/static/VERSION/abc/def.ghi" path is interpreted by stapler to be the same thing as "/abc/def.ghi", but this avoids the stale cache problem when the user upgrades to new Jenkins. Stapler also sets a long future expiration dates for such static resources. see https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML */ context.setVariable("resURL",rootURL+getResourcePath()); context.setVariable("imagesURL",rootURL+getResourcePath()+"/images"); } /** * Given {@code c=MyList (extends ArrayList<Foo>), base=List}, compute the parameterization of 'base' * that's assignable from 'c' (in this case {@code List<Foo>}), and return its n-th type parameter * (n=0 would return {@code Foo}). * * <p> * This method is useful for doing type arithmetic. * * @throws AssertionError * if c' is not parameterized. */ public static <B> Class getTypeParameter(Class<? extends B> c, Class<B> base, int n) { Type parameterization = Types.getBaseClass(c,base); if (parameterization instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) parameterization; return Types.erasure(Types.getTypeArgument(pt,n)); } else { throw new AssertionError(c+" doesn't properly parameterize "+base); } } public JDK.DescriptorImpl getJDKDescriptor() { return Jenkins.getInstance().getDescriptorByType(JDK.DescriptorImpl.class); } /** * Prints the integer as a string that represents difference, * like "-5", "+/-0", "+3". */ public static String getDiffString(int i) { if(i==0) return "\u00B10"; // +/-0 String s = Integer.toString(i); if(i>0) return "+"+s; else return s; } /** * {@link #getDiffString(int)} that doesn't show anything for +/-0 */ public static String getDiffString2(int i) { if(i==0) return ""; String s = Integer.toString(i); if(i>0) return "+"+s; else return s; } /** * {@link #getDiffString2(int)} that puts the result into prefix and suffix * if there's something to print */ public static String getDiffString2(String prefix, int i, String suffix) { if(i==0) return ""; String s = Integer.toString(i); if(i>0) return prefix+"+"+s+suffix; else return prefix+s+suffix; } /** * Adds the proper suffix. */ public static String addSuffix(int n, String singular, String plural) { StringBuilder buf = new StringBuilder(); buf.append(n).append(' '); if(n==1) buf.append(singular); else buf.append(plural); return buf.toString(); } public static RunUrl decompose(StaplerRequest req) { List<Ancestor> ancestors = req.getAncestors(); // find the first and last Run instances Ancestor f=null,l=null; for (Ancestor anc : ancestors) { if(anc.getObject() instanceof Run) { if(f==null) f=anc; l=anc; } } if(l==null) return null; // there was no Run object String head = f.getPrev().getUrl()+'/'; String base = l.getUrl(); String reqUri = req.getOriginalRequestURI(); // Find "rest" or URI by removing N path components. // Not using reqUri.substring(f.getUrl().length()) to avoid mismatches due to // url-encoding or extra slashes. Former may occur in Tomcat (despite the spec saying // this string is not decoded, Tomcat apparently decodes this string. You see ' ' // instead of '%20', which is what the browser has sent), latter may occur in some // proxy or URL-rewriting setups where extra slashes are inadvertently added. String furl = f.getUrl(); int slashCount = 0; // Count components in ancestor URL for (int i = furl.indexOf('/'); i >= 0; i = furl.indexOf('/', i + 1)) slashCount++; // Remove that many from request URL, ignoring extra slashes String rest = reqUri.replaceFirst("(?:/+[^/]*){" + slashCount + "}", ""); return new RunUrl( (Run) f.getObject(), head, base, rest); } /** * If we know the user's screen resolution, return it. Otherwise null. * @since 1.213 */ public static Area getScreenResolution() { Cookie res = Functions.getCookie(Stapler.getCurrentRequest(),"screenResolution"); if(res!=null) return Area.parse(res.getValue()); return null; } /** * URL decomposed for easier computation of relevant URLs. * * <p> * The decomposed URL will be of the form: * <pre> * aaaaaa/524/bbbbb/cccc * -head-| N |---rest--- * ----- base -----| * </pre> * * <p> * The head portion is the part of the URL from the {@link jenkins.model.Jenkins} * object to the first {@link Run} subtype. When "next/prev build" * is chosen, this part remains intact. * * <p> * The <tt>524</tt> is the path from {@link Job} to {@link Run}. * * <p> * The <tt>bbb</tt> portion is the path after that till the last * {@link Run} subtype. The <tt>ccc</tt> portion is the part * after that. */ public static final class RunUrl { private final String head, base, rest; private final Run run; public RunUrl(Run run, String head, String base, String rest) { this.run = run; this.head = head; this.base = base; this.rest = rest; } public String getBaseUrl() { return base; } /** * Returns the same page in the next build. */ public String getNextBuildUrl() { return getUrl(run.getNextBuild()); } /** * Returns the same page in the previous build. */ public String getPreviousBuildUrl() { return getUrl(run.getPreviousBuild()); } private String getUrl(Run n) { if(n ==null) return null; else { return head+n.getNumber()+rest; } } } public static Node.Mode[] getNodeModes() { return Node.Mode.values(); } public static String getProjectListString(List<Project> projects) { return Items.toNameList(projects); } /** * @deprecated as of 1.294 * JEXL now supports the real ternary operator "x?y:z", so this work around * is no longer necessary. */ public static Object ifThenElse(boolean cond, Object thenValue, Object elseValue) { return cond ? thenValue : elseValue; } public static String appendIfNotNull(String text, String suffix, String nullText) { return text == null ? nullText : text + suffix; } public static Map getSystemProperties() { return new TreeMap<Object,Object>(System.getProperties()); } public static Map getEnvVars() { return new TreeMap<String,String>(EnvVars.masterEnvVars); } public static boolean isWindows() { return File.pathSeparatorChar==';'; } public static List<LogRecord> getLogRecords() { return Jenkins.logRecords; } public static String printLogRecord(LogRecord r) { return formatter.format(r); } public static Cookie getCookie(HttpServletRequest req,String name) { Cookie[] cookies = req.getCookies(); if(cookies!=null) { for (Cookie cookie : cookies) { if(cookie.getName().equals(name)) { return cookie; } } } return null; } public static String getCookie(HttpServletRequest req,String name, String defaultValue) { Cookie c = getCookie(req, name); if(c==null || c.getValue()==null) return defaultValue; return c.getValue(); } private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+"); @Restricted(NoExternalUse.class) public static String validateIconSize(String iconSize) throws SecurityException { if (!ICON_SIZE.matcher(iconSize).matches()) { throw new SecurityException("invalid iconSize"); } return iconSize; } /** * Gets the suffix to use for YUI JavaScript. */ public static String getYuiSuffix() { return DEBUG_YUI ? "debug" : "min"; } /** * Set to true if you need to use the debug version of YUI. */ public static boolean DEBUG_YUI = Boolean.getBoolean("debug.YUI"); /** * Creates a sub map by using the given range (both ends inclusive). */ public static <V> SortedMap<Integer,V> filter(SortedMap<Integer,V> map, String from, String to) { if(from==null && to==null) return map; if(to==null) return map.headMap(Integer.parseInt(from)-1); if(from==null) return map.tailMap(Integer.parseInt(to)); return map.subMap(Integer.parseInt(to),Integer.parseInt(from)-1); } private static final SimpleFormatter formatter = new SimpleFormatter(); /** * Used by <tt>layout.jelly</tt> to control the auto refresh behavior. * * @param noAutoRefresh * On certain pages, like a page with forms, will have annoying interference * with auto refresh. On those pages, disable auto-refresh. */ public static void configureAutoRefresh(HttpServletRequest request, HttpServletResponse response, boolean noAutoRefresh) { if(noAutoRefresh) return; String param = request.getParameter("auto_refresh"); boolean refresh = isAutoRefresh(request); if (param != null) { refresh = Boolean.parseBoolean(param); Cookie c = new Cookie("hudson_auto_refresh", Boolean.toString(refresh)); // Need to set path or it will not stick from e.g. a project page to the dashboard. // Using request.getContextPath() might work but it seems simpler to just use the hudson_ prefix // to avoid conflicts with any other web apps that might be on the same machine. c.setPath("/"); c.setMaxAge(60*60*24*30); // persist it roughly for a month response.addCookie(c); } if (refresh) { response.addHeader("Refresh", System.getProperty("hudson.Functions.autoRefreshSeconds", "10")); } } public static boolean isAutoRefresh(HttpServletRequest request) { String param = request.getParameter("auto_refresh"); if (param != null) { return Boolean.parseBoolean(param); } Cookie[] cookies = request.getCookies(); if(cookies==null) return false; // when API design messes it up, we all suffer for (Cookie c : cookies) { if (c.getName().equals("hudson_auto_refresh")) { return Boolean.parseBoolean(c.getValue()); } } return false; } /** * Finds the given object in the ancestor list and returns its URL. * This is used to determine the "current" URL assigned to the given object, * so that one can compute relative URLs from it. */ public static String getNearestAncestorUrl(StaplerRequest req,Object it) { List list = req.getAncestors(); for( int i=list.size()-1; i>=0; i-- ) { Ancestor anc = (Ancestor) list.get(i); if(anc.getObject()==it) return anc.getUrl(); } return null; } /** * Finds the inner-most {@link SearchableModelObject} in scope. */ public static String getSearchURL() { List list = Stapler.getCurrentRequest().getAncestors(); for( int i=list.size()-1; i>=0; i-- ) { Ancestor anc = (Ancestor) list.get(i); if(anc.getObject() instanceof SearchableModelObject) return anc.getUrl()+"/search/"; } return null; } public static String appendSpaceIfNotNull(String n) { if(n==null) return null; else return n+' '; } /** * One nbsp per 10 pixels in given size, which may be a plain number or "NxN" * (like an iconSize). Useful in a sortable table heading. */ public static String nbspIndent(String size) { int i = size.indexOf('x'); i = Integer.parseInt(i > 0 ? size.substring(0, i) : size) / 10; StringBuilder buf = new StringBuilder(30); for (int j = 0; j < i; j++) buf.append("&nbsp;"); return buf.toString(); } public static String getWin32ErrorMessage(IOException e) { return Util.getWin32ErrorMessage(e); } public static boolean isMultiline(String s) { if(s==null) return false; return s.indexOf('\r')>=0 || s.indexOf('\n')>=0; } public static String encode(String s) { return Util.encode(s); } public static String escape(String s) { return Util.escape(s); } public static String xmlEscape(String s) { return Util.xmlEscape(s); } public static String xmlUnescape(String s) { return s.replace("&lt;","<").replace("&gt;",">").replace("&amp;","&"); } public static String htmlAttributeEscape(String text) { StringBuilder buf = new StringBuilder(text.length()+64); for( int i=0; i<text.length(); i++ ) { char ch = text.charAt(i); if(ch=='<') buf.append("&lt;"); else if(ch=='>') buf.append("&gt;"); else if(ch=='&') buf.append("&amp;"); else if(ch=='"') buf.append("&quot;"); else if(ch=='\'') buf.append("&#39;"); else buf.append(ch); } return buf.toString(); } public static void checkPermission(Permission permission) throws IOException, ServletException { checkPermission(Jenkins.getInstance(),permission); } public static void checkPermission(AccessControlled object, Permission permission) throws IOException, ServletException { if (permission != null) { object.checkPermission(permission); } } /** * This version is so that the 'checkPermission' on <tt>layout.jelly</tt> * degrades gracefully if "it" is not an {@link AccessControlled} object. * Otherwise it will perform no check and that problem is hard to notice. */ public static void checkPermission(Object object, Permission permission) throws IOException, ServletException { if (permission == null) return; if (object instanceof AccessControlled) checkPermission((AccessControlled) object,permission); else { List<Ancestor> ancs = Stapler.getCurrentRequest().getAncestors(); for(Ancestor anc : Iterators.reverse(ancs)) { Object o = anc.getObject(); if (o instanceof AccessControlled) { checkPermission((AccessControlled) o,permission); return; } } checkPermission(Jenkins.getInstance(),permission); } } /** * Returns true if the current user has the given permission. * * @param permission * If null, returns true. This defaulting is convenient in making the use of this method terse. */ public static boolean hasPermission(Permission permission) throws IOException, ServletException { return hasPermission(Jenkins.getInstance(),permission); } /** * This version is so that the 'hasPermission' can degrade gracefully * if "it" is not an {@link AccessControlled} object. */ public static boolean hasPermission(Object object, Permission permission) throws IOException, ServletException { if (permission == null) return true; if (object instanceof AccessControlled) return ((AccessControlled)object).hasPermission(permission); else { List<Ancestor> ancs = Stapler.getCurrentRequest().getAncestors(); for(Ancestor anc : Iterators.reverse(ancs)) { Object o = anc.getObject(); if (o instanceof AccessControlled) { return ((AccessControlled)o).hasPermission(permission); } } return Jenkins.getInstance().hasPermission(permission); } } public static void adminCheck(StaplerRequest req, StaplerResponse rsp, Object required, Permission permission) throws IOException, ServletException { // this is legacy --- all views should be eventually converted to // the permission based model. if(required!=null && !Hudson.adminCheck(req, rsp)) { // check failed. commit the FORBIDDEN response, then abort. rsp.setStatus(HttpServletResponse.SC_FORBIDDEN); rsp.getOutputStream().close(); throw new ServletException("Unauthorized access"); } // make sure the user owns the necessary permission to access this page. if(permission!=null) checkPermission(permission); } /** * Infers the hudson installation URL from the given request. */ public static String inferHudsonURL(StaplerRequest req) { String rootUrl = Jenkins.getInstance().getRootUrl(); if(rootUrl !=null) // prefer the one explicitly configured, to work with load-balancer, frontend, etc. return rootUrl; StringBuilder buf = new StringBuilder(); buf.append(req.getScheme()).append("://"); buf.append(req.getServerName()); if(! (req.getScheme().equals("http") && req.getLocalPort()==80 || req.getScheme().equals("https") && req.getLocalPort()==443)) buf.append(':').append(req.getLocalPort()); buf.append(req.getContextPath()).append('/'); return buf.toString(); } /** * Returns the link to be displayed in the footer of the UI. */ public static String getFooterURL() { if(footerURL == null) { footerURL = System.getProperty("hudson.footerURL"); if(StringUtils.isBlank(footerURL)) { footerURL = "http://jenkins-ci.org/"; } } return footerURL; } private static String footerURL = null; public static List<JobPropertyDescriptor> getJobPropertyDescriptors(Class<? extends Job> clazz) { return JobPropertyDescriptor.getPropertyDescriptors(clazz); } public static List<Descriptor<BuildWrapper>> getBuildWrapperDescriptors(AbstractProject<?,?> project) { return BuildWrappers.getFor(project); } public static List<Descriptor<SecurityRealm>> getSecurityRealmDescriptors() { return SecurityRealm.all(); } public static List<Descriptor<AuthorizationStrategy>> getAuthorizationStrategyDescriptors() { return AuthorizationStrategy.all(); } public static List<Descriptor<Builder>> getBuilderDescriptors(AbstractProject<?,?> project) { return BuildStepDescriptor.filter(Builder.all(), project.getClass()); } public static List<Descriptor<Publisher>> getPublisherDescriptors(AbstractProject<?,?> project) { return BuildStepDescriptor.filter(Publisher.all(), project.getClass()); } public static List<SCMDescriptor<?>> getSCMDescriptors(AbstractProject<?,?> project) { return SCM._for(project); } public static List<Descriptor<ComputerLauncher>> getComputerLauncherDescriptors() { return Jenkins.getInstance().<ComputerLauncher,Descriptor<ComputerLauncher>>getDescriptorList(ComputerLauncher.class); } public static List<Descriptor<RetentionStrategy<?>>> getRetentionStrategyDescriptors() { return RetentionStrategy.all(); } public static List<ParameterDescriptor> getParameterDescriptors() { return ParameterDefinition.all(); } public static List<Descriptor<CaptchaSupport>> getCaptchaSupportDescriptors() { return CaptchaSupport.all(); } public static List<Descriptor<ViewsTabBar>> getViewsTabBarDescriptors() { return ViewsTabBar.all(); } public static List<Descriptor<MyViewsTabBar>> getMyViewsTabBarDescriptors() { return MyViewsTabBar.all(); } public static List<NodePropertyDescriptor> getNodePropertyDescriptors(Class<? extends Node> clazz) { List<NodePropertyDescriptor> result = new ArrayList<NodePropertyDescriptor>(); Collection<NodePropertyDescriptor> list = (Collection) Jenkins.getInstance().getDescriptorList(NodeProperty.class); for (NodePropertyDescriptor npd : list) { if (npd.isApplicable(clazz)) { result.add(npd); } } return result; } /** * Gets all the descriptors sorted by their inheritance tree of {@link Describable} * so that descriptors of similar types come nearby. * * <p> * We sort them by {@link Extension#ordinal()} but only for {@link GlobalConfiguration}s, * as the value is normally used to compare similar kinds of extensions, and we needed * {@link GlobalConfiguration}s to be able to position themselves in a layer above. * This however creates some asymmetry between regular {@link Descriptor}s and {@link GlobalConfiguration}s. * Perhaps it is better to introduce another annotation element? But then, * extensions shouldn't normally concern themselves about ordering too much, and the only reason * we needed this for {@link GlobalConfiguration}s are for backward compatibility. * * @param predicate * Filter the descriptors based on {@link GlobalConfigurationCategory} * @since 1.494 */ public static Collection<Descriptor> getSortedDescriptorsForGlobalConfig(Predicate<GlobalConfigurationCategory> predicate) { ExtensionList<Descriptor> exts = Jenkins.getInstance().getExtensionList(Descriptor.class); List<Tag> r = new ArrayList<Tag>(exts.size()); for (ExtensionComponent<Descriptor> c : exts.getComponents()) { Descriptor d = c.getInstance(); if (d.getGlobalConfigPage()==null) continue; if (d instanceof GlobalConfiguration) { if (predicate.apply(((GlobalConfiguration)d).getCategory())) r.add(new Tag(c.ordinal(), d)); } else { if (predicate.apply(GlobalConfigurationCategory.get(Unclassified.class))) r.add(new Tag(0, d)); } } Collections.sort(r); List<Descriptor> answer = new ArrayList<Descriptor>(r.size()); for (Tag d : r) answer.add(d.d); return DescriptorVisibilityFilter.apply(Jenkins.getInstance(),answer); } /** * Like {@link #getSortedDescriptorsForGlobalConfig(Predicate)} but with a constant truth predicate, to include all descriptors. */ public static Collection<Descriptor> getSortedDescriptorsForGlobalConfig() { return getSortedDescriptorsForGlobalConfig(Predicates.<GlobalConfigurationCategory>alwaysTrue()); } /** * @deprecated This is rather meaningless. */ @Deprecated public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigNoSecurity() { return getSortedDescriptorsForGlobalConfig(Predicates.not(GlobalSecurityConfiguration.FILTER)); } /** * Like {@link #getSortedDescriptorsForGlobalConfig(Predicate)} but for unclassified descriptors only. * @since 1.506 */ public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigUnclassified() { return getSortedDescriptorsForGlobalConfig(new Predicate<GlobalConfigurationCategory>() { public boolean apply(GlobalConfigurationCategory cat) { return cat instanceof GlobalConfigurationCategory.Unclassified; } }); } private static class Tag implements Comparable<Tag> { double ordinal; String hierarchy; Descriptor d; Tag(double ordinal, Descriptor d) { this.ordinal = ordinal; this.d = d; this.hierarchy = buildSuperclassHierarchy(d.clazz, new StringBuilder()).toString(); } private StringBuilder buildSuperclassHierarchy(Class c, StringBuilder buf) { Class sc = c.getSuperclass(); if (sc!=null) buildSuperclassHierarchy(sc,buf).append(':'); return buf.append(c.getName()); } public int compareTo(Tag that) { int r = Double.compare(this.ordinal, that.ordinal); if (r!=0) return -r; // descending for ordinal return this.hierarchy.compareTo(that.hierarchy); } } /** * Computes the path to the icon of the given action * from the context path. */ public static String getIconFilePath(Action a) { String name = a.getIconFileName(); if (name==null) return null; if (name.startsWith("/")) return name.substring(1); else return "images/24x24/"+name; } /** * Works like JSTL build-in size(x) function, * but handle null gracefully. */ public static int size2(Object o) throws Exception { if(o==null) return 0; return ASTSizeFunction.sizeOf(o,Introspector.getUberspect()); } /** * Computes the relative path from the current page to the given item. */ public static String getRelativeLinkTo(Item p) { Map<Object,String> ancestors = new HashMap<Object,String>(); View view=null; StaplerRequest request = Stapler.getCurrentRequest(); for( Ancestor a : request.getAncestors() ) { ancestors.put(a.getObject(),a.getRelativePath()); if(a.getObject() instanceof View) view = (View) a.getObject(); } String path = ancestors.get(p); if(path!=null) return path; Item i=p; String url = ""; while(true) { ItemGroup ig = i.getParent(); url = i.getShortUrl()+url; if(ig== Jenkins.getInstance()) { assert i instanceof TopLevelItem; if(view!=null && view.contains((TopLevelItem)i)) { // if p and the current page belongs to the same view, then return a relative path return ancestors.get(view)+'/'+url; } else { // otherwise return a path from the root Hudson return request.getContextPath()+'/'+p.getUrl(); } } path = ancestors.get(ig); if(path!=null) return path+'/'+url; assert ig instanceof Item; // if not, ig must have been the Hudson instance i = (Item) ig; } } public static Map<Thread,StackTraceElement[]> dumpAllThreads() { Map<Thread,StackTraceElement[]> sorted = new TreeMap<Thread,StackTraceElement[]>(new ThreadSorter()); sorted.putAll(Thread.getAllStackTraces()); return sorted; } @IgnoreJRERequirement public static ThreadInfo[] getThreadInfos() { ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); return mbean.dumpAllThreads(mbean.isObjectMonitorUsageSupported(),mbean.isSynchronizerUsageSupported()); } public static ThreadGroupMap sortThreadsAndGetGroupMap(ThreadInfo[] list) { ThreadGroupMap sorter = new ThreadGroupMap(); Arrays.sort(list, sorter); return sorter; } // Common code for sorting Threads/ThreadInfos by ThreadGroup private static class ThreadSorterBase { protected Map<Long,String> map = new HashMap<Long,String>(); private ThreadSorterBase() { ThreadGroup tg = Thread.currentThread().getThreadGroup(); while (tg.getParent() != null) tg = tg.getParent(); Thread[] threads = new Thread[tg.activeCount()*2]; int threadsLen = tg.enumerate(threads, true); for (int i = 0; i < threadsLen; i++) map.put(threads[i].getId(), threads[i].getThreadGroup().getName()); } protected int compare(long idA, long idB) { String tga = map.get(idA), tgb = map.get(idB); int result = (tga!=null?-1:0) + (tgb!=null?1:0); // Will be non-zero if only one is null if (result==0 && tga!=null) result = tga.compareToIgnoreCase(tgb); return result; } } public static class ThreadGroupMap extends ThreadSorterBase implements Comparator<ThreadInfo> { /** * @return ThreadGroup name or null if unknown */ public String getThreadGroup(ThreadInfo ti) { return map.get(ti.getThreadId()); } public int compare(ThreadInfo a, ThreadInfo b) { int result = compare(a.getThreadId(), b.getThreadId()); if (result == 0) result = a.getThreadName().compareToIgnoreCase(b.getThreadName()); return result; } } private static class ThreadSorter extends ThreadSorterBase implements Comparator<Thread> { public int compare(Thread a, Thread b) { int result = compare(a.getId(), b.getId()); if (result == 0) result = a.getName().compareToIgnoreCase(b.getName()); return result; } } /** * Are we running on JRE6 or above? */ @IgnoreJRERequirement public static boolean isMustangOrAbove() { try { System.console(); return true; } catch(LinkageError e) { return false; } } // ThreadInfo.toString() truncates the stack trace by first 8, so needed my own version @IgnoreJRERequirement public static String dumpThreadInfo(ThreadInfo ti, ThreadGroupMap map) { String grp = map.getThreadGroup(ti); StringBuilder sb = new StringBuilder("\"" + ti.getThreadName() + "\"" + " Id=" + ti.getThreadId() + " Group=" + (grp != null ? grp : "?") + " " + ti.getThreadState()); if (ti.getLockName() != null) { sb.append(" on " + ti.getLockName()); } if (ti.getLockOwnerName() != null) { sb.append(" owned by \"" + ti.getLockOwnerName() + "\" Id=" + ti.getLockOwnerId()); } if (ti.isSuspended()) { sb.append(" (suspended)"); } if (ti.isInNative()) { sb.append(" (in native)"); } sb.append('\n'); StackTraceElement[] stackTrace = ti.getStackTrace(); for (int i=0; i < stackTrace.length; i++) { StackTraceElement ste = stackTrace[i]; sb.append("\tat " + ste.toString()); sb.append('\n'); if (i == 0 && ti.getLockInfo() != null) { Thread.State ts = ti.getThreadState(); switch (ts) { case BLOCKED: sb.append("\t- blocked on " + ti.getLockInfo()); sb.append('\n'); break; case WAITING: sb.append("\t- waiting on " + ti.getLockInfo()); sb.append('\n'); break; case TIMED_WAITING: sb.append("\t- waiting on " + ti.getLockInfo()); sb.append('\n'); break; default: } } for (MonitorInfo mi : ti.getLockedMonitors()) { if (mi.getLockedStackDepth() == i) { sb.append("\t- locked " + mi); sb.append('\n'); } } } LockInfo[] locks = ti.getLockedSynchronizers(); if (locks.length > 0) { sb.append("\n\tNumber of locked synchronizers = " + locks.length); sb.append('\n'); for (LockInfo li : locks) { sb.append("\t- " + li); sb.append('\n'); } } sb.append('\n'); return sb.toString(); } public static <T> Collection<T> emptyList() { return Collections.emptyList(); } public static String jsStringEscape(String s) { StringBuilder buf = new StringBuilder(); for( int i=0; i<s.length(); i++ ) { char ch = s.charAt(i); switch(ch) { case '\'': buf.append("\\'"); break; case '\\': buf.append("\\\\"); break; case '"': buf.append("\\\""); break; default: buf.append(ch); } } return buf.toString(); } /** * Converts "abc" to "Abc". */ public static String capitalize(String s) { if(s==null || s.length()==0) return s; return Character.toUpperCase(s.charAt(0))+s.substring(1); } public static String getVersion() { return Jenkins.VERSION; } /** * Resoruce path prefix. */ public static String getResourcePath() { return Jenkins.RESOURCE_PATH; } public static String getViewResource(Object it, String path) { Class clazz = it.getClass(); if(it instanceof Class) clazz = (Class)it; if(it instanceof Descriptor) clazz = ((Descriptor)it).clazz; StringBuilder buf = new StringBuilder(Stapler.getCurrentRequest().getContextPath()); buf.append(Jenkins.VIEW_RESOURCE_PATH).append('/'); buf.append(clazz.getName().replace('.','/').replace('$','/')); buf.append('/').append(path); return buf.toString(); } public static boolean hasView(Object it, String path) throws IOException { if(it==null) return false; return Stapler.getCurrentRequest().getView(it,path)!=null; } /** * Can be used to check a checkbox by default. * Used from views like {@code h.defaultToTrue(scm.useUpdate)}. * The expression will evaluate to true if scm is null. */ public static boolean defaultToTrue(Boolean b) { if(b==null) return true; return b; } /** * If the value exists, return that value. Otherwise return the default value. * <p> * Starting 1.294, JEXL supports the elvis operator "x?:y" that supercedes this. * * @since 1.150 */ public static <T> T defaulted(T value, T defaultValue) { return value!=null ? value : defaultValue; } public static String printThrowable(Throwable t) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); return sw.toString(); } /** * Counts the number of rows needed for textarea to fit the content. * Minimum 5 rows. */ public static int determineRows(String s) { if(s==null) return 5; return Math.max(5,LINE_END.split(s).length); } /** * Converts the Hudson build status to CruiseControl build status, * which is either Success, Failure, Exception, or Unknown. */ public static String toCCStatus(Item i) { if (i instanceof Job) { Job j = (Job) i; switch (j.getIconColor().noAnime()) { case ABORTED: case RED: case YELLOW: return "Failure"; case BLUE: return "Success"; case DISABLED: case GREY: return "Unknown"; } } return "Unknown"; } private static final Pattern LINE_END = Pattern.compile("\r?\n"); /** * Checks if the current user is anonymous. */ public static boolean isAnonymous() { return Jenkins.getAuthentication() instanceof AnonymousAuthenticationToken; } /** * When called from within JEXL expression evaluation, * this method returns the current {@link JellyContext} used * to evaluate the script. * * @since 1.164 */ public static JellyContext getCurrentJellyContext() { JellyContext context = ExpressionFactory2.CURRENT_CONTEXT.get(); assert context!=null; return context; } /** * Evaluate a Jelly script and return output as a String. * * @since 1.267 */ public static String runScript(Script script) throws JellyTagException { StringWriter out = new StringWriter(); script.run(getCurrentJellyContext(), XMLOutput.createXMLOutput(out)); return out.toString(); } /** * Returns a sub-list if the given list is bigger than the specified 'maxSize' */ public static <T> List<T> subList(List<T> base, int maxSize) { if(maxSize<base.size()) return base.subList(0,maxSize); else return base; } /** * Combine path components via '/' while handling leading/trailing '/' to avoid duplicates. */ public static String joinPath(String... components) { StringBuilder buf = new StringBuilder(); for (String s : components) { if (s.length()==0) continue; if (buf.length()>0) { if (buf.charAt(buf.length()-1)!='/') buf.append('/'); if (s.charAt(0)=='/') s=s.substring(1); } buf.append(s); } return buf.toString(); } /** * Computes the hyperlink to actions, to handle the situation when the {@link Action#getUrlName()} * returns absolute URL. */ public static String getActionUrl(String itUrl,Action action) { String urlName = action.getUrlName(); if(urlName==null) return null; // to avoid NPE and fail to render the whole page try { if (new URI(urlName).isAbsolute()) { return urlName; } } catch (URISyntaxException x) { Logger.getLogger(Functions.class.getName()).log(Level.WARNING, "Failed to parse URL for {0}: {1}", new Object[] {action, x}); return null; } if(urlName.startsWith("/")) return joinPath(Stapler.getCurrentRequest().getContextPath(),urlName); else // relative URL name return joinPath(Stapler.getCurrentRequest().getContextPath()+'/'+itUrl,urlName); } /** * Escapes the character unsafe for e-mail address. * See http://en.wikipedia.org/wiki/E-mail_address for the details, * but here the vocabulary is even more restricted. */ public static String toEmailSafeString(String projectName) { // TODO: escape non-ASCII characters StringBuilder buf = new StringBuilder(projectName.length()); for( int i=0; i<projectName.length(); i++ ) { char ch = projectName.charAt(i); if(('a'<=ch && ch<='z') || ('z'<=ch && ch<='Z') || ('0'<=ch && ch<='9') || "-_.".indexOf(ch)>=0) buf.append(ch); else buf.append('_'); // escape } return projectName; } public String getSystemProperty(String key) { return System.getProperty(key); } /** * Obtains the host name of the Hudson server that clients can use to talk back to. * <p> * This is primarily used in <tt>slave-agent.jnlp.jelly</tt> to specify the destination * that the slaves talk to. */ public String getServerName() { // Try to infer this from the configured root URL. // This makes it work correctly when Hudson runs behind a reverse proxy. String url = Jenkins.getInstance().getRootUrl(); try { if(url!=null) { String host = new URL(url).getHost(); if(host!=null) return host; } } catch (MalformedURLException e) { // fall back to HTTP request } return Stapler.getCurrentRequest().getServerName(); } /** * Determines the form validation check URL. See textbox.jelly */ public String getCheckUrl(String userDefined, Object descriptor, String field) { if(userDefined!=null || field==null) return userDefined; if (descriptor instanceof Descriptor) { Descriptor d = (Descriptor) descriptor; return d.getCheckUrl(field); } return null; } /** * If the given href link is matching the current page, return true. * * Used in <tt>task.jelly</tt> to decide if the page should be highlighted. */ public boolean hyperlinkMatchesCurrentPage(String href) throws UnsupportedEncodingException { String url = Stapler.getCurrentRequest().getRequestURL().toString(); if (href == null || href.length() <= 1) return ".".equals(href) && url.endsWith("/"); url = URLDecoder.decode(url,"UTF-8"); href = URLDecoder.decode(href,"UTF-8"); if (url.endsWith("/")) url = url.substring(0, url.length() - 1); if (href.endsWith("/")) href = href.substring(0, href.length() - 1); return url.endsWith(href); } public <T> List<T> singletonList(T t) { return Collections.singletonList(t); } /** * Gets all the {@link PageDecorator}s. */ public static List<PageDecorator> getPageDecorators() { // this method may be called to render start up errors, at which point Hudson doesn't exist yet. see HUDSON-3608 if(Jenkins.getInstance()==null) return Collections.emptyList(); return PageDecorator.all(); } public static List<Descriptor<Cloud>> getCloudDescriptors() { return Cloud.all(); } /** * Prepend a prefix only when there's the specified body. */ public String prepend(String prefix, String body) { if(body!=null && body.length()>0) return prefix+body; return body; } public static List<Descriptor<CrumbIssuer>> getCrumbIssuerDescriptors() { return CrumbIssuer.all(); } public static String getCrumb(StaplerRequest req) { Jenkins h = Jenkins.getInstance(); CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null; return issuer != null ? issuer.getCrumb(req) : ""; } public static String getCrumbRequestField() { Jenkins h = Jenkins.getInstance(); CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null; return issuer != null ? issuer.getDescriptor().getCrumbRequestField() : ""; } public static Date getCurrentTime() { return new Date(); } public static Locale getCurrentLocale() { Locale locale=null; StaplerRequest req = Stapler.getCurrentRequest(); if(req!=null) locale = req.getLocale(); if(locale==null) locale = Locale.getDefault(); return locale; } /** * Generate a series of &lt;script> tags to include <tt>script.js</tt> * from {@link ConsoleAnnotatorFactory}s and {@link ConsoleAnnotationDescriptor}s. */ public static String generateConsoleAnnotationScriptAndStylesheet() { String cp = Stapler.getCurrentRequest().getContextPath(); StringBuilder buf = new StringBuilder(); for (ConsoleAnnotatorFactory f : ConsoleAnnotatorFactory.all()) { String path = cp + "/extensionList/" + ConsoleAnnotatorFactory.class.getName() + "/" + f.getClass().getName(); if (f.hasScript()) buf.append("<script src='"+path+"/script.js'></script>"); if (f.hasStylesheet()) buf.append("<link rel='stylesheet' type='text/css' href='"+path+"/style.css' />"); } for (ConsoleAnnotationDescriptor d : ConsoleAnnotationDescriptor.all()) { String path = cp+"/descriptor/"+d.clazz.getName(); if (d.hasScript()) buf.append("<script src='"+path+"/script.js'></script>"); if (d.hasStylesheet()) buf.append("<link rel='stylesheet' type='text/css' href='"+path+"/style.css' />"); } return buf.toString(); } /** * Work around for bug 6935026. */ public List<String> getLoggerNames() { while (true) { try { List<String> r = new ArrayList<String>(); Enumeration<String> e = LogManager.getLogManager().getLoggerNames(); while (e.hasMoreElements()) r.add(e.nextElement()); return r; } catch (ConcurrentModificationException e) { // retry } } } /** * Used by &lt;f:password/> so that we send an encrypted value to the client. */ public String getPasswordValue(Object o) { if (o==null) return null; if (o instanceof Secret) return ((Secret)o).getEncryptedValue(); if (getIsUnitTest()) { throw new SecurityException("attempted to render plaintext ‘" + o + "’ in password field; use a getter of type Secret instead"); } return o.toString(); } public List filterDescriptors(Object context, Iterable descriptors) { return DescriptorVisibilityFilter.apply(context,descriptors); } /** * Returns true if we are running unit tests. */ public static boolean getIsUnitTest() { return Main.isUnitTest; } /** * Returns {@code true} if the {@link Run#ARTIFACTS} permission is enabled, * {@code false} otherwise. * * <p>When the {@link Run#ARTIFACTS} permission is not turned on using the * {@code hudson.security.ArtifactsPermission} system property, this * permission must not be considered to be set to {@code false} for every * user. It must rather be like if the permission doesn't exist at all * (which means that every user has to have an access to the artifacts but * the permission can't be configured in the security screen). Got it?</p> */ public static boolean isArtifactsPermissionEnabled() { return Boolean.getBoolean("hudson.security.ArtifactsPermission"); } /** * Returns {@code true} if the {@link Item#WIPEOUT} permission is enabled, * {@code false} otherwise. * * <p>The "Wipe Out Workspace" action available on jobs is controlled by the * {@link Item#BUILD} permission. For some specific projects, however, it is * not acceptable to let users have this possibility, even it they can * trigger builds. As such, when enabling the {@code hudson.security.WipeOutPermission} * system property, a new "WipeOut" permission will allow to have greater * control on the "Wipe Out Workspace" action.</p> */ public static boolean isWipeOutPermissionEnabled() { return Boolean.getBoolean("hudson.security.WipeOutPermission"); } public static String createRenderOnDemandProxy(JellyContext context, String attributesToCapture) { return Stapler.getCurrentRequest().createJavaScriptProxy(new RenderOnDemandClosure(context,attributesToCapture)); } public static String getCurrentDescriptorByNameUrl() { return Descriptor.getCurrentDescriptorByNameUrl(); } public static String setCurrentDescriptorByNameUrl(String value) { String o = getCurrentDescriptorByNameUrl(); Stapler.getCurrentRequest().setAttribute("currentDescriptorByNameUrl", value); return o; } public static void restoreCurrentDescriptorByNameUrl(String old) { Stapler.getCurrentRequest().setAttribute("currentDescriptorByNameUrl", old); } public static List<String> getRequestHeaders(String name) { List<String> r = new ArrayList<String>(); Enumeration e = Stapler.getCurrentRequest().getHeaders(name); while (e.hasMoreElements()) { r.add(e.nextElement().toString()); } return r; } /** * Used for arguments to internationalized expressions to avoid escape */ public static Object rawHtml(Object o) { return o==null ? null : new RawHtmlArgument(o); } public static ArrayList<CLICommand> getCLICommands() { ArrayList<CLICommand> all = new ArrayList<CLICommand>(CLICommand.all()); Collections.sort(all, new Comparator<CLICommand>() { public int compare(CLICommand cliCommand, CLICommand cliCommand1) { return cliCommand.getName().compareTo(cliCommand1.getName()); } }); return all; } /** * Returns an avatar image URL for the specified user and preferred image size * @param user the user * @param avatarSize the preferred size of the avatar image * @return a URL string * @since 1.433 */ public static String getAvatar(User user, String avatarSize) { return UserAvatarResolver.resolve(user, avatarSize); } /** * @deprecated as of 1.451 * Use {@link #getAvatar} */ public String getUserAvatar(User user, String avatarSize) { return getAvatar(user,avatarSize); } /** * Returns human readable information about file size * * @param file size in bytes * @return file size in appropriate unit */ public static String humanReadableByteSize(long size){ String measure = "B"; if(size < 1024){ return size + " " + measure; } Double number = new Double(size); if(number>=1024){ number = number/1024; measure = "KB"; if(number>=1024){ number = number/1024; measure = "MB"; if(number>=1024){ number=number/1024; measure = "GB"; } } } DecimalFormat format = new DecimalFormat("#0.00"); return format.format(number) + " " + measure; } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_2093_0
crossvul-java_data_bad_4760_1
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.SignatureException; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.spec.DSAParameterSpec; import java.security.spec.DSAPrivateKeySpec; import java.security.spec.DSAPublicKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.ASN1Primitive; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.eac.EACObjectIdentifiers; import org.bouncycastle.asn1.nist.NISTNamedCurves; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers; import org.bouncycastle.asn1.x509.AlgorithmIdentifier; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.signers.DSASigner; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.BigIntegers; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.FixedSecureRandom; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.util.test.TestRandomBigInteger; import org.bouncycastle.util.test.TestRandomData; public class DSATest extends SimpleTest { byte[] k1 = Hex.decode("d5014e4b60ef2ba8b6211b4062ba3224e0427dd3"); byte[] k2 = Hex.decode("345e8d05c075c3a508df729a1685690e68fcfb8c8117847e89063bca1f85d968fd281540b6e13bd1af989a1fbf17e06462bf511f9d0b140fb48ac1b1baa5bded"); SecureRandom random = new FixedSecureRandom(new byte[][] { k1, k2 }); // DSA modified signatures, courtesy of the Google security team static final DSAPrivateKeySpec PRIVATE_KEY = new DSAPrivateKeySpec( // x new BigInteger( "15382583218386677486843706921635237927801862255437148328980464126979"), // p new BigInteger( "181118486631420055711787706248812146965913392568235070235446058914" + "1170708161715231951918020125044061516370042605439640379530343556" + "4101919053459832890139496933938670005799610981765220283775567361" + "4836626483403394052203488713085936276470766894079318754834062443" + "1033792580942743268186462355159813630244169054658542719322425431" + "4088256212718983105131138772434658820375111735710449331518776858" + "7867938758654181244292694091187568128410190746310049564097068770" + "8161261634790060655580211122402292101772553741704724263582994973" + "9109274666495826205002104010355456981211025738812433088757102520" + "562459649777989718122219159982614304359"), // q new BigInteger( "19689526866605154788513693571065914024068069442724893395618704484701"), // g new BigInteger( "2859278237642201956931085611015389087970918161297522023542900348" + "0877180630984239764282523693409675060100542360520959501692726128" + "3149190229583566074777557293475747419473934711587072321756053067" + "2532404847508798651915566434553729839971841903983916294692452760" + "2490198571084091890169933809199002313226100830607842692992570749" + "0504363602970812128803790973955960534785317485341020833424202774" + "0275688698461842637641566056165699733710043802697192696426360843" + "1736206792141319514001488556117408586108219135730880594044593648" + "9237302749293603778933701187571075920849848690861126195402696457" + "4111219599568903257472567764789616958430")); static final DSAPublicKeySpec PUBLIC_KEY = new DSAPublicKeySpec( new BigInteger( "3846308446317351758462473207111709291533523711306097971550086650" + "2577333637930103311673872185522385807498738696446063139653693222" + "3528823234976869516765207838304932337200968476150071617737755913" + "3181601169463467065599372409821150709457431511200322947508290005" + "1780020974429072640276810306302799924668893998032630777409440831" + "4314588994475223696460940116068336991199969153649625334724122468" + "7497038281983541563359385775312520539189474547346202842754393945" + "8755803223951078082197762886933401284142487322057236814878262166" + "5072306622943221607031324846468109901964841479558565694763440972" + "5447389416166053148132419345627682740529"), PRIVATE_KEY.getP(), PRIVATE_KEY.getQ(), PRIVATE_KEY.getG()); // The following test vectors check for signature malleability and bugs. That means the test // vectors are derived from a valid signature by modifying the ASN encoding. A correct // implementation of DSA should only accept correct DER encoding and properly handle the others. // Allowing alternative BER encodings is in many cases benign. An example where this kind of // signature malleability was a problem: https://en.bitcoin.it/wiki/Transaction_Malleability static final String[] MODIFIED_SIGNATURES = { "303e02811c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f0282001c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021d001e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd02811d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "303f021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd0282001d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303e021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021e0000ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "30813d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9e" + "f41dd424a4e1c8f16967cf3365813fe8786236", "3082003d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f" + "9ef41dd424a4e1c8f16967cf3365813fe8786236", "303d021c1e41b479ad576905b960fe14eadb91b0ccf34843dab916173bb8c9cd021d00ade65988d237d30f9ef4" + "1dd424a4e1c8f16967cf3365813fe87862360000", "3040021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca8021d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3040100", "303e021c57b10411b54ab248af03d8f2456676ebc6d3db5f1081492ac87e9ca802811d00942b117051d7d9d107fc42cac9c5a36a1fd7f0f8916ccca86cec4ed3" }; private void testModified() throws Exception { KeyFactory kFact = KeyFactory.getInstance("DSA", "BC"); PublicKey pubKey = kFact.generatePublic(PUBLIC_KEY); Signature sig = Signature.getInstance("DSA", "BC"); for (int i = 0; i != MODIFIED_SIGNATURES.length; i++) { sig.initVerify(pubKey); sig.update(Strings.toByteArray("Hello")); boolean failed; try { failed = !sig.verify(Hex.decode(MODIFIED_SIGNATURES[i])); } catch (SignatureException e) { failed = true; } isTrue("sig verified when shouldn't", failed); } } private void testCompat() throws Exception { if (Security.getProvider("SUN") == null) { return; } Signature s = Signature.getInstance("DSA", "SUN"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); // // sign SUN - verify with BC // s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("SUN -> BC verification failed"); } // // sign BC - verify with SUN // s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("DSA", "SUN"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("BC -> SUN verification failed"); } // // key encoding test - BC decoding Sun keys // KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(vKey.getEncoded()); DSAPublicKey k1 = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); PKCS8EncodedKeySpec pkcs8 = new PKCS8EncodedKeySpec(sKey.getEncoded()); DSAPrivateKey k2 = (DSAPrivateKey)f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); // // key decoding test - SUN decoding BC keys // f = KeyFactory.getInstance("DSA", "SUN"); x509s = new X509EncodedKeySpec(k1.getEncoded()); vKey = (DSAPublicKey)f.generatePublic(x509s); checkPublic(k1, vKey); pkcs8 = new PKCS8EncodedKeySpec(k2.getEncoded()); sKey = f.generatePrivate(pkcs8); checkPrivateKey(k2, sKey); } private void testNullParameters() throws Exception { KeyFactory f = KeyFactory.getInstance("DSA", "BC"); X509EncodedKeySpec x509s = new X509EncodedKeySpec(new SubjectPublicKeyInfo(new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa), new ASN1Integer(10001)).getEncoded()); DSAPublicKey key1 = (DSAPublicKey)f.generatePublic(x509s); DSAPublicKey key2 = (DSAPublicKey)f.generatePublic(x509s); isTrue("parameters not absent", key1.getParams() == null && key2.getParams() == null); isTrue("hashCode mismatch", key1.hashCode() == key2.hashCode()); isTrue("not equal", key1.equals(key2)); isTrue("encoding mismatch", Arrays.areEqual(x509s.getEncoded(), key1.getEncoded())); } private void testValidate() throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); KeyFactory f = KeyFactory.getInstance("DSA", "BC"); try { f.generatePublic(new DSAPublicKeySpec(BigInteger.valueOf(1), dsaParams.getP(), dsaParams.getG(), dsaParams.getQ())); fail("no exception"); } catch (Exception e) { isTrue("mismatch", "invalid KeySpec: y value does not appear to be in correct group".equals(e.getMessage())); } } private void testNONEwithDSA() throws Exception { byte[] dummySha1 = Hex.decode("01020304050607080910111213141516"); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA", "BC"); kpGen.initialize(512); KeyPair kp = kpGen.generateKeyPair(); Signature sig = Signature.getInstance("NONEwithDSA", "BC"); sig.initSign(kp.getPrivate()); sig.update(dummySha1); byte[] sigBytes = sig.sign(); sig.initVerify(kp.getPublic()); sig.update(dummySha1); sig.verify(sigBytes); // reset test sig.update(dummySha1); if (!sig.verify(sigBytes)) { fail("NONEwithDSA failed to reset"); } // lightweight test DSAPublicKey key = (DSAPublicKey)kp.getPublic(); DSAParameters params = new DSAParameters(key.getParams().getP(), key.getParams().getQ(), key.getParams().getG()); DSAPublicKeyParameters keyParams = new DSAPublicKeyParameters(key.getY(), params); DSASigner signer = new DSASigner(); ASN1Sequence derSig = ASN1Sequence.getInstance(ASN1Primitive.fromByteArray(sigBytes)); signer.init(false, keyParams); if (!signer.verifySignature(dummySha1, ASN1Integer.getInstance(derSig.getObjectAt(0)).getValue(), ASN1Integer.getInstance(derSig.getObjectAt(1)).getValue())) { fail("NONEwithDSA not really NONE!"); } } private void checkPublic(DSAPublicKey k1, PublicKey vKey) { if (!k1.getY().equals(((DSAPublicKey)vKey).getY())) { fail("public number not decoded properly"); } if (!k1.getParams().getG().equals(((DSAPublicKey)vKey).getParams().getG())) { fail("public generator not decoded properly"); } if (!k1.getParams().getP().equals(((DSAPublicKey)vKey).getParams().getP())) { fail("public p value not decoded properly"); } if (!k1.getParams().getQ().equals(((DSAPublicKey)vKey).getParams().getQ())) { fail("public q value not decoded properly"); } } private void checkPrivateKey(DSAPrivateKey k2, PrivateKey sKey) { if (!k2.getX().equals(((DSAPrivateKey)sKey).getX())) { fail("private number not decoded properly"); } if (!k2.getParams().getG().equals(((DSAPrivateKey)sKey).getParams().getG())) { fail("private generator not decoded properly"); } if (!k2.getParams().getP().equals(((DSAPrivateKey)sKey).getParams().getP())) { fail("private p value not decoded properly"); } if (!k2.getParams().getQ().equals(((DSAPrivateKey)sKey).getParams().getQ())) { fail("private q value not decoded properly"); } } private Object serializeDeserialize(Object o) throws Exception { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ObjectOutputStream oOut = new ObjectOutputStream(bOut); oOut.writeObject(o); oOut.close(); ObjectInputStream oIn = new ObjectInputStream(new ByteArrayInputStream(bOut.toByteArray())); return oIn.readObject(); } /** * X9.62 - 1998,<br> * J.3.2, Page 155, ECDSA over the field Fp<br> * an example with 239 bit prime */ private void testECDSA239bitPrime() throws Exception { BigInteger r = new BigInteger("308636143175167811492622547300668018854959378758531778147462058306432176"); BigInteger s = new BigInteger("323813553209797357708078776831250505931891051755007842781978505179448783"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); sgr.initSign(sKey, k); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testNONEwithECDSA239bitPrime() throws Exception { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), // Q spec); Signature sgr = Signature.getInstance("NONEwithECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKey); PublicKey vKey = f.generatePublic(pubKey); byte[] message = "abc".getBytes(); byte[] sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e64cb19604be06c57e761b3de5518f71de0f6e0cd2df677cec8a6ffcb690d"); checkMessage(sgr, sKey, vKey, message, sig); message = "abcdefghijklmnopqrstuvwxyz".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e43fd65b3363d76aabef8630572257dbb67c82818ad9fad31256539b1b02c"); checkMessage(sgr, sKey, vKey, message, sig); message = "a very very long message gauranteed to cause an overflow".getBytes(); sig = Hex.decode("3040021e2cb7f36803ebb9c427c58d8265f11fc5084747133078fc279de874fbecb0021e7d5be84b22937a1691859a3c6fe45ed30b108574431d01b34025825ec17a"); checkMessage(sgr, sKey, vKey, message, sig); } private void testECDSAP256sha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { X9ECParameters p = NISTNamedCurves.getByName("P-256"); KeyFactory ecKeyFact = KeyFactory.getInstance("EC", "BC"); ECDomainParameters params = new ECDomainParameters(p.getCurve(), p.getG(), p.getN(), p.getH()); ECCurve curve = p.getCurve(); ECParameterSpec spec = new ECParameterSpec( curve, p.getG(), // G p.getN()); // n ECPrivateKeySpec priKey = new ECPrivateKeySpec( new BigInteger("20186677036482506117540275567393538695075300175221296989956723148347484984008"), // d spec); ECPublicKeySpec pubKey = new ECPublicKeySpec( params.getCurve().decodePoint(Hex.decode("03596375E6CE57E0F20294FC46BDFCFD19A39F8161B58695B3EC5B3D16427C274D")), // Q spec); doEcDsaTest("SHA3-" + size + "withECDSA", s, ecKeyFact, pubKey, priKey); doEcDsaTest(sigOid.getId(), s, ecKeyFact, pubKey, priKey); } private void doEcDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, ECPublicKeySpec pubKey, ECPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new TestRandomBigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("97354732615802252173078420023658453040116611318111190383344590814578738210384"); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void testDSAsha3(ASN1ObjectIdentifier sigOid, int size, BigInteger s) throws Exception { DSAParameterSpec dsaParams = new DSAParameterSpec( new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16), new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16), new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16) ); BigInteger x = new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16); BigInteger y = new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16); DSAPrivateKeySpec priKey = new DSAPrivateKeySpec( x, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); DSAPublicKeySpec pubKey = new DSAPublicKeySpec( y, dsaParams.getP(), dsaParams.getQ(), dsaParams.getG()); KeyFactory dsaKeyFact = KeyFactory.getInstance("DSA", "BC"); doDsaTest("SHA3-" + size + "withDSA", s, dsaKeyFact, pubKey, priKey); doDsaTest(sigOid.getId(), s, dsaKeyFact, pubKey, priKey); } private void doDsaTest(String sigName, BigInteger s, KeyFactory ecKeyFact, DSAPublicKeySpec pubKey, DSAPrivateKeySpec priKey) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, InvalidKeySpecException, SignatureException { SecureRandom k = new FixedSecureRandom( new FixedSecureRandom.Source[] { new FixedSecureRandom.BigInteger(BigIntegers.asUnsignedByteArray(new BigInteger("72546832179840998877302529996971396893172522460793442785601695562409154906335"))), new FixedSecureRandom.Data(Hex.decode("01020304")) }); byte[] M = Hex.decode("1BD4ED430B0F384B4E8D458EFF1A8A553286D7AC21CB2F6806172EF5F94A06AD"); Signature dsa = Signature.getInstance(sigName, "BC"); dsa.initSign(ecKeyFact.generatePrivate(priKey), k); dsa.update(M, 0, M.length); byte[] encSig = dsa.sign(); ASN1Sequence sig = ASN1Sequence.getInstance(encSig); BigInteger r = new BigInteger("4864074fe30e6601268ee663440e4d9b703f62673419864e91e9edb0338ce510", 16); BigInteger sigR = ASN1Integer.getInstance(sig.getObjectAt(0)).getValue(); if (!r.equals(sigR)) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r.toString(16) + Strings.lineSeparator() + " got : " + sigR.toString(16)); } BigInteger sigS = ASN1Integer.getInstance(sig.getObjectAt(1)).getValue(); if (!s.equals(sigS)) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s.toString(16) + Strings.lineSeparator() + " got : " + sigS.toString(16)); } // Verify the signature dsa.initVerify(ecKeyFact.generatePublic(pubKey)); dsa.update(M, 0, M.length); if (!dsa.verify(encSig)) { fail("signature fails"); } } private void checkMessage(Signature sgr, PrivateKey sKey, PublicKey vKey, byte[] message, byte[] sig) throws InvalidKeyException, SignatureException { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("700000017569056646655505781757157107570501575775705779575555657156756655")); SecureRandom k = new TestRandomBigInteger(kData); sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); if (!Arrays.areEqual(sigBytes, sig)) { fail(new String(message) + " signature incorrect"); } sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail(new String(message) + " verification failed"); } } /** * X9.62 - 1998,<br> * J.2.1, Page 100, ECDSA over the field F2m<br> * an example with 191 bit binary field */ private void testECDSA239bitBinary() throws Exception { BigInteger r = new BigInteger("21596333210419611985018340039034612628818151486841789642455876922391552"); BigInteger s = new BigInteger("197030374000731686738334997654997227052849804072198819102649413465737174"); byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance("ECDSA", "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC verification failed"); } BigInteger[] sig = derDecode(sigBytes); if (!r.equals(sig[0])) { fail("r component wrong." + Strings.lineSeparator() + " expecting: " + r + Strings.lineSeparator() + " got : " + sig[0]); } if (!s.equals(sig[1])) { fail("s component wrong." + Strings.lineSeparator() + " expecting: " + s + Strings.lineSeparator() + " got : " + sig[1]); } } private void testECDSA239bitBinary(String algorithm, ASN1ObjectIdentifier oid) throws Exception { byte[] kData = BigIntegers.asUnsignedByteArray(new BigInteger("171278725565216523967285789236956265265265235675811949404040041670216363")); SecureRandom k = new TestRandomBigInteger(kData); ECCurve curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ECParameterSpec params = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h ECPrivateKeySpec priKeySpec = new ECPrivateKeySpec( new BigInteger("145642755521911534651321230007534120304391871461646461466464667494947990"), // d params); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("045894609CCECF9A92533F630DE713A958E96C97CCB8F5ABB5A688A238DEED6DC2D9D0C94EBFB7D526BA6A61764175B99CB6011E2047F9F067293F57F5")), // Q params); Signature sgr = Signature.getInstance(algorithm, "BC"); KeyFactory f = KeyFactory.getInstance("ECDSA", "BC"); PrivateKey sKey = f.generatePrivate(priKeySpec); PublicKey vKey = f.generatePublic(pubKeySpec); byte[] message = new byte[] { (byte)'a', (byte)'b', (byte)'c' }; sgr.initSign(sKey, k); sgr.update(message); byte[] sigBytes = sgr.sign(); sgr = Signature.getInstance(oid.getId(), "BC"); sgr.initVerify(vKey); sgr.update(message); if (!sgr.verify(sigBytes)) { fail("239 Bit EC RIPEMD160 verification failed"); } } private void testGeneration() throws Exception { Signature s = Signature.getInstance("DSA", "BC"); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; // test exception // try { g.initialize(513, new SecureRandom()); fail("illegal parameter 513 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(510, new SecureRandom()); fail("illegal parameter 510 check failed."); } catch (IllegalArgumentException e) { // expected } try { g.initialize(1025, new SecureRandom()); fail("illegal parameter 1025 check failed."); } catch (IllegalArgumentException e) { // expected } g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } // // key decoding test - serialisation test // DSAPublicKey k1 = (DSAPublicKey)serializeDeserialize(vKey); checkPublic(k1, vKey); checkEquals(k1, vKey); DSAPrivateKey k2 = (DSAPrivateKey)serializeDeserialize(sKey); checkPrivateKey(k2, sKey); checkEquals(k2, sKey); if (!(k2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } // // ECDSA Fp generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), // q new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), // a new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); // b ECParameterSpec ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), // G new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); // n g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // PublicKey eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); PrivateKey eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // Named curve parameter g.initialize(new ECNamedCurveGenParameterSpec("P-256"), new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); // // ECDSA F2m generation test // s = Signature.getInstance("ECDSA", "BC"); g = KeyPairGenerator.getInstance("ECDSA", "BC"); curve = new ECCurve.F2m( 239, // m 36, // k new BigInteger("32010857077C5431123A46B808906756F543423E8D27877578125778AC76", 16), // a new BigInteger("790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", 16)); // b ecSpec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("0457927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305")), // G new BigInteger("220855883097298041197912187592864814557886993776713230936715041207411783"), // n BigInteger.valueOf(4)); // h g.initialize(ecSpec, new SecureRandom()); p = g.generateKeyPair(); sKey = p.getPrivate(); vKey = p.getPublic(); s.initSign(sKey); s.update(data); sigBytes = s.sign(); s = Signature.getInstance("ECDSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("ECDSA verification failed"); } // // key decoding test - serialisation test // eck1 = (PublicKey)serializeDeserialize(vKey); checkEquals(eck1, vKey); eck2 = (PrivateKey)serializeDeserialize(sKey); checkEquals(eck2, sKey); if (!(eck2 instanceof PKCS12BagAttributeCarrier)) { fail("private key not implementing PKCS12 attribute carrier"); } } private void checkEquals(Object o1, Object o2) { if (!o1.equals(o2)) { fail("comparison test failed"); } if (o1.hashCode() != o2.hashCode()) { fail("hashCode test failed"); } } private void testParameters() throws Exception { AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(512, random); AlgorithmParameters params = a.generateParameters(); byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new SecureRandom()); KeyPair p = g.generateKeyPair(); PrivateKey sKey = p.getPrivate(); PublicKey vKey = p.getPublic(); Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } private void testDSA2Parameters() throws Exception { byte[] seed = Hex.decode("4783081972865EA95D43318AB2EAF9C61A2FC7BBF1B772A09017BDF5A58F4FF0"); AlgorithmParameterGenerator a = AlgorithmParameterGenerator.getInstance("DSA", "BC"); a.init(2048, new DSATestSecureRandom(seed)); AlgorithmParameters params = a.generateParameters(); DSAParameterSpec dsaP = (DSAParameterSpec)params.getParameterSpec(DSAParameterSpec.class); if (!dsaP.getQ().equals(new BigInteger("C24ED361870B61E0D367F008F99F8A1F75525889C89DB1B673C45AF5867CB467", 16))) { fail("Q incorrect"); } if (!dsaP.getP().equals(new BigInteger( "F56C2A7D366E3EBDEAA1891FD2A0D099" + "436438A673FED4D75F594959CFFEBCA7BE0FC72E4FE67D91" + "D801CBA0693AC4ED9E411B41D19E2FD1699C4390AD27D94C" + "69C0B143F1DC88932CFE2310C886412047BD9B1C7A67F8A2" + "5909132627F51A0C866877E672E555342BDF9355347DBD43" + "B47156B2C20BAD9D2B071BC2FDCF9757F75C168C5D9FC431" + "31BE162A0756D1BDEC2CA0EB0E3B018A8B38D3EF2487782A" + "EB9FBF99D8B30499C55E4F61E5C7DCEE2A2BB55BD7F75FCD" + "F00E48F2E8356BDB59D86114028F67B8E07B127744778AFF" + "1CF1399A4D679D92FDE7D941C5C85C5D7BFF91BA69F9489D" + "531D1EBFA727CFDA651390F8021719FA9F7216CEB177BD75", 16))) { fail("P incorrect"); } if (!dsaP.getG().equals(new BigInteger( "8DC6CC814CAE4A1C05A3E186A6FE27EA" + "BA8CDB133FDCE14A963A92E809790CBA096EAA26140550C1" + "29FA2B98C16E84236AA33BF919CD6F587E048C52666576DB" + "6E925C6CBE9B9EC5C16020F9A44C9F1C8F7A8E611C1F6EC2" + "513EA6AA0B8D0F72FED73CA37DF240DB57BBB27431D61869" + "7B9E771B0B301D5DF05955425061A30DC6D33BB6D2A32BD0" + "A75A0A71D2184F506372ABF84A56AEEEA8EB693BF29A6403" + "45FA1298A16E85421B2208D00068A5A42915F82CF0B858C8" + "FA39D43D704B6927E0B2F916304E86FB6A1B487F07D8139E" + "428BB096C6D67A76EC0B8D4EF274B8A2CF556D279AD267CC" + "EF5AF477AFED029F485B5597739F5D0240F67C2D948A6279", 16))) { fail("G incorrect"); } KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "BC"); g.initialize(dsaP, new TestRandomBigInteger(Hex.decode("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C"))); KeyPair p = g.generateKeyPair(); DSAPrivateKey sKey = (DSAPrivateKey)p.getPrivate(); DSAPublicKey vKey = (DSAPublicKey)p.getPublic(); if (!vKey.getY().equals(new BigInteger( "2828003D7C747199143C370FDD07A286" + "1524514ACC57F63F80C38C2087C6B795B62DE1C224BF8D1D" + "1424E60CE3F5AE3F76C754A2464AF292286D873A7A30B7EA" + "CBBC75AAFDE7191D9157598CDB0B60E0C5AA3F6EBE425500" + "C611957DBF5ED35490714A42811FDCDEB19AF2AB30BEADFF" + "2907931CEE7F3B55532CFFAEB371F84F01347630EB227A41" + "9B1F3F558BC8A509D64A765D8987D493B007C4412C297CAF" + "41566E26FAEE475137EC781A0DC088A26C8804A98C23140E" + "7C936281864B99571EE95C416AA38CEEBB41FDBFF1EB1D1D" + "C97B63CE1355257627C8B0FD840DDB20ED35BE92F08C49AE" + "A5613957D7E5C7A6D5A5834B4CB069E0831753ECF65BA02B", 16))) { fail("Y value incorrect"); } if (!sKey.getX().equals( new BigInteger("0CAF2EF547EC49C4F3A6FE6DF4223A174D01F2C115D49A6F73437C29A2A8458C", 16))) { fail("X value incorrect"); } byte[] encodeParams = params.getEncoded(); AlgorithmParameters a2 = AlgorithmParameters.getInstance("DSA", "BC"); a2.init(encodeParams); // a and a2 should be equivalent! byte[] encodeParams_2 = a2.getEncoded(); if (!areEqual(encodeParams, encodeParams_2)) { fail("encode/decode parameters failed"); } Signature s = Signature.getInstance("DSA", "BC"); byte[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; s.initSign(sKey); s.update(data); byte[] sigBytes = s.sign(); s = Signature.getInstance("DSA", "BC"); s.initVerify(vKey); s.update(data); if (!s.verify(sigBytes)) { fail("DSA verification failed"); } } public void performTest() throws Exception { testCompat(); testNONEwithDSA(); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_224, 224, new BigInteger("613202af2a7f77e02b11b5c3a5311cf6b412192bc0032aac3ec127faebfc6bd0", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_256, 256, new BigInteger("2450755c5e15a691b121bc833b97864e34a61ee025ecec89289c949c1858091e", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_384, 384, new BigInteger("7aad97c0b71bb1e1a6483b6948a03bbe952e4780b0cee699a11731f90d84ddd1", 16)); testDSAsha3(NISTObjectIdentifiers.id_dsa_with_sha3_512, 512, new BigInteger("725ad64d923c668e64e7c3898b5efde484cab49ce7f98c2885d2a13a9e355ad4", 16)); testECDSA239bitPrime(); testNONEwithECDSA239bitPrime(); testECDSA239bitBinary(); testECDSA239bitBinary("RIPEMD160withECDSA", TeleTrusTObjectIdentifiers.ecSignWithRipemd160); testECDSA239bitBinary("SHA1withECDSA", TeleTrusTObjectIdentifiers.ecSignWithSha1); testECDSA239bitBinary("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); testECDSA239bitBinary("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); testECDSA239bitBinary("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); testECDSA239bitBinary("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); testECDSA239bitBinary("SHA1withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_1); testECDSA239bitBinary("SHA224withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_224); testECDSA239bitBinary("SHA256withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_256); testECDSA239bitBinary("SHA384withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_384); testECDSA239bitBinary("SHA512withCVC-ECDSA", EACObjectIdentifiers.id_TA_ECDSA_SHA_512); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_224, 224, new BigInteger("84d7d8e68e405064109cd9fc3e3026d74d278aada14ce6b7a9dd0380c154dc94", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_256, 256, new BigInteger("99a43bdab4af989aaf2899079375642f2bae2dce05bcd8b72ec8c4a8d9a143f", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_384, 384, new BigInteger("aa27726509c37aaf601de6f7e01e11c19add99530c9848381c23365dc505b11a", 16)); testECDSAP256sha3(NISTObjectIdentifiers.id_ecdsa_with_sha3_512, 512, new BigInteger("f8306b57a1f5068bf12e53aabaae39e2658db39bc56747eaefb479995130ad16", 16)); testGeneration(); testParameters(); testDSA2Parameters(); testNullParameters(); testValidate(); testModified(); } protected BigInteger[] derDecode( byte[] encoding) throws IOException { ByteArrayInputStream bIn = new ByteArrayInputStream(encoding); ASN1InputStream aIn = new ASN1InputStream(bIn); ASN1Sequence s = (ASN1Sequence)aIn.readObject(); BigInteger[] sig = new BigInteger[2]; sig[0] = ((ASN1Integer)s.getObjectAt(0)).getValue(); sig[1] = ((ASN1Integer)s.getObjectAt(1)).getValue(); return sig; } public String getName() { return "DSA/ECDSA"; } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new DSATest()); } private class DSATestSecureRandom extends TestRandomData { private boolean first = true; public DSATestSecureRandom(byte[] value) { super(value); } public void nextBytes(byte[] bytes) { if (first) { super.nextBytes(bytes); first = false; } else { bytes[bytes.length - 1] = 2; } } } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4760_1
crossvul-java_data_good_4760_0
package org.bouncycastle.jcajce.provider.asymmetric.dsa; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidParameterException; import java.security.KeyPair; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.DSAParameterSpec; import java.util.Hashtable; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.digests.SHA256Digest; import org.bouncycastle.crypto.generators.DSAKeyPairGenerator; import org.bouncycastle.crypto.generators.DSAParametersGenerator; import org.bouncycastle.crypto.params.DSAKeyGenerationParameters; import org.bouncycastle.crypto.params.DSAParameterGenerationParameters; import org.bouncycastle.crypto.params.DSAParameters; import org.bouncycastle.crypto.params.DSAPrivateKeyParameters; import org.bouncycastle.crypto.params.DSAPublicKeyParameters; import org.bouncycastle.util.Integers; import org.bouncycastle.util.Properties; public class KeyPairGeneratorSpi extends java.security.KeyPairGenerator { private static Hashtable params = new Hashtable(); private static Object lock = new Object(); DSAKeyGenerationParameters param; DSAKeyPairGenerator engine = new DSAKeyPairGenerator(); int strength = 1024; int certainty = 20; SecureRandom random = new SecureRandom(); boolean initialised = false; public KeyPairGeneratorSpi() { super("DSA"); } public void initialize( int strength, SecureRandom random) { if (strength < 512 || strength > 4096 || ((strength < 1024) && strength % 64 != 0) || (strength >= 1024 && strength % 1024 != 0)) { throw new InvalidParameterException("strength must be from 512 - 4096 and a multiple of 1024 above 1024"); } this.strength = strength; this.random = random; this.initialised = false; } public void initialize( AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(params instanceof DSAParameterSpec)) { throw new InvalidAlgorithmParameterException("parameter object not a DSAParameterSpec"); } DSAParameterSpec dsaParams = (DSAParameterSpec)params; param = new DSAKeyGenerationParameters(random, new DSAParameters(dsaParams.getP(), dsaParams.getQ(), dsaParams.getG())); engine.init(param); initialised = true; } public KeyPair generateKeyPair() { if (!initialised) { Integer paramStrength = Integers.valueOf(strength); if (params.containsKey(paramStrength)) { param = (DSAKeyGenerationParameters)params.get(paramStrength); } else { synchronized (lock) { // we do the check again in case we were blocked by a generator for // our key size. if (params.containsKey(paramStrength)) { param = (DSAKeyGenerationParameters)params.get(paramStrength); } else { DSAParametersGenerator pGen; DSAParameterGenerationParameters dsaParams; // Typical combination of keysize and size of q. // keysize = 1024, q's size = 160 // keysize = 2048, q's size = 224 // keysize = 2048, q's size = 256 // keysize = 3072, q's size = 256 // For simplicity if keysize is greater than 1024 then we choose q's size to be 256. // For legacy keysize that is less than 1024-bit, we just use the 186-2 style parameters if (strength == 1024) { pGen = new DSAParametersGenerator(); if (Properties.isOverrideSet("org.bouncycastle.dsa.FIPS186-2for1024bits")) { pGen.init(strength, certainty, random); } else { dsaParams = new DSAParameterGenerationParameters(1024, 160, certainty, random); pGen.init(dsaParams); } } else if (strength > 1024) { dsaParams = new DSAParameterGenerationParameters(strength, 256, certainty, random); pGen = new DSAParametersGenerator(new SHA256Digest()); pGen.init(dsaParams); } else { pGen = new DSAParametersGenerator(); pGen.init(strength, certainty, random); } param = new DSAKeyGenerationParameters(random, pGen.generateParameters()); params.put(paramStrength, param); } } } engine.init(param); initialised = true; } AsymmetricCipherKeyPair pair = engine.generateKeyPair(); DSAPublicKeyParameters pub = (DSAPublicKeyParameters)pair.getPublic(); DSAPrivateKeyParameters priv = (DSAPrivateKeyParameters)pair.getPrivate(); return new KeyPair(new BCDSAPublicKey(pub), new BCDSAPrivateKey(priv)); } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4760_0
crossvul-java_data_good_2093_3
/* * The MIT License * * Copyright 2013 Jesse Glick. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.model; import static org.junit.Assert.assertEquals; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; public class PasswordParameterDefinitionTest { @Rule public JenkinsRule j = new JenkinsRule(); @Test public void defaultValueKeptSecret() throws Exception { FreeStyleProject p = j.createFreeStyleProject(); p.addProperty(new ParametersDefinitionProperty(new PasswordParameterDefinition("p", "s3cr3t", ""))); j.configRoundtrip(p); assertEquals("s3cr3t", ((PasswordParameterDefinition) p.getProperty(ParametersDefinitionProperty.class).getParameterDefinition("p")).getDefaultValue()); } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_2093_3
crossvul-java_data_good_4755_0
package org.bouncycastle.crypto.engines; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.OutputLengthException; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Pack; /** * an implementation of the AES (Rijndael), from FIPS-197. * <p> * For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a> * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor, they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations, 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each, for a total of 2Kbytes, * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first. * * The slowest version uses no static tables at all and computes the values in each round. * <p> * This file contains the middle performance version with 2Kbytes of static tables for round precomputation. * */ public class AESEngine implements BlockCipher { // The S box private static final byte[] S = { (byte)99, (byte)124, (byte)119, (byte)123, (byte)242, (byte)107, (byte)111, (byte)197, (byte)48, (byte)1, (byte)103, (byte)43, (byte)254, (byte)215, (byte)171, (byte)118, (byte)202, (byte)130, (byte)201, (byte)125, (byte)250, (byte)89, (byte)71, (byte)240, (byte)173, (byte)212, (byte)162, (byte)175, (byte)156, (byte)164, (byte)114, (byte)192, (byte)183, (byte)253, (byte)147, (byte)38, (byte)54, (byte)63, (byte)247, (byte)204, (byte)52, (byte)165, (byte)229, (byte)241, (byte)113, (byte)216, (byte)49, (byte)21, (byte)4, (byte)199, (byte)35, (byte)195, (byte)24, (byte)150, (byte)5, (byte)154, (byte)7, (byte)18, (byte)128, (byte)226, (byte)235, (byte)39, (byte)178, (byte)117, (byte)9, (byte)131, (byte)44, (byte)26, (byte)27, (byte)110, (byte)90, (byte)160, (byte)82, (byte)59, (byte)214, (byte)179, (byte)41, (byte)227, (byte)47, (byte)132, (byte)83, (byte)209, (byte)0, (byte)237, (byte)32, (byte)252, (byte)177, (byte)91, (byte)106, (byte)203, (byte)190, (byte)57, (byte)74, (byte)76, (byte)88, (byte)207, (byte)208, (byte)239, (byte)170, (byte)251, (byte)67, (byte)77, (byte)51, (byte)133, (byte)69, (byte)249, (byte)2, (byte)127, (byte)80, (byte)60, (byte)159, (byte)168, (byte)81, (byte)163, (byte)64, (byte)143, (byte)146, (byte)157, (byte)56, (byte)245, (byte)188, (byte)182, (byte)218, (byte)33, (byte)16, (byte)255, (byte)243, (byte)210, (byte)205, (byte)12, (byte)19, (byte)236, (byte)95, (byte)151, (byte)68, (byte)23, (byte)196, (byte)167, (byte)126, (byte)61, (byte)100, (byte)93, (byte)25, (byte)115, (byte)96, (byte)129, (byte)79, (byte)220, (byte)34, (byte)42, (byte)144, (byte)136, (byte)70, (byte)238, (byte)184, (byte)20, (byte)222, (byte)94, (byte)11, (byte)219, (byte)224, (byte)50, (byte)58, (byte)10, (byte)73, (byte)6, (byte)36, (byte)92, (byte)194, (byte)211, (byte)172, (byte)98, (byte)145, (byte)149, (byte)228, (byte)121, (byte)231, (byte)200, (byte)55, (byte)109, (byte)141, (byte)213, (byte)78, (byte)169, (byte)108, (byte)86, (byte)244, (byte)234, (byte)101, (byte)122, (byte)174, (byte)8, (byte)186, (byte)120, (byte)37, (byte)46, (byte)28, (byte)166, (byte)180, (byte)198, (byte)232, (byte)221, (byte)116, (byte)31, (byte)75, (byte)189, (byte)139, (byte)138, (byte)112, (byte)62, (byte)181, (byte)102, (byte)72, (byte)3, (byte)246, (byte)14, (byte)97, (byte)53, (byte)87, (byte)185, (byte)134, (byte)193, (byte)29, (byte)158, (byte)225, (byte)248, (byte)152, (byte)17, (byte)105, (byte)217, (byte)142, (byte)148, (byte)155, (byte)30, (byte)135, (byte)233, (byte)206, (byte)85, (byte)40, (byte)223, (byte)140, (byte)161, (byte)137, (byte)13, (byte)191, (byte)230, (byte)66, (byte)104, (byte)65, (byte)153, (byte)45, (byte)15, (byte)176, (byte)84, (byte)187, (byte)22, }; // The inverse S-box private static final byte[] Si = { (byte)82, (byte)9, (byte)106, (byte)213, (byte)48, (byte)54, (byte)165, (byte)56, (byte)191, (byte)64, (byte)163, (byte)158, (byte)129, (byte)243, (byte)215, (byte)251, (byte)124, (byte)227, (byte)57, (byte)130, (byte)155, (byte)47, (byte)255, (byte)135, (byte)52, (byte)142, (byte)67, (byte)68, (byte)196, (byte)222, (byte)233, (byte)203, (byte)84, (byte)123, (byte)148, (byte)50, (byte)166, (byte)194, (byte)35, (byte)61, (byte)238, (byte)76, (byte)149, (byte)11, (byte)66, (byte)250, (byte)195, (byte)78, (byte)8, (byte)46, (byte)161, (byte)102, (byte)40, (byte)217, (byte)36, (byte)178, (byte)118, (byte)91, (byte)162, (byte)73, (byte)109, (byte)139, (byte)209, (byte)37, (byte)114, (byte)248, (byte)246, (byte)100, (byte)134, (byte)104, (byte)152, (byte)22, (byte)212, (byte)164, (byte)92, (byte)204, (byte)93, (byte)101, (byte)182, (byte)146, (byte)108, (byte)112, (byte)72, (byte)80, (byte)253, (byte)237, (byte)185, (byte)218, (byte)94, (byte)21, (byte)70, (byte)87, (byte)167, (byte)141, (byte)157, (byte)132, (byte)144, (byte)216, (byte)171, (byte)0, (byte)140, (byte)188, (byte)211, (byte)10, (byte)247, (byte)228, (byte)88, (byte)5, (byte)184, (byte)179, (byte)69, (byte)6, (byte)208, (byte)44, (byte)30, (byte)143, (byte)202, (byte)63, (byte)15, (byte)2, (byte)193, (byte)175, (byte)189, (byte)3, (byte)1, (byte)19, (byte)138, (byte)107, (byte)58, (byte)145, (byte)17, (byte)65, (byte)79, (byte)103, (byte)220, (byte)234, (byte)151, (byte)242, (byte)207, (byte)206, (byte)240, (byte)180, (byte)230, (byte)115, (byte)150, (byte)172, (byte)116, (byte)34, (byte)231, (byte)173, (byte)53, (byte)133, (byte)226, (byte)249, (byte)55, (byte)232, (byte)28, (byte)117, (byte)223, (byte)110, (byte)71, (byte)241, (byte)26, (byte)113, (byte)29, (byte)41, (byte)197, (byte)137, (byte)111, (byte)183, (byte)98, (byte)14, (byte)170, (byte)24, (byte)190, (byte)27, (byte)252, (byte)86, (byte)62, (byte)75, (byte)198, (byte)210, (byte)121, (byte)32, (byte)154, (byte)219, (byte)192, (byte)254, (byte)120, (byte)205, (byte)90, (byte)244, (byte)31, (byte)221, (byte)168, (byte)51, (byte)136, (byte)7, (byte)199, (byte)49, (byte)177, (byte)18, (byte)16, (byte)89, (byte)39, (byte)128, (byte)236, (byte)95, (byte)96, (byte)81, (byte)127, (byte)169, (byte)25, (byte)181, (byte)74, (byte)13, (byte)45, (byte)229, (byte)122, (byte)159, (byte)147, (byte)201, (byte)156, (byte)239, (byte)160, (byte)224, (byte)59, (byte)77, (byte)174, (byte)42, (byte)245, (byte)176, (byte)200, (byte)235, (byte)187, (byte)60, (byte)131, (byte)83, (byte)153, (byte)97, (byte)23, (byte)43, (byte)4, (byte)126, (byte)186, (byte)119, (byte)214, (byte)38, (byte)225, (byte)105, (byte)20, (byte)99, (byte)85, (byte)33, (byte)12, (byte)125, }; // vector used in calculating key schedule (powers of x in GF(256)) private static final int[] rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static final int[] T0 = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c}; private static final int[] Tinv0 = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0}; private static int shift(int r, int shift) { return (r >>> shift) | (r << -shift); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private static final int m1 = 0x80808080; private static final int m2 = 0x7f7f7f7f; private static final int m3 = 0x0000001b; private static final int m4 = 0xC0C0C0C0; private static final int m5 = 0x3f3f3f3f; private static int FFmulX(int x) { return (((x & m2) << 1) ^ (((x & m1) >>> 7) * m3)); } private static int FFmulX2(int x) { int t0 = (x & m5) << 2; int t1 = (x & m4); t1 ^= (t1 >>> 1); return t0 ^ (t1 >>> 2) ^ (t1 >>> 5); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private static int inv_mcol(int x) { int t0, t1; t0 = x; t1 = t0 ^ shift(t0, 8); t0 ^= FFmulX(t1); t1 ^= FFmulX2(t0); t0 ^= t1 ^ shift(t1, 16); return t0; } private static int subWord(int x) { return (S[x&255]&255 | ((S[(x>>8)&255]&255)<<8) | ((S[(x>>16)&255]&255)<<16) | S[(x>>24)&255]<<24); } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private int[][] generateWorkingKey(byte[] key, boolean forEncryption) { int keyLen = key.length; if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) { throw new IllegalArgumentException("Key length not 128/192/256 bits."); } int KC = keyLen >>> 2; ROUNDS = KC + 6; // This is not always true for the generalized Rijndael that allows larger block sizes int[][] W = new int[ROUNDS+1][4]; // 4 words in a block switch (KC) { case 4: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; for (int i = 1; i <= 10; ++i) { int u = subWord(shift(t3, 8)) ^ rcon[i - 1]; t0 ^= u; W[i][0] = t0; t1 ^= t0; W[i][1] = t1; t2 ^= t1; W[i][2] = t2; t3 ^= t2; W[i][3] = t3; } break; } case 6: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; int t4 = Pack.littleEndianToInt(key, 16); W[1][0] = t4; int t5 = Pack.littleEndianToInt(key, 20); W[1][1] = t5; int rcon = 1; int u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[1][2] = t0; t1 ^= t0; W[1][3] = t1; t2 ^= t1; W[2][0] = t2; t3 ^= t2; W[2][1] = t3; t4 ^= t3; W[2][2] = t4; t5 ^= t4; W[2][3] = t5; for (int i = 3; i < 12; i += 3) { u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i ][0] = t0; t1 ^= t0; W[i ][1] = t1; t2 ^= t1; W[i ][2] = t2; t3 ^= t2; W[i ][3] = t3; t4 ^= t3; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; u = subWord(shift(t5, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i + 1][2] = t0; t1 ^= t0; W[i + 1][3] = t1; t2 ^= t1; W[i + 2][0] = t2; t3 ^= t2; W[i + 2][1] = t3; t4 ^= t3; W[i + 2][2] = t4; t5 ^= t4; W[i + 2][3] = t5; } u = subWord(shift(t5, 8)) ^ rcon; t0 ^= u; W[12][0] = t0; t1 ^= t0; W[12][1] = t1; t2 ^= t1; W[12][2] = t2; t3 ^= t2; W[12][3] = t3; break; } case 8: { int t0 = Pack.littleEndianToInt(key, 0); W[0][0] = t0; int t1 = Pack.littleEndianToInt(key, 4); W[0][1] = t1; int t2 = Pack.littleEndianToInt(key, 8); W[0][2] = t2; int t3 = Pack.littleEndianToInt(key, 12); W[0][3] = t3; int t4 = Pack.littleEndianToInt(key, 16); W[1][0] = t4; int t5 = Pack.littleEndianToInt(key, 20); W[1][1] = t5; int t6 = Pack.littleEndianToInt(key, 24); W[1][2] = t6; int t7 = Pack.littleEndianToInt(key, 28); W[1][3] = t7; int u, rcon = 1; for (int i = 2; i < 14; i += 2) { u = subWord(shift(t7, 8)) ^ rcon; rcon <<= 1; t0 ^= u; W[i ][0] = t0; t1 ^= t0; W[i ][1] = t1; t2 ^= t1; W[i ][2] = t2; t3 ^= t2; W[i ][3] = t3; u = subWord(t3); t4 ^= u; W[i + 1][0] = t4; t5 ^= t4; W[i + 1][1] = t5; t6 ^= t5; W[i + 1][2] = t6; t7 ^= t6; W[i + 1][3] = t7; } u = subWord(shift(t7, 8)) ^ rcon; t0 ^= u; W[14][0] = t0; t1 ^= t0; W[14][1] = t1; t2 ^= t1; W[14][2] = t2; t3 ^= t2; W[14][3] = t3; break; } default: { throw new IllegalStateException("Should never get here"); } } if (!forEncryption) { for (int j = 1; j < ROUNDS; j++) { for (int i = 0; i < 4; i++) { W[j][i] = inv_mcol(W[j][i]); } } } return W; } private int ROUNDS; private int[][] WorkingKey = null; private int C0, C1, C2, C3; private boolean forEncryption; private byte[] s; private static final int BLOCK_SIZE = 16; /** * default constructor - 128 bit block size. */ public AESEngine() { } /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param params the parameters required to set up the cipher. * @exception IllegalArgumentException if the params argument is * inappropriate. */ public void init( boolean forEncryption, CipherParameters params) { if (params instanceof KeyParameter) { WorkingKey = generateWorkingKey(((KeyParameter)params).getKey(), forEncryption); this.forEncryption = forEncryption; if (forEncryption) { s = Arrays.clone(S); } else { s = Arrays.clone(Si); } return; } throw new IllegalArgumentException("invalid parameter passed to AES init - " + params.getClass().getName()); } public String getAlgorithmName() { return "AES"; } public int getBlockSize() { return BLOCK_SIZE; } public int processBlock( byte[] in, int inOff, byte[] out, int outOff) { if (WorkingKey == null) { throw new IllegalStateException("AES engine not initialised"); } if ((inOff + (32 / 2)) > in.length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (32 / 2)) > out.length) { throw new OutputLengthException("output buffer too short"); } if (forEncryption) { unpackBlock(in, inOff); encryptBlock(WorkingKey); packBlock(out, outOff); } else { unpackBlock(in, inOff); decryptBlock(WorkingKey); packBlock(out, outOff); } return BLOCK_SIZE; } public void reset() { } private void unpackBlock( byte[] bytes, int off) { int index = off; C0 = (bytes[index++] & 0xff); C0 |= (bytes[index++] & 0xff) << 8; C0 |= (bytes[index++] & 0xff) << 16; C0 |= bytes[index++] << 24; C1 = (bytes[index++] & 0xff); C1 |= (bytes[index++] & 0xff) << 8; C1 |= (bytes[index++] & 0xff) << 16; C1 |= bytes[index++] << 24; C2 = (bytes[index++] & 0xff); C2 |= (bytes[index++] & 0xff) << 8; C2 |= (bytes[index++] & 0xff) << 16; C2 |= bytes[index++] << 24; C3 = (bytes[index++] & 0xff); C3 |= (bytes[index++] & 0xff) << 8; C3 |= (bytes[index++] & 0xff) << 16; C3 |= bytes[index++] << 24; } private void packBlock( byte[] bytes, int off) { int index = off; bytes[index++] = (byte)C0; bytes[index++] = (byte)(C0 >> 8); bytes[index++] = (byte)(C0 >> 16); bytes[index++] = (byte)(C0 >> 24); bytes[index++] = (byte)C1; bytes[index++] = (byte)(C1 >> 8); bytes[index++] = (byte)(C1 >> 16); bytes[index++] = (byte)(C1 >> 24); bytes[index++] = (byte)C2; bytes[index++] = (byte)(C2 >> 8); bytes[index++] = (byte)(C2 >> 16); bytes[index++] = (byte)(C2 >> 24); bytes[index++] = (byte)C3; bytes[index++] = (byte)(C3 >> 8); bytes[index++] = (byte)(C3 >> 16); bytes[index++] = (byte)(C3 >> 24); } private void encryptBlock(int[][] KW) { int t0 = this.C0 ^ KW[0][0]; int t1 = this.C1 ^ KW[0][1]; int t2 = this.C2 ^ KW[0][2]; int r = 1, r0, r1, r2, r3 = this.C3 ^ KW[0][3]; while (r < ROUNDS - 1) { r0 = T0[t0&255] ^ shift(T0[(t1>>8)&255], 24) ^ shift(T0[(t2>>16)&255], 16) ^ shift(T0[(r3>>24)&255], 8) ^ KW[r][0]; r1 = T0[t1&255] ^ shift(T0[(t2>>8)&255], 24) ^ shift(T0[(r3>>16)&255], 16) ^ shift(T0[(t0>>24)&255], 8) ^ KW[r][1]; r2 = T0[t2&255] ^ shift(T0[(r3>>8)&255], 24) ^ shift(T0[(t0>>16)&255], 16) ^ shift(T0[(t1>>24)&255], 8) ^ KW[r][2]; r3 = T0[r3&255] ^ shift(T0[(t0>>8)&255], 24) ^ shift(T0[(t1>>16)&255], 16) ^ shift(T0[(t2>>24)&255], 8) ^ KW[r++][3]; t0 = T0[r0&255] ^ shift(T0[(r1>>8)&255], 24) ^ shift(T0[(r2>>16)&255], 16) ^ shift(T0[(r3>>24)&255], 8) ^ KW[r][0]; t1 = T0[r1&255] ^ shift(T0[(r2>>8)&255], 24) ^ shift(T0[(r3>>16)&255], 16) ^ shift(T0[(r0>>24)&255], 8) ^ KW[r][1]; t2 = T0[r2&255] ^ shift(T0[(r3>>8)&255], 24) ^ shift(T0[(r0>>16)&255], 16) ^ shift(T0[(r1>>24)&255], 8) ^ KW[r][2]; r3 = T0[r3&255] ^ shift(T0[(r0>>8)&255], 24) ^ shift(T0[(r1>>16)&255], 16) ^ shift(T0[(r2>>24)&255], 8) ^ KW[r++][3]; } r0 = T0[t0&255] ^ shift(T0[(t1>>8)&255], 24) ^ shift(T0[(t2>>16)&255], 16) ^ shift(T0[(r3>>24)&255], 8) ^ KW[r][0]; r1 = T0[t1&255] ^ shift(T0[(t2>>8)&255], 24) ^ shift(T0[(r3>>16)&255], 16) ^ shift(T0[(t0>>24)&255], 8) ^ KW[r][1]; r2 = T0[t2&255] ^ shift(T0[(r3>>8)&255], 24) ^ shift(T0[(t0>>16)&255], 16) ^ shift(T0[(t1>>24)&255], 8) ^ KW[r][2]; r3 = T0[r3&255] ^ shift(T0[(t0>>8)&255], 24) ^ shift(T0[(t1>>16)&255], 16) ^ shift(T0[(t2>>24)&255], 8) ^ KW[r++][3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it this.C0 = (S[r0&255]&255) ^ ((S[(r1>>8)&255]&255)<<8) ^ ((s[(r2>>16)&255]&255)<<16) ^ (s[(r3>>24)&255]<<24) ^ KW[r][0]; this.C1 = (s[r1&255]&255) ^ ((S[(r2>>8)&255]&255)<<8) ^ ((S[(r3>>16)&255]&255)<<16) ^ (s[(r0>>24)&255]<<24) ^ KW[r][1]; this.C2 = (s[r2&255]&255) ^ ((S[(r3>>8)&255]&255)<<8) ^ ((S[(r0>>16)&255]&255)<<16) ^ (S[(r1>>24)&255]<<24) ^ KW[r][2]; this.C3 = (s[r3&255]&255) ^ ((s[(r0>>8)&255]&255)<<8) ^ ((s[(r1>>16)&255]&255)<<16) ^ (S[(r2>>24)&255]<<24) ^ KW[r][3]; } private void decryptBlock(int[][] KW) { int t0 = this.C0 ^ KW[ROUNDS][0]; int t1 = this.C1 ^ KW[ROUNDS][1]; int t2 = this.C2 ^ KW[ROUNDS][2]; int r = ROUNDS - 1, r0, r1, r2, r3 = this.C3 ^ KW[ROUNDS][3]; while (r > 1) { r0 = Tinv0[t0&255] ^ shift(Tinv0[(r3>>8)&255], 24) ^ shift(Tinv0[(t2>>16)&255], 16) ^ shift(Tinv0[(t1>>24)&255], 8) ^ KW[r][0]; r1 = Tinv0[t1&255] ^ shift(Tinv0[(t0>>8)&255], 24) ^ shift(Tinv0[(r3>>16)&255], 16) ^ shift(Tinv0[(t2>>24)&255], 8) ^ KW[r][1]; r2 = Tinv0[t2&255] ^ shift(Tinv0[(t1>>8)&255], 24) ^ shift(Tinv0[(t0>>16)&255], 16) ^ shift(Tinv0[(r3>>24)&255], 8) ^ KW[r][2]; r3 = Tinv0[r3&255] ^ shift(Tinv0[(t2>>8)&255], 24) ^ shift(Tinv0[(t1>>16)&255], 16) ^ shift(Tinv0[(t0>>24)&255], 8) ^ KW[r--][3]; t0 = Tinv0[r0&255] ^ shift(Tinv0[(r3>>8)&255], 24) ^ shift(Tinv0[(r2>>16)&255], 16) ^ shift(Tinv0[(r1>>24)&255], 8) ^ KW[r][0]; t1 = Tinv0[r1&255] ^ shift(Tinv0[(r0>>8)&255], 24) ^ shift(Tinv0[(r3>>16)&255], 16) ^ shift(Tinv0[(r2>>24)&255], 8) ^ KW[r][1]; t2 = Tinv0[r2&255] ^ shift(Tinv0[(r1>>8)&255], 24) ^ shift(Tinv0[(r0>>16)&255], 16) ^ shift(Tinv0[(r3>>24)&255], 8) ^ KW[r][2]; r3 = Tinv0[r3&255] ^ shift(Tinv0[(r2>>8)&255], 24) ^ shift(Tinv0[(r1>>16)&255], 16) ^ shift(Tinv0[(r0>>24)&255], 8) ^ KW[r--][3]; } r0 = Tinv0[t0&255] ^ shift(Tinv0[(r3>>8)&255], 24) ^ shift(Tinv0[(t2>>16)&255], 16) ^ shift(Tinv0[(t1>>24)&255], 8) ^ KW[r][0]; r1 = Tinv0[t1&255] ^ shift(Tinv0[(t0>>8)&255], 24) ^ shift(Tinv0[(r3>>16)&255], 16) ^ shift(Tinv0[(t2>>24)&255], 8) ^ KW[r][1]; r2 = Tinv0[t2&255] ^ shift(Tinv0[(t1>>8)&255], 24) ^ shift(Tinv0[(t0>>16)&255], 16) ^ shift(Tinv0[(r3>>24)&255], 8) ^ KW[r][2]; r3 = Tinv0[r3&255] ^ shift(Tinv0[(t2>>8)&255], 24) ^ shift(Tinv0[(t1>>16)&255], 16) ^ shift(Tinv0[(t0>>24)&255], 8) ^ KW[r][3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it this.C0 = (Si[r0&255]&255) ^ ((s[(r3>>8)&255]&255)<<8) ^ ((s[(r2>>16)&255]&255)<<16) ^ (Si[(r1>>24)&255]<<24) ^ KW[0][0]; this.C1 = (s[r1&255]&255) ^ ((s[(r0>>8)&255]&255)<<8) ^ ((Si[(r3>>16)&255]&255)<<16) ^ (s[(r2>>24)&255]<<24) ^ KW[0][1]; this.C2 = (s[r2&255]&255) ^ ((Si[(r1>>8)&255]&255)<<8) ^ ((Si[(r0>>16)&255]&255)<<16) ^ (s[(r3>>24)&255]<<24) ^ KW[0][2]; this.C3 = (Si[r3&255]&255) ^ ((s[(r2>>8)&255]&255)<<8) ^ ((s[(r1>>16)&255]&255)<<16) ^ (s[(r0>>24)&255]<<24) ^ KW[0][3]; } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4755_0
crossvul-java_data_bad_2093_0
/* * The MIT License * * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, * Yahoo! Inc., Stephen Connolly, Tom Huybrechts, Alan Harder, Manufacture * Francaise des Pneumatiques Michelin, Romain Seguy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import hudson.cli.CLICommand; import hudson.console.ConsoleAnnotationDescriptor; import hudson.console.ConsoleAnnotatorFactory; import hudson.model.*; import hudson.model.ParameterDefinition.ParameterDescriptor; import hudson.search.SearchableModelObject; import hudson.security.AccessControlled; import hudson.security.AuthorizationStrategy; import hudson.security.GlobalSecurityConfiguration; import hudson.security.Permission; import hudson.security.SecurityRealm; import hudson.security.captcha.CaptchaSupport; import hudson.security.csrf.CrumbIssuer; import hudson.slaves.Cloud; import hudson.slaves.ComputerLauncher; import hudson.slaves.NodeProperty; import hudson.slaves.NodePropertyDescriptor; import hudson.slaves.RetentionStrategy; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildWrapper; import hudson.tasks.BuildWrappers; import hudson.tasks.Builder; import hudson.tasks.Publisher; import hudson.tasks.UserAvatarResolver; import hudson.util.Area; import hudson.util.Iterators; import hudson.scm.SCM; import hudson.scm.SCMDescriptor; import hudson.util.Secret; import hudson.views.MyViewsTabBar; import hudson.views.ViewsTabBar; import hudson.widgets.RenderOnDemandClosure; import jenkins.model.GlobalConfiguration; import jenkins.model.GlobalConfigurationCategory; import jenkins.model.GlobalConfigurationCategory.Unclassified; import jenkins.model.Jenkins; import jenkins.model.ModelObjectWithContextMenu; import org.acegisecurity.providers.anonymous.AnonymousAuthenticationToken; import org.apache.commons.jelly.JellyContext; import org.apache.commons.jelly.JellyTagException; import org.apache.commons.jelly.Script; import org.apache.commons.jelly.XMLOutput; import org.apache.commons.jexl.parser.ASTSizeFunction; import org.apache.commons.jexl.util.Introspector; import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; import org.jvnet.tiger_types.Types; import org.kohsuke.stapler.Ancestor; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.jelly.InternationalizedStringExpression.RawHtmlArgument; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.management.LockInfo; import java.lang.management.ManagementFactory; import java.lang.management.MonitorInfo; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLDecoder; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.Date; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.LogRecord; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; /** * Utility functions used in views. * * <p> * An instance of this class is created for each request and made accessible * from view pages via the variable 'h' (h stands for Hudson.) * * @author Kohsuke Kawaguchi */ public class Functions { private static volatile int globalIota = 0; private int iota; public Functions() { iota = globalIota; // concurrent requests can use the same ID --- we are just trying to // prevent the same user from seeing the same ID repeatedly. globalIota+=1000; } /** * Generates an unique ID. */ public String generateId() { return "id"+iota++; } public static boolean isModel(Object o) { return o instanceof ModelObject; } public static boolean isModelWithContextMenu(Object o) { return o instanceof ModelObjectWithContextMenu; } public static String xsDate(Calendar cal) { return Util.XS_DATETIME_FORMATTER.format(cal.getTime()); } public static String rfc822Date(Calendar cal) { return Util.RFC822_DATETIME_FORMATTER.format(cal.getTime()); } public static void initPageVariables(JellyContext context) { String rootURL = Stapler.getCurrentRequest().getContextPath(); Functions h = new Functions(); context.setVariable("h", h); // The path starts with a "/" character but does not end with a "/" character. context.setVariable("rootURL", rootURL); /* load static resources from the path dedicated to a specific version. This "/static/VERSION/abc/def.ghi" path is interpreted by stapler to be the same thing as "/abc/def.ghi", but this avoids the stale cache problem when the user upgrades to new Jenkins. Stapler also sets a long future expiration dates for such static resources. see https://wiki.jenkins-ci.org/display/JENKINS/Hyperlinks+in+HTML */ context.setVariable("resURL",rootURL+getResourcePath()); context.setVariable("imagesURL",rootURL+getResourcePath()+"/images"); } /** * Given {@code c=MyList (extends ArrayList<Foo>), base=List}, compute the parameterization of 'base' * that's assignable from 'c' (in this case {@code List<Foo>}), and return its n-th type parameter * (n=0 would return {@code Foo}). * * <p> * This method is useful for doing type arithmetic. * * @throws AssertionError * if c' is not parameterized. */ public static <B> Class getTypeParameter(Class<? extends B> c, Class<B> base, int n) { Type parameterization = Types.getBaseClass(c,base); if (parameterization instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) parameterization; return Types.erasure(Types.getTypeArgument(pt,n)); } else { throw new AssertionError(c+" doesn't properly parameterize "+base); } } public JDK.DescriptorImpl getJDKDescriptor() { return Jenkins.getInstance().getDescriptorByType(JDK.DescriptorImpl.class); } /** * Prints the integer as a string that represents difference, * like "-5", "+/-0", "+3". */ public static String getDiffString(int i) { if(i==0) return "\u00B10"; // +/-0 String s = Integer.toString(i); if(i>0) return "+"+s; else return s; } /** * {@link #getDiffString(int)} that doesn't show anything for +/-0 */ public static String getDiffString2(int i) { if(i==0) return ""; String s = Integer.toString(i); if(i>0) return "+"+s; else return s; } /** * {@link #getDiffString2(int)} that puts the result into prefix and suffix * if there's something to print */ public static String getDiffString2(String prefix, int i, String suffix) { if(i==0) return ""; String s = Integer.toString(i); if(i>0) return prefix+"+"+s+suffix; else return prefix+s+suffix; } /** * Adds the proper suffix. */ public static String addSuffix(int n, String singular, String plural) { StringBuilder buf = new StringBuilder(); buf.append(n).append(' '); if(n==1) buf.append(singular); else buf.append(plural); return buf.toString(); } public static RunUrl decompose(StaplerRequest req) { List<Ancestor> ancestors = req.getAncestors(); // find the first and last Run instances Ancestor f=null,l=null; for (Ancestor anc : ancestors) { if(anc.getObject() instanceof Run) { if(f==null) f=anc; l=anc; } } if(l==null) return null; // there was no Run object String head = f.getPrev().getUrl()+'/'; String base = l.getUrl(); String reqUri = req.getOriginalRequestURI(); // Find "rest" or URI by removing N path components. // Not using reqUri.substring(f.getUrl().length()) to avoid mismatches due to // url-encoding or extra slashes. Former may occur in Tomcat (despite the spec saying // this string is not decoded, Tomcat apparently decodes this string. You see ' ' // instead of '%20', which is what the browser has sent), latter may occur in some // proxy or URL-rewriting setups where extra slashes are inadvertently added. String furl = f.getUrl(); int slashCount = 0; // Count components in ancestor URL for (int i = furl.indexOf('/'); i >= 0; i = furl.indexOf('/', i + 1)) slashCount++; // Remove that many from request URL, ignoring extra slashes String rest = reqUri.replaceFirst("(?:/+[^/]*){" + slashCount + "}", ""); return new RunUrl( (Run) f.getObject(), head, base, rest); } /** * If we know the user's screen resolution, return it. Otherwise null. * @since 1.213 */ public static Area getScreenResolution() { Cookie res = Functions.getCookie(Stapler.getCurrentRequest(),"screenResolution"); if(res!=null) return Area.parse(res.getValue()); return null; } /** * URL decomposed for easier computation of relevant URLs. * * <p> * The decomposed URL will be of the form: * <pre> * aaaaaa/524/bbbbb/cccc * -head-| N |---rest--- * ----- base -----| * </pre> * * <p> * The head portion is the part of the URL from the {@link jenkins.model.Jenkins} * object to the first {@link Run} subtype. When "next/prev build" * is chosen, this part remains intact. * * <p> * The <tt>524</tt> is the path from {@link Job} to {@link Run}. * * <p> * The <tt>bbb</tt> portion is the path after that till the last * {@link Run} subtype. The <tt>ccc</tt> portion is the part * after that. */ public static final class RunUrl { private final String head, base, rest; private final Run run; public RunUrl(Run run, String head, String base, String rest) { this.run = run; this.head = head; this.base = base; this.rest = rest; } public String getBaseUrl() { return base; } /** * Returns the same page in the next build. */ public String getNextBuildUrl() { return getUrl(run.getNextBuild()); } /** * Returns the same page in the previous build. */ public String getPreviousBuildUrl() { return getUrl(run.getPreviousBuild()); } private String getUrl(Run n) { if(n ==null) return null; else { return head+n.getNumber()+rest; } } } public static Node.Mode[] getNodeModes() { return Node.Mode.values(); } public static String getProjectListString(List<Project> projects) { return Items.toNameList(projects); } /** * @deprecated as of 1.294 * JEXL now supports the real ternary operator "x?y:z", so this work around * is no longer necessary. */ public static Object ifThenElse(boolean cond, Object thenValue, Object elseValue) { return cond ? thenValue : elseValue; } public static String appendIfNotNull(String text, String suffix, String nullText) { return text == null ? nullText : text + suffix; } public static Map getSystemProperties() { return new TreeMap<Object,Object>(System.getProperties()); } public static Map getEnvVars() { return new TreeMap<String,String>(EnvVars.masterEnvVars); } public static boolean isWindows() { return File.pathSeparatorChar==';'; } public static List<LogRecord> getLogRecords() { return Jenkins.logRecords; } public static String printLogRecord(LogRecord r) { return formatter.format(r); } public static Cookie getCookie(HttpServletRequest req,String name) { Cookie[] cookies = req.getCookies(); if(cookies!=null) { for (Cookie cookie : cookies) { if(cookie.getName().equals(name)) { return cookie; } } } return null; } public static String getCookie(HttpServletRequest req,String name, String defaultValue) { Cookie c = getCookie(req, name); if(c==null || c.getValue()==null) return defaultValue; return c.getValue(); } private static final Pattern ICON_SIZE = Pattern.compile("\\d+x\\d+"); @Restricted(NoExternalUse.class) public static String validateIconSize(String iconSize) throws SecurityException { if (!ICON_SIZE.matcher(iconSize).matches()) { throw new SecurityException("invalid iconSize"); } return iconSize; } /** * Gets the suffix to use for YUI JavaScript. */ public static String getYuiSuffix() { return DEBUG_YUI ? "debug" : "min"; } /** * Set to true if you need to use the debug version of YUI. */ public static boolean DEBUG_YUI = Boolean.getBoolean("debug.YUI"); /** * Creates a sub map by using the given range (both ends inclusive). */ public static <V> SortedMap<Integer,V> filter(SortedMap<Integer,V> map, String from, String to) { if(from==null && to==null) return map; if(to==null) return map.headMap(Integer.parseInt(from)-1); if(from==null) return map.tailMap(Integer.parseInt(to)); return map.subMap(Integer.parseInt(to),Integer.parseInt(from)-1); } private static final SimpleFormatter formatter = new SimpleFormatter(); /** * Used by <tt>layout.jelly</tt> to control the auto refresh behavior. * * @param noAutoRefresh * On certain pages, like a page with forms, will have annoying interference * with auto refresh. On those pages, disable auto-refresh. */ public static void configureAutoRefresh(HttpServletRequest request, HttpServletResponse response, boolean noAutoRefresh) { if(noAutoRefresh) return; String param = request.getParameter("auto_refresh"); boolean refresh = isAutoRefresh(request); if (param != null) { refresh = Boolean.parseBoolean(param); Cookie c = new Cookie("hudson_auto_refresh", Boolean.toString(refresh)); // Need to set path or it will not stick from e.g. a project page to the dashboard. // Using request.getContextPath() might work but it seems simpler to just use the hudson_ prefix // to avoid conflicts with any other web apps that might be on the same machine. c.setPath("/"); c.setMaxAge(60*60*24*30); // persist it roughly for a month response.addCookie(c); } if (refresh) { response.addHeader("Refresh", System.getProperty("hudson.Functions.autoRefreshSeconds", "10")); } } public static boolean isAutoRefresh(HttpServletRequest request) { String param = request.getParameter("auto_refresh"); if (param != null) { return Boolean.parseBoolean(param); } Cookie[] cookies = request.getCookies(); if(cookies==null) return false; // when API design messes it up, we all suffer for (Cookie c : cookies) { if (c.getName().equals("hudson_auto_refresh")) { return Boolean.parseBoolean(c.getValue()); } } return false; } /** * Finds the given object in the ancestor list and returns its URL. * This is used to determine the "current" URL assigned to the given object, * so that one can compute relative URLs from it. */ public static String getNearestAncestorUrl(StaplerRequest req,Object it) { List list = req.getAncestors(); for( int i=list.size()-1; i>=0; i-- ) { Ancestor anc = (Ancestor) list.get(i); if(anc.getObject()==it) return anc.getUrl(); } return null; } /** * Finds the inner-most {@link SearchableModelObject} in scope. */ public static String getSearchURL() { List list = Stapler.getCurrentRequest().getAncestors(); for( int i=list.size()-1; i>=0; i-- ) { Ancestor anc = (Ancestor) list.get(i); if(anc.getObject() instanceof SearchableModelObject) return anc.getUrl()+"/search/"; } return null; } public static String appendSpaceIfNotNull(String n) { if(n==null) return null; else return n+' '; } /** * One nbsp per 10 pixels in given size, which may be a plain number or "NxN" * (like an iconSize). Useful in a sortable table heading. */ public static String nbspIndent(String size) { int i = size.indexOf('x'); i = Integer.parseInt(i > 0 ? size.substring(0, i) : size) / 10; StringBuilder buf = new StringBuilder(30); for (int j = 0; j < i; j++) buf.append("&nbsp;"); return buf.toString(); } public static String getWin32ErrorMessage(IOException e) { return Util.getWin32ErrorMessage(e); } public static boolean isMultiline(String s) { if(s==null) return false; return s.indexOf('\r')>=0 || s.indexOf('\n')>=0; } public static String encode(String s) { return Util.encode(s); } public static String escape(String s) { return Util.escape(s); } public static String xmlEscape(String s) { return Util.xmlEscape(s); } public static String xmlUnescape(String s) { return s.replace("&lt;","<").replace("&gt;",">").replace("&amp;","&"); } public static String htmlAttributeEscape(String text) { StringBuilder buf = new StringBuilder(text.length()+64); for( int i=0; i<text.length(); i++ ) { char ch = text.charAt(i); if(ch=='<') buf.append("&lt;"); else if(ch=='>') buf.append("&gt;"); else if(ch=='&') buf.append("&amp;"); else if(ch=='"') buf.append("&quot;"); else if(ch=='\'') buf.append("&#39;"); else buf.append(ch); } return buf.toString(); } public static void checkPermission(Permission permission) throws IOException, ServletException { checkPermission(Jenkins.getInstance(),permission); } public static void checkPermission(AccessControlled object, Permission permission) throws IOException, ServletException { if (permission != null) { object.checkPermission(permission); } } /** * This version is so that the 'checkPermission' on <tt>layout.jelly</tt> * degrades gracefully if "it" is not an {@link AccessControlled} object. * Otherwise it will perform no check and that problem is hard to notice. */ public static void checkPermission(Object object, Permission permission) throws IOException, ServletException { if (permission == null) return; if (object instanceof AccessControlled) checkPermission((AccessControlled) object,permission); else { List<Ancestor> ancs = Stapler.getCurrentRequest().getAncestors(); for(Ancestor anc : Iterators.reverse(ancs)) { Object o = anc.getObject(); if (o instanceof AccessControlled) { checkPermission((AccessControlled) o,permission); return; } } checkPermission(Jenkins.getInstance(),permission); } } /** * Returns true if the current user has the given permission. * * @param permission * If null, returns true. This defaulting is convenient in making the use of this method terse. */ public static boolean hasPermission(Permission permission) throws IOException, ServletException { return hasPermission(Jenkins.getInstance(),permission); } /** * This version is so that the 'hasPermission' can degrade gracefully * if "it" is not an {@link AccessControlled} object. */ public static boolean hasPermission(Object object, Permission permission) throws IOException, ServletException { if (permission == null) return true; if (object instanceof AccessControlled) return ((AccessControlled)object).hasPermission(permission); else { List<Ancestor> ancs = Stapler.getCurrentRequest().getAncestors(); for(Ancestor anc : Iterators.reverse(ancs)) { Object o = anc.getObject(); if (o instanceof AccessControlled) { return ((AccessControlled)o).hasPermission(permission); } } return Jenkins.getInstance().hasPermission(permission); } } public static void adminCheck(StaplerRequest req, StaplerResponse rsp, Object required, Permission permission) throws IOException, ServletException { // this is legacy --- all views should be eventually converted to // the permission based model. if(required!=null && !Hudson.adminCheck(req, rsp)) { // check failed. commit the FORBIDDEN response, then abort. rsp.setStatus(HttpServletResponse.SC_FORBIDDEN); rsp.getOutputStream().close(); throw new ServletException("Unauthorized access"); } // make sure the user owns the necessary permission to access this page. if(permission!=null) checkPermission(permission); } /** * Infers the hudson installation URL from the given request. */ public static String inferHudsonURL(StaplerRequest req) { String rootUrl = Jenkins.getInstance().getRootUrl(); if(rootUrl !=null) // prefer the one explicitly configured, to work with load-balancer, frontend, etc. return rootUrl; StringBuilder buf = new StringBuilder(); buf.append(req.getScheme()).append("://"); buf.append(req.getServerName()); if(! (req.getScheme().equals("http") && req.getLocalPort()==80 || req.getScheme().equals("https") && req.getLocalPort()==443)) buf.append(':').append(req.getLocalPort()); buf.append(req.getContextPath()).append('/'); return buf.toString(); } /** * Returns the link to be displayed in the footer of the UI. */ public static String getFooterURL() { if(footerURL == null) { footerURL = System.getProperty("hudson.footerURL"); if(StringUtils.isBlank(footerURL)) { footerURL = "http://jenkins-ci.org/"; } } return footerURL; } private static String footerURL = null; public static List<JobPropertyDescriptor> getJobPropertyDescriptors(Class<? extends Job> clazz) { return JobPropertyDescriptor.getPropertyDescriptors(clazz); } public static List<Descriptor<BuildWrapper>> getBuildWrapperDescriptors(AbstractProject<?,?> project) { return BuildWrappers.getFor(project); } public static List<Descriptor<SecurityRealm>> getSecurityRealmDescriptors() { return SecurityRealm.all(); } public static List<Descriptor<AuthorizationStrategy>> getAuthorizationStrategyDescriptors() { return AuthorizationStrategy.all(); } public static List<Descriptor<Builder>> getBuilderDescriptors(AbstractProject<?,?> project) { return BuildStepDescriptor.filter(Builder.all(), project.getClass()); } public static List<Descriptor<Publisher>> getPublisherDescriptors(AbstractProject<?,?> project) { return BuildStepDescriptor.filter(Publisher.all(), project.getClass()); } public static List<SCMDescriptor<?>> getSCMDescriptors(AbstractProject<?,?> project) { return SCM._for(project); } public static List<Descriptor<ComputerLauncher>> getComputerLauncherDescriptors() { return Jenkins.getInstance().<ComputerLauncher,Descriptor<ComputerLauncher>>getDescriptorList(ComputerLauncher.class); } public static List<Descriptor<RetentionStrategy<?>>> getRetentionStrategyDescriptors() { return RetentionStrategy.all(); } public static List<ParameterDescriptor> getParameterDescriptors() { return ParameterDefinition.all(); } public static List<Descriptor<CaptchaSupport>> getCaptchaSupportDescriptors() { return CaptchaSupport.all(); } public static List<Descriptor<ViewsTabBar>> getViewsTabBarDescriptors() { return ViewsTabBar.all(); } public static List<Descriptor<MyViewsTabBar>> getMyViewsTabBarDescriptors() { return MyViewsTabBar.all(); } public static List<NodePropertyDescriptor> getNodePropertyDescriptors(Class<? extends Node> clazz) { List<NodePropertyDescriptor> result = new ArrayList<NodePropertyDescriptor>(); Collection<NodePropertyDescriptor> list = (Collection) Jenkins.getInstance().getDescriptorList(NodeProperty.class); for (NodePropertyDescriptor npd : list) { if (npd.isApplicable(clazz)) { result.add(npd); } } return result; } /** * Gets all the descriptors sorted by their inheritance tree of {@link Describable} * so that descriptors of similar types come nearby. * * <p> * We sort them by {@link Extension#ordinal()} but only for {@link GlobalConfiguration}s, * as the value is normally used to compare similar kinds of extensions, and we needed * {@link GlobalConfiguration}s to be able to position themselves in a layer above. * This however creates some asymmetry between regular {@link Descriptor}s and {@link GlobalConfiguration}s. * Perhaps it is better to introduce another annotation element? But then, * extensions shouldn't normally concern themselves about ordering too much, and the only reason * we needed this for {@link GlobalConfiguration}s are for backward compatibility. * * @param predicate * Filter the descriptors based on {@link GlobalConfigurationCategory} * @since 1.494 */ public static Collection<Descriptor> getSortedDescriptorsForGlobalConfig(Predicate<GlobalConfigurationCategory> predicate) { ExtensionList<Descriptor> exts = Jenkins.getInstance().getExtensionList(Descriptor.class); List<Tag> r = new ArrayList<Tag>(exts.size()); for (ExtensionComponent<Descriptor> c : exts.getComponents()) { Descriptor d = c.getInstance(); if (d.getGlobalConfigPage()==null) continue; if (d instanceof GlobalConfiguration) { if (predicate.apply(((GlobalConfiguration)d).getCategory())) r.add(new Tag(c.ordinal(), d)); } else { if (predicate.apply(GlobalConfigurationCategory.get(Unclassified.class))) r.add(new Tag(0, d)); } } Collections.sort(r); List<Descriptor> answer = new ArrayList<Descriptor>(r.size()); for (Tag d : r) answer.add(d.d); return DescriptorVisibilityFilter.apply(Jenkins.getInstance(),answer); } /** * Like {@link #getSortedDescriptorsForGlobalConfig(Predicate)} but with a constant truth predicate, to include all descriptors. */ public static Collection<Descriptor> getSortedDescriptorsForGlobalConfig() { return getSortedDescriptorsForGlobalConfig(Predicates.<GlobalConfigurationCategory>alwaysTrue()); } /** * @deprecated This is rather meaningless. */ @Deprecated public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigNoSecurity() { return getSortedDescriptorsForGlobalConfig(Predicates.not(GlobalSecurityConfiguration.FILTER)); } /** * Like {@link #getSortedDescriptorsForGlobalConfig(Predicate)} but for unclassified descriptors only. * @since 1.506 */ public static Collection<Descriptor> getSortedDescriptorsForGlobalConfigUnclassified() { return getSortedDescriptorsForGlobalConfig(new Predicate<GlobalConfigurationCategory>() { public boolean apply(GlobalConfigurationCategory cat) { return cat instanceof GlobalConfigurationCategory.Unclassified; } }); } private static class Tag implements Comparable<Tag> { double ordinal; String hierarchy; Descriptor d; Tag(double ordinal, Descriptor d) { this.ordinal = ordinal; this.d = d; this.hierarchy = buildSuperclassHierarchy(d.clazz, new StringBuilder()).toString(); } private StringBuilder buildSuperclassHierarchy(Class c, StringBuilder buf) { Class sc = c.getSuperclass(); if (sc!=null) buildSuperclassHierarchy(sc,buf).append(':'); return buf.append(c.getName()); } public int compareTo(Tag that) { int r = Double.compare(this.ordinal, that.ordinal); if (r!=0) return -r; // descending for ordinal return this.hierarchy.compareTo(that.hierarchy); } } /** * Computes the path to the icon of the given action * from the context path. */ public static String getIconFilePath(Action a) { String name = a.getIconFileName(); if (name==null) return null; if (name.startsWith("/")) return name.substring(1); else return "images/24x24/"+name; } /** * Works like JSTL build-in size(x) function, * but handle null gracefully. */ public static int size2(Object o) throws Exception { if(o==null) return 0; return ASTSizeFunction.sizeOf(o,Introspector.getUberspect()); } /** * Computes the relative path from the current page to the given item. */ public static String getRelativeLinkTo(Item p) { Map<Object,String> ancestors = new HashMap<Object,String>(); View view=null; StaplerRequest request = Stapler.getCurrentRequest(); for( Ancestor a : request.getAncestors() ) { ancestors.put(a.getObject(),a.getRelativePath()); if(a.getObject() instanceof View) view = (View) a.getObject(); } String path = ancestors.get(p); if(path!=null) return path; Item i=p; String url = ""; while(true) { ItemGroup ig = i.getParent(); url = i.getShortUrl()+url; if(ig== Jenkins.getInstance()) { assert i instanceof TopLevelItem; if(view!=null && view.contains((TopLevelItem)i)) { // if p and the current page belongs to the same view, then return a relative path return ancestors.get(view)+'/'+url; } else { // otherwise return a path from the root Hudson return request.getContextPath()+'/'+p.getUrl(); } } path = ancestors.get(ig); if(path!=null) return path+'/'+url; assert ig instanceof Item; // if not, ig must have been the Hudson instance i = (Item) ig; } } public static Map<Thread,StackTraceElement[]> dumpAllThreads() { Map<Thread,StackTraceElement[]> sorted = new TreeMap<Thread,StackTraceElement[]>(new ThreadSorter()); sorted.putAll(Thread.getAllStackTraces()); return sorted; } @IgnoreJRERequirement public static ThreadInfo[] getThreadInfos() { ThreadMXBean mbean = ManagementFactory.getThreadMXBean(); return mbean.dumpAllThreads(mbean.isObjectMonitorUsageSupported(),mbean.isSynchronizerUsageSupported()); } public static ThreadGroupMap sortThreadsAndGetGroupMap(ThreadInfo[] list) { ThreadGroupMap sorter = new ThreadGroupMap(); Arrays.sort(list, sorter); return sorter; } // Common code for sorting Threads/ThreadInfos by ThreadGroup private static class ThreadSorterBase { protected Map<Long,String> map = new HashMap<Long,String>(); private ThreadSorterBase() { ThreadGroup tg = Thread.currentThread().getThreadGroup(); while (tg.getParent() != null) tg = tg.getParent(); Thread[] threads = new Thread[tg.activeCount()*2]; int threadsLen = tg.enumerate(threads, true); for (int i = 0; i < threadsLen; i++) map.put(threads[i].getId(), threads[i].getThreadGroup().getName()); } protected int compare(long idA, long idB) { String tga = map.get(idA), tgb = map.get(idB); int result = (tga!=null?-1:0) + (tgb!=null?1:0); // Will be non-zero if only one is null if (result==0 && tga!=null) result = tga.compareToIgnoreCase(tgb); return result; } } public static class ThreadGroupMap extends ThreadSorterBase implements Comparator<ThreadInfo> { /** * @return ThreadGroup name or null if unknown */ public String getThreadGroup(ThreadInfo ti) { return map.get(ti.getThreadId()); } public int compare(ThreadInfo a, ThreadInfo b) { int result = compare(a.getThreadId(), b.getThreadId()); if (result == 0) result = a.getThreadName().compareToIgnoreCase(b.getThreadName()); return result; } } private static class ThreadSorter extends ThreadSorterBase implements Comparator<Thread> { public int compare(Thread a, Thread b) { int result = compare(a.getId(), b.getId()); if (result == 0) result = a.getName().compareToIgnoreCase(b.getName()); return result; } } /** * Are we running on JRE6 or above? */ @IgnoreJRERequirement public static boolean isMustangOrAbove() { try { System.console(); return true; } catch(LinkageError e) { return false; } } // ThreadInfo.toString() truncates the stack trace by first 8, so needed my own version @IgnoreJRERequirement public static String dumpThreadInfo(ThreadInfo ti, ThreadGroupMap map) { String grp = map.getThreadGroup(ti); StringBuilder sb = new StringBuilder("\"" + ti.getThreadName() + "\"" + " Id=" + ti.getThreadId() + " Group=" + (grp != null ? grp : "?") + " " + ti.getThreadState()); if (ti.getLockName() != null) { sb.append(" on " + ti.getLockName()); } if (ti.getLockOwnerName() != null) { sb.append(" owned by \"" + ti.getLockOwnerName() + "\" Id=" + ti.getLockOwnerId()); } if (ti.isSuspended()) { sb.append(" (suspended)"); } if (ti.isInNative()) { sb.append(" (in native)"); } sb.append('\n'); StackTraceElement[] stackTrace = ti.getStackTrace(); for (int i=0; i < stackTrace.length; i++) { StackTraceElement ste = stackTrace[i]; sb.append("\tat " + ste.toString()); sb.append('\n'); if (i == 0 && ti.getLockInfo() != null) { Thread.State ts = ti.getThreadState(); switch (ts) { case BLOCKED: sb.append("\t- blocked on " + ti.getLockInfo()); sb.append('\n'); break; case WAITING: sb.append("\t- waiting on " + ti.getLockInfo()); sb.append('\n'); break; case TIMED_WAITING: sb.append("\t- waiting on " + ti.getLockInfo()); sb.append('\n'); break; default: } } for (MonitorInfo mi : ti.getLockedMonitors()) { if (mi.getLockedStackDepth() == i) { sb.append("\t- locked " + mi); sb.append('\n'); } } } LockInfo[] locks = ti.getLockedSynchronizers(); if (locks.length > 0) { sb.append("\n\tNumber of locked synchronizers = " + locks.length); sb.append('\n'); for (LockInfo li : locks) { sb.append("\t- " + li); sb.append('\n'); } } sb.append('\n'); return sb.toString(); } public static <T> Collection<T> emptyList() { return Collections.emptyList(); } public static String jsStringEscape(String s) { StringBuilder buf = new StringBuilder(); for( int i=0; i<s.length(); i++ ) { char ch = s.charAt(i); switch(ch) { case '\'': buf.append("\\'"); break; case '\\': buf.append("\\\\"); break; case '"': buf.append("\\\""); break; default: buf.append(ch); } } return buf.toString(); } /** * Converts "abc" to "Abc". */ public static String capitalize(String s) { if(s==null || s.length()==0) return s; return Character.toUpperCase(s.charAt(0))+s.substring(1); } public static String getVersion() { return Jenkins.VERSION; } /** * Resoruce path prefix. */ public static String getResourcePath() { return Jenkins.RESOURCE_PATH; } public static String getViewResource(Object it, String path) { Class clazz = it.getClass(); if(it instanceof Class) clazz = (Class)it; if(it instanceof Descriptor) clazz = ((Descriptor)it).clazz; StringBuilder buf = new StringBuilder(Stapler.getCurrentRequest().getContextPath()); buf.append(Jenkins.VIEW_RESOURCE_PATH).append('/'); buf.append(clazz.getName().replace('.','/').replace('$','/')); buf.append('/').append(path); return buf.toString(); } public static boolean hasView(Object it, String path) throws IOException { if(it==null) return false; return Stapler.getCurrentRequest().getView(it,path)!=null; } /** * Can be used to check a checkbox by default. * Used from views like {@code h.defaultToTrue(scm.useUpdate)}. * The expression will evaluate to true if scm is null. */ public static boolean defaultToTrue(Boolean b) { if(b==null) return true; return b; } /** * If the value exists, return that value. Otherwise return the default value. * <p> * Starting 1.294, JEXL supports the elvis operator "x?:y" that supercedes this. * * @since 1.150 */ public static <T> T defaulted(T value, T defaultValue) { return value!=null ? value : defaultValue; } public static String printThrowable(Throwable t) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); return sw.toString(); } /** * Counts the number of rows needed for textarea to fit the content. * Minimum 5 rows. */ public static int determineRows(String s) { if(s==null) return 5; return Math.max(5,LINE_END.split(s).length); } /** * Converts the Hudson build status to CruiseControl build status, * which is either Success, Failure, Exception, or Unknown. */ public static String toCCStatus(Item i) { if (i instanceof Job) { Job j = (Job) i; switch (j.getIconColor().noAnime()) { case ABORTED: case RED: case YELLOW: return "Failure"; case BLUE: return "Success"; case DISABLED: case GREY: return "Unknown"; } } return "Unknown"; } private static final Pattern LINE_END = Pattern.compile("\r?\n"); /** * Checks if the current user is anonymous. */ public static boolean isAnonymous() { return Jenkins.getAuthentication() instanceof AnonymousAuthenticationToken; } /** * When called from within JEXL expression evaluation, * this method returns the current {@link JellyContext} used * to evaluate the script. * * @since 1.164 */ public static JellyContext getCurrentJellyContext() { JellyContext context = ExpressionFactory2.CURRENT_CONTEXT.get(); assert context!=null; return context; } /** * Evaluate a Jelly script and return output as a String. * * @since 1.267 */ public static String runScript(Script script) throws JellyTagException { StringWriter out = new StringWriter(); script.run(getCurrentJellyContext(), XMLOutput.createXMLOutput(out)); return out.toString(); } /** * Returns a sub-list if the given list is bigger than the specified 'maxSize' */ public static <T> List<T> subList(List<T> base, int maxSize) { if(maxSize<base.size()) return base.subList(0,maxSize); else return base; } /** * Combine path components via '/' while handling leading/trailing '/' to avoid duplicates. */ public static String joinPath(String... components) { StringBuilder buf = new StringBuilder(); for (String s : components) { if (s.length()==0) continue; if (buf.length()>0) { if (buf.charAt(buf.length()-1)!='/') buf.append('/'); if (s.charAt(0)=='/') s=s.substring(1); } buf.append(s); } return buf.toString(); } /** * Computes the hyperlink to actions, to handle the situation when the {@link Action#getUrlName()} * returns absolute URL. */ public static String getActionUrl(String itUrl,Action action) { String urlName = action.getUrlName(); if(urlName==null) return null; // to avoid NPE and fail to render the whole page try { if (new URI(urlName).isAbsolute()) { return urlName; } } catch (URISyntaxException x) { Logger.getLogger(Functions.class.getName()).log(Level.WARNING, "Failed to parse URL for {0}: {1}", new Object[] {action, x}); return null; } if(urlName.startsWith("/")) return joinPath(Stapler.getCurrentRequest().getContextPath(),urlName); else // relative URL name return joinPath(Stapler.getCurrentRequest().getContextPath()+'/'+itUrl,urlName); } /** * Escapes the character unsafe for e-mail address. * See http://en.wikipedia.org/wiki/E-mail_address for the details, * but here the vocabulary is even more restricted. */ public static String toEmailSafeString(String projectName) { // TODO: escape non-ASCII characters StringBuilder buf = new StringBuilder(projectName.length()); for( int i=0; i<projectName.length(); i++ ) { char ch = projectName.charAt(i); if(('a'<=ch && ch<='z') || ('z'<=ch && ch<='Z') || ('0'<=ch && ch<='9') || "-_.".indexOf(ch)>=0) buf.append(ch); else buf.append('_'); // escape } return projectName; } public String getSystemProperty(String key) { return System.getProperty(key); } /** * Obtains the host name of the Hudson server that clients can use to talk back to. * <p> * This is primarily used in <tt>slave-agent.jnlp.jelly</tt> to specify the destination * that the slaves talk to. */ public String getServerName() { // Try to infer this from the configured root URL. // This makes it work correctly when Hudson runs behind a reverse proxy. String url = Jenkins.getInstance().getRootUrl(); try { if(url!=null) { String host = new URL(url).getHost(); if(host!=null) return host; } } catch (MalformedURLException e) { // fall back to HTTP request } return Stapler.getCurrentRequest().getServerName(); } /** * Determines the form validation check URL. See textbox.jelly */ public String getCheckUrl(String userDefined, Object descriptor, String field) { if(userDefined!=null || field==null) return userDefined; if (descriptor instanceof Descriptor) { Descriptor d = (Descriptor) descriptor; return d.getCheckUrl(field); } return null; } /** * If the given href link is matching the current page, return true. * * Used in <tt>task.jelly</tt> to decide if the page should be highlighted. */ public boolean hyperlinkMatchesCurrentPage(String href) throws UnsupportedEncodingException { String url = Stapler.getCurrentRequest().getRequestURL().toString(); if (href == null || href.length() <= 1) return ".".equals(href) && url.endsWith("/"); url = URLDecoder.decode(url,"UTF-8"); href = URLDecoder.decode(href,"UTF-8"); if (url.endsWith("/")) url = url.substring(0, url.length() - 1); if (href.endsWith("/")) href = href.substring(0, href.length() - 1); return url.endsWith(href); } public <T> List<T> singletonList(T t) { return Collections.singletonList(t); } /** * Gets all the {@link PageDecorator}s. */ public static List<PageDecorator> getPageDecorators() { // this method may be called to render start up errors, at which point Hudson doesn't exist yet. see HUDSON-3608 if(Jenkins.getInstance()==null) return Collections.emptyList(); return PageDecorator.all(); } public static List<Descriptor<Cloud>> getCloudDescriptors() { return Cloud.all(); } /** * Prepend a prefix only when there's the specified body. */ public String prepend(String prefix, String body) { if(body!=null && body.length()>0) return prefix+body; return body; } public static List<Descriptor<CrumbIssuer>> getCrumbIssuerDescriptors() { return CrumbIssuer.all(); } public static String getCrumb(StaplerRequest req) { Jenkins h = Jenkins.getInstance(); CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null; return issuer != null ? issuer.getCrumb(req) : ""; } public static String getCrumbRequestField() { Jenkins h = Jenkins.getInstance(); CrumbIssuer issuer = h != null ? h.getCrumbIssuer() : null; return issuer != null ? issuer.getDescriptor().getCrumbRequestField() : ""; } public static Date getCurrentTime() { return new Date(); } public static Locale getCurrentLocale() { Locale locale=null; StaplerRequest req = Stapler.getCurrentRequest(); if(req!=null) locale = req.getLocale(); if(locale==null) locale = Locale.getDefault(); return locale; } /** * Generate a series of &lt;script> tags to include <tt>script.js</tt> * from {@link ConsoleAnnotatorFactory}s and {@link ConsoleAnnotationDescriptor}s. */ public static String generateConsoleAnnotationScriptAndStylesheet() { String cp = Stapler.getCurrentRequest().getContextPath(); StringBuilder buf = new StringBuilder(); for (ConsoleAnnotatorFactory f : ConsoleAnnotatorFactory.all()) { String path = cp + "/extensionList/" + ConsoleAnnotatorFactory.class.getName() + "/" + f.getClass().getName(); if (f.hasScript()) buf.append("<script src='"+path+"/script.js'></script>"); if (f.hasStylesheet()) buf.append("<link rel='stylesheet' type='text/css' href='"+path+"/style.css' />"); } for (ConsoleAnnotationDescriptor d : ConsoleAnnotationDescriptor.all()) { String path = cp+"/descriptor/"+d.clazz.getName(); if (d.hasScript()) buf.append("<script src='"+path+"/script.js'></script>"); if (d.hasStylesheet()) buf.append("<link rel='stylesheet' type='text/css' href='"+path+"/style.css' />"); } return buf.toString(); } /** * Work around for bug 6935026. */ public List<String> getLoggerNames() { while (true) { try { List<String> r = new ArrayList<String>(); Enumeration<String> e = LogManager.getLogManager().getLoggerNames(); while (e.hasMoreElements()) r.add(e.nextElement()); return r; } catch (ConcurrentModificationException e) { // retry } } } /** * Used by &lt;f:password/> so that we send an encrypted value to the client. */ public String getPasswordValue(Object o) { if (o==null) return null; if (o instanceof Secret) return ((Secret)o).getEncryptedValue(); return o.toString(); } public List filterDescriptors(Object context, Iterable descriptors) { return DescriptorVisibilityFilter.apply(context,descriptors); } /** * Returns true if we are running unit tests. */ public static boolean getIsUnitTest() { return Main.isUnitTest; } /** * Returns {@code true} if the {@link Run#ARTIFACTS} permission is enabled, * {@code false} otherwise. * * <p>When the {@link Run#ARTIFACTS} permission is not turned on using the * {@code hudson.security.ArtifactsPermission} system property, this * permission must not be considered to be set to {@code false} for every * user. It must rather be like if the permission doesn't exist at all * (which means that every user has to have an access to the artifacts but * the permission can't be configured in the security screen). Got it?</p> */ public static boolean isArtifactsPermissionEnabled() { return Boolean.getBoolean("hudson.security.ArtifactsPermission"); } /** * Returns {@code true} if the {@link Item#WIPEOUT} permission is enabled, * {@code false} otherwise. * * <p>The "Wipe Out Workspace" action available on jobs is controlled by the * {@link Item#BUILD} permission. For some specific projects, however, it is * not acceptable to let users have this possibility, even it they can * trigger builds. As such, when enabling the {@code hudson.security.WipeOutPermission} * system property, a new "WipeOut" permission will allow to have greater * control on the "Wipe Out Workspace" action.</p> */ public static boolean isWipeOutPermissionEnabled() { return Boolean.getBoolean("hudson.security.WipeOutPermission"); } public static String createRenderOnDemandProxy(JellyContext context, String attributesToCapture) { return Stapler.getCurrentRequest().createJavaScriptProxy(new RenderOnDemandClosure(context,attributesToCapture)); } public static String getCurrentDescriptorByNameUrl() { return Descriptor.getCurrentDescriptorByNameUrl(); } public static String setCurrentDescriptorByNameUrl(String value) { String o = getCurrentDescriptorByNameUrl(); Stapler.getCurrentRequest().setAttribute("currentDescriptorByNameUrl", value); return o; } public static void restoreCurrentDescriptorByNameUrl(String old) { Stapler.getCurrentRequest().setAttribute("currentDescriptorByNameUrl", old); } public static List<String> getRequestHeaders(String name) { List<String> r = new ArrayList<String>(); Enumeration e = Stapler.getCurrentRequest().getHeaders(name); while (e.hasMoreElements()) { r.add(e.nextElement().toString()); } return r; } /** * Used for arguments to internationalized expressions to avoid escape */ public static Object rawHtml(Object o) { return o==null ? null : new RawHtmlArgument(o); } public static ArrayList<CLICommand> getCLICommands() { ArrayList<CLICommand> all = new ArrayList<CLICommand>(CLICommand.all()); Collections.sort(all, new Comparator<CLICommand>() { public int compare(CLICommand cliCommand, CLICommand cliCommand1) { return cliCommand.getName().compareTo(cliCommand1.getName()); } }); return all; } /** * Returns an avatar image URL for the specified user and preferred image size * @param user the user * @param avatarSize the preferred size of the avatar image * @return a URL string * @since 1.433 */ public static String getAvatar(User user, String avatarSize) { return UserAvatarResolver.resolve(user, avatarSize); } /** * @deprecated as of 1.451 * Use {@link #getAvatar} */ public String getUserAvatar(User user, String avatarSize) { return getAvatar(user,avatarSize); } /** * Returns human readable information about file size * * @param file size in bytes * @return file size in appropriate unit */ public static String humanReadableByteSize(long size){ String measure = "B"; if(size < 1024){ return size + " " + measure; } Double number = new Double(size); if(number>=1024){ number = number/1024; measure = "KB"; if(number>=1024){ number = number/1024; measure = "MB"; if(number>=1024){ number=number/1024; measure = "GB"; } } } DecimalFormat format = new DecimalFormat("#0.00"); return format.format(number) + " " + measure; } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_2093_0
crossvul-java_data_bad_4761_0
package org.bouncycastle.jcajce.provider.asymmetric; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jcajce.provider.asymmetric.dh.KeyFactorySpi; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.util.AsymmetricAlgorithmProvider; public class DH { private static final String PREFIX = "org.bouncycastle.jcajce.provider.asymmetric" + ".dh."; public static class Mappings extends AsymmetricAlgorithmProvider { public Mappings() { } public void configure(ConfigurableProvider provider) { provider.addAlgorithm("KeyPairGenerator.DH", PREFIX + "KeyPairGeneratorSpi"); provider.addAlgorithm("Alg.Alias.KeyPairGenerator.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("KeyAgreement.DH", PREFIX + "KeyAgreementSpi"); provider.addAlgorithm("Alg.Alias.KeyAgreement.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("KeyAgreement", PKCSObjectIdentifiers.id_alg_ESDH, PREFIX + "KeyAgreementSpi$DHwithRFC2631KDF"); provider.addAlgorithm("KeyAgreement", PKCSObjectIdentifiers.id_alg_SSDH, PREFIX + "KeyAgreementSpi$DHwithRFC2631KDF"); provider.addAlgorithm("KeyFactory.DH", PREFIX + "KeyFactorySpi"); provider.addAlgorithm("Alg.Alias.KeyFactory.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("AlgorithmParameters.DH", PREFIX + "AlgorithmParametersSpi"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator.DIFFIEHELLMAN", "DH"); provider.addAlgorithm("AlgorithmParameterGenerator.DH", PREFIX + "AlgorithmParameterGeneratorSpi"); provider.addAlgorithm("Cipher.IES", PREFIX + "IESCipher$IES"); provider.addAlgorithm("Cipher.IESwithAES", PREFIX + "IESCipher$IESwithAES"); provider.addAlgorithm("Cipher.IESWITHAES", PREFIX + "IESCipher$IESwithAES"); provider.addAlgorithm("Cipher.IESWITHDESEDE", PREFIX + "IESCipher$IESwithDESede"); provider.addAlgorithm("Cipher.DHIES", PREFIX + "IESCipher$IES"); provider.addAlgorithm("Cipher.DHIESwithAES", PREFIX + "IESCipher$IESwithAES"); provider.addAlgorithm("Cipher.DHIESWITHAES", PREFIX + "IESCipher$IESwithAES"); provider.addAlgorithm("Cipher.DHIESWITHDESEDE", PREFIX + "IESCipher$IESwithDESede"); provider.addAlgorithm("Cipher.OLDDHIES", PREFIX + "IESCipher$OldIES"); provider.addAlgorithm("Cipher.OLDDHIESwithAES", PREFIX + "IESCipher$OldIESwithAES"); provider.addAlgorithm("Cipher.OLDDHIESWITHAES", PREFIX + "IESCipher$OldIESwithAES"); provider.addAlgorithm("Cipher.OLDDHIESWITHDESEDE", PREFIX + "IESCipher$OldIESwithDESede"); registerOid(provider, PKCSObjectIdentifiers.dhKeyAgreement, "DH", new KeyFactorySpi()); registerOid(provider, X9ObjectIdentifiers.dhpublicnumber, "DH", new KeyFactorySpi()); } } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_4761_0
crossvul-java_data_good_4756_2
package org.bouncycastle.jcajce.provider.symmetric; import java.io.IOException; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.SecureRandom; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidParameterSpecException; import javax.crypto.spec.IvParameterSpec; import org.bouncycastle.asn1.bc.BCObjectIdentifiers; import org.bouncycastle.asn1.cms.CCMParameters; import org.bouncycastle.asn1.cms.GCMParameters; import org.bouncycastle.asn1.nist.NISTObjectIdentifiers; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.BufferedBlockCipher; import org.bouncycastle.crypto.CipherKeyGenerator; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.engines.AESEngine; import org.bouncycastle.crypto.engines.AESWrapEngine; import org.bouncycastle.crypto.engines.RFC3211WrapEngine; import org.bouncycastle.crypto.engines.RFC5649WrapEngine; import org.bouncycastle.crypto.generators.Poly1305KeyGenerator; import org.bouncycastle.crypto.macs.CMac; import org.bouncycastle.crypto.macs.GMac; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.modes.CCMBlockCipher; import org.bouncycastle.crypto.modes.CFBBlockCipher; import org.bouncycastle.crypto.modes.GCMBlockCipher; import org.bouncycastle.crypto.modes.OFBBlockCipher; import org.bouncycastle.jcajce.provider.config.ConfigurableProvider; import org.bouncycastle.jcajce.provider.symmetric.util.BaseAlgorithmParameterGenerator; import org.bouncycastle.jcajce.provider.symmetric.util.BaseAlgorithmParameters; import org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher; import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator; import org.bouncycastle.jcajce.provider.symmetric.util.BaseMac; import org.bouncycastle.jcajce.provider.symmetric.util.BaseWrapCipher; import org.bouncycastle.jcajce.provider.symmetric.util.BlockCipherProvider; import org.bouncycastle.jcajce.provider.symmetric.util.IvAlgorithmParameters; import org.bouncycastle.jcajce.provider.symmetric.util.PBESecretKeyFactory; import org.bouncycastle.jcajce.spec.AEADParameterSpec; public final class AES { private static final Class gcmSpecClass = lookup("javax.crypto.spec.GCMParameterSpec"); private AES() { } public static class ECB extends BaseBlockCipher { public ECB() { super(new BlockCipherProvider() { public BlockCipher get() { return new AESEngine(); } }); } } public static class CBC extends BaseBlockCipher { public CBC() { super(new CBCBlockCipher(new AESEngine()), 128); } } static public class CFB extends BaseBlockCipher { public CFB() { super(new BufferedBlockCipher(new CFBBlockCipher(new AESEngine(), 128)), 128); } } static public class OFB extends BaseBlockCipher { public OFB() { super(new BufferedBlockCipher(new OFBBlockCipher(new AESEngine(), 128)), 128); } } static public class GCM extends BaseBlockCipher { public GCM() { super(new GCMBlockCipher(new AESEngine())); } } static public class CCM extends BaseBlockCipher { public CCM() { super(new CCMBlockCipher(new AESEngine()), false, 16); } } public static class AESCMAC extends BaseMac { public AESCMAC() { super(new CMac(new AESEngine())); } } public static class AESGMAC extends BaseMac { public AESGMAC() { super(new GMac(new GCMBlockCipher(new AESEngine()))); } } public static class AESCCMMAC extends BaseMac { public AESCCMMAC() { super(new CCMMac()); } private static class CCMMac implements Mac { private final CCMBlockCipher ccm = new CCMBlockCipher(new AESEngine()); private int macLength = 8; public void init(CipherParameters params) throws IllegalArgumentException { ccm.init(true, params); this.macLength = ccm.getMac().length; } public String getAlgorithmName() { return ccm.getAlgorithmName() + "Mac"; } public int getMacSize() { return macLength; } public void update(byte in) throws IllegalStateException { ccm.processAADByte(in); } public void update(byte[] in, int inOff, int len) throws DataLengthException, IllegalStateException { ccm.processAADBytes(in, inOff, len); } public int doFinal(byte[] out, int outOff) throws DataLengthException, IllegalStateException { try { return ccm.doFinal(out, 0); } catch (InvalidCipherTextException e) { throw new IllegalStateException("exception on doFinal(): " + e.toString()); } } public void reset() { ccm.reset(); } } } public static class Poly1305 extends BaseMac { public Poly1305() { super(new org.bouncycastle.crypto.macs.Poly1305(new AESEngine())); } } public static class Poly1305KeyGen extends BaseKeyGenerator { public Poly1305KeyGen() { super("Poly1305-AES", 256, new Poly1305KeyGenerator()); } } static public class Wrap extends BaseWrapCipher { public Wrap() { super(new AESWrapEngine()); } } public static class RFC3211Wrap extends BaseWrapCipher { public RFC3211Wrap() { super(new RFC3211WrapEngine(new AESEngine()), 16); } } public static class RFC5649Wrap extends BaseWrapCipher { public RFC5649Wrap() { super(new RFC5649WrapEngine(new AESEngine())); } } /** * PBEWithAES-CBC */ static public class PBEWithAESCBC extends BaseBlockCipher { public PBEWithAESCBC() { super(new CBCBlockCipher(new AESEngine())); } } /** * PBEWithSHA1AES-CBC */ static public class PBEWithSHA1AESCBC128 extends BaseBlockCipher { public PBEWithSHA1AESCBC128() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 128, 16); } } static public class PBEWithSHA1AESCBC192 extends BaseBlockCipher { public PBEWithSHA1AESCBC192() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 192, 16); } } static public class PBEWithSHA1AESCBC256 extends BaseBlockCipher { public PBEWithSHA1AESCBC256() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA1, 256, 16); } } /** * PBEWithSHA256AES-CBC */ static public class PBEWithSHA256AESCBC128 extends BaseBlockCipher { public PBEWithSHA256AESCBC128() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 128, 16); } } static public class PBEWithSHA256AESCBC192 extends BaseBlockCipher { public PBEWithSHA256AESCBC192() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 192, 16); } } static public class PBEWithSHA256AESCBC256 extends BaseBlockCipher { public PBEWithSHA256AESCBC256() { super(new CBCBlockCipher(new AESEngine()), PKCS12, SHA256, 256, 16); } } public static class KeyGen extends BaseKeyGenerator { public KeyGen() { this(192); } public KeyGen(int keySize) { super("AES", keySize, new CipherKeyGenerator()); } } public static class KeyGen128 extends KeyGen { public KeyGen128() { super(128); } } public static class KeyGen192 extends KeyGen { public KeyGen192() { super(192); } } public static class KeyGen256 extends KeyGen { public KeyGen256() { super(256); } } /** * PBEWithSHA1And128BitAES-BC */ static public class PBEWithSHAAnd128BitAESBC extends PBESecretKeyFactory { public PBEWithSHAAnd128BitAESBC() { super("PBEWithSHA1And128BitAES-CBC-BC", null, true, PKCS12, SHA1, 128, 128); } } /** * PBEWithSHA1And192BitAES-BC */ static public class PBEWithSHAAnd192BitAESBC extends PBESecretKeyFactory { public PBEWithSHAAnd192BitAESBC() { super("PBEWithSHA1And192BitAES-CBC-BC", null, true, PKCS12, SHA1, 192, 128); } } /** * PBEWithSHA1And256BitAES-BC */ static public class PBEWithSHAAnd256BitAESBC extends PBESecretKeyFactory { public PBEWithSHAAnd256BitAESBC() { super("PBEWithSHA1And256BitAES-CBC-BC", null, true, PKCS12, SHA1, 256, 128); } } /** * PBEWithSHA256And128BitAES-BC */ static public class PBEWithSHA256And128BitAESBC extends PBESecretKeyFactory { public PBEWithSHA256And128BitAESBC() { super("PBEWithSHA256And128BitAES-CBC-BC", null, true, PKCS12, SHA256, 128, 128); } } /** * PBEWithSHA256And192BitAES-BC */ static public class PBEWithSHA256And192BitAESBC extends PBESecretKeyFactory { public PBEWithSHA256And192BitAESBC() { super("PBEWithSHA256And192BitAES-CBC-BC", null, true, PKCS12, SHA256, 192, 128); } } /** * PBEWithSHA256And256BitAES-BC */ static public class PBEWithSHA256And256BitAESBC extends PBESecretKeyFactory { public PBEWithSHA256And256BitAESBC() { super("PBEWithSHA256And256BitAES-CBC-BC", null, true, PKCS12, SHA256, 256, 128); } } /** * PBEWithMD5And128BitAES-OpenSSL */ static public class PBEWithMD5And128BitAESCBCOpenSSL extends PBESecretKeyFactory { public PBEWithMD5And128BitAESCBCOpenSSL() { super("PBEWithMD5And128BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 128, 128); } } /** * PBEWithMD5And192BitAES-OpenSSL */ static public class PBEWithMD5And192BitAESCBCOpenSSL extends PBESecretKeyFactory { public PBEWithMD5And192BitAESCBCOpenSSL() { super("PBEWithMD5And192BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 192, 128); } } /** * PBEWithMD5And256BitAES-OpenSSL */ static public class PBEWithMD5And256BitAESCBCOpenSSL extends PBESecretKeyFactory { public PBEWithMD5And256BitAESCBCOpenSSL() { super("PBEWithMD5And256BitAES-CBC-OpenSSL", null, true, OPENSSL, MD5, 256, 128); } } public static class AlgParamGen extends BaseAlgorithmParameterGenerator { protected void engineInit( AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for AES parameter generation."); } protected AlgorithmParameters engineGenerateParameters() { byte[] iv = new byte[16]; if (random == null) { random = new SecureRandom(); } random.nextBytes(iv); AlgorithmParameters params; try { params = createParametersInstance("AES"); params.init(new IvParameterSpec(iv)); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; } } public static class AlgParamGenCCM extends BaseAlgorithmParameterGenerator { protected void engineInit( AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { // TODO: add support for GCMParameterSpec as a template. throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for AES parameter generation."); } protected AlgorithmParameters engineGenerateParameters() { byte[] iv = new byte[12]; if (random == null) { random = new SecureRandom(); } random.nextBytes(iv); AlgorithmParameters params; try { params = createParametersInstance("CCM"); params.init(new CCMParameters(iv, 12).getEncoded()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; } } public static class AlgParamGenGCM extends BaseAlgorithmParameterGenerator { protected void engineInit( AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { // TODO: add support for GCMParameterSpec as a template. throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for AES parameter generation."); } protected AlgorithmParameters engineGenerateParameters() { byte[] nonce = new byte[12]; if (random == null) { random = new SecureRandom(); } random.nextBytes(nonce); AlgorithmParameters params; try { params = createParametersInstance("GCM"); params.init(new GCMParameters(nonce, 16).getEncoded()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; } } public static class AlgParams extends IvAlgorithmParameters { protected String engineToString() { return "AES IV"; } } public static class AlgParamsGCM extends BaseAlgorithmParameters { private GCMParameters gcmParams; protected void engineInit(AlgorithmParameterSpec paramSpec) throws InvalidParameterSpecException { if (GcmSpecUtil.isGcmSpec(paramSpec)) { gcmParams = GcmSpecUtil.extractGcmParameters(paramSpec); } else if (paramSpec instanceof AEADParameterSpec) { gcmParams = new GCMParameters(((AEADParameterSpec)paramSpec).getNonce(), ((AEADParameterSpec)paramSpec).getMacSizeInBits() / 8); } else { throw new InvalidParameterSpecException("AlgorithmParameterSpec class not recognized: " + paramSpec.getClass().getName()); } } protected void engineInit(byte[] params) throws IOException { gcmParams = GCMParameters.getInstance(params); } protected void engineInit(byte[] params, String format) throws IOException { if (!isASN1FormatString(format)) { throw new IOException("unknown format specified"); } gcmParams = GCMParameters.getInstance(params); } protected byte[] engineGetEncoded() throws IOException { return gcmParams.getEncoded(); } protected byte[] engineGetEncoded(String format) throws IOException { if (!isASN1FormatString(format)) { throw new IOException("unknown format specified"); } return gcmParams.getEncoded(); } protected String engineToString() { return "GCM"; } protected AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec) throws InvalidParameterSpecException { if (paramSpec == AlgorithmParameterSpec.class || GcmSpecUtil.isGcmSpec(paramSpec)) { if (GcmSpecUtil.gcmSpecExists()) { return GcmSpecUtil.extractGcmSpec(gcmParams.toASN1Primitive()); } return new AEADParameterSpec(gcmParams.getNonce(), gcmParams.getIcvLen() * 8); } if (paramSpec == AEADParameterSpec.class) { return new AEADParameterSpec(gcmParams.getNonce(), gcmParams.getIcvLen() * 8); } if (paramSpec == IvParameterSpec.class) { return new IvParameterSpec(gcmParams.getNonce()); } throw new InvalidParameterSpecException("AlgorithmParameterSpec not recognized: " + paramSpec.getName()); } } public static class AlgParamsCCM extends BaseAlgorithmParameters { private CCMParameters ccmParams; protected void engineInit(AlgorithmParameterSpec paramSpec) throws InvalidParameterSpecException { if (GcmSpecUtil.isGcmSpec(paramSpec)) { ccmParams = CCMParameters.getInstance(GcmSpecUtil.extractGcmParameters(paramSpec)); } else if (paramSpec instanceof AEADParameterSpec) { ccmParams = new CCMParameters(((AEADParameterSpec)paramSpec).getNonce(), ((AEADParameterSpec)paramSpec).getMacSizeInBits() / 8); } else { throw new InvalidParameterSpecException("AlgorithmParameterSpec class not recognized: " + paramSpec.getClass().getName()); } } protected void engineInit(byte[] params) throws IOException { ccmParams = CCMParameters.getInstance(params); } protected void engineInit(byte[] params, String format) throws IOException { if (!isASN1FormatString(format)) { throw new IOException("unknown format specified"); } ccmParams = CCMParameters.getInstance(params); } protected byte[] engineGetEncoded() throws IOException { return ccmParams.getEncoded(); } protected byte[] engineGetEncoded(String format) throws IOException { if (!isASN1FormatString(format)) { throw new IOException("unknown format specified"); } return ccmParams.getEncoded(); } protected String engineToString() { return "CCM"; } protected AlgorithmParameterSpec localEngineGetParameterSpec(Class paramSpec) throws InvalidParameterSpecException { if (paramSpec == AlgorithmParameterSpec.class || GcmSpecUtil.isGcmSpec(paramSpec)) { if (GcmSpecUtil.gcmSpecExists()) { return GcmSpecUtil.extractGcmSpec(ccmParams.toASN1Primitive()); } return new AEADParameterSpec(ccmParams.getNonce(), ccmParams.getIcvLen() * 8); } if (paramSpec == AEADParameterSpec.class) { return new AEADParameterSpec(ccmParams.getNonce(), ccmParams.getIcvLen() * 8); } if (paramSpec == IvParameterSpec.class) { return new IvParameterSpec(ccmParams.getNonce()); } throw new InvalidParameterSpecException("AlgorithmParameterSpec not recognized: " + paramSpec.getName()); } } public static class Mappings extends SymmetricAlgorithmProvider { private static final String PREFIX = AES.class.getName(); /** * These three got introduced in some messages as a result of a typo in an * early document. We don't produce anything using these OID values, but we'll * read them. */ private static final String wrongAES128 = "2.16.840.1.101.3.4.2"; private static final String wrongAES192 = "2.16.840.1.101.3.4.22"; private static final String wrongAES256 = "2.16.840.1.101.3.4.42"; public Mappings() { } public void configure(ConfigurableProvider provider) { provider.addAlgorithm("AlgorithmParameters.AES", PREFIX + "$AlgParams"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + wrongAES128, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + wrongAES192, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + wrongAES256, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes128_CBC, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes192_CBC, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes256_CBC, "AES"); provider.addAlgorithm("AlgorithmParameters.GCM", PREFIX + "$AlgParamsGCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes128_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes192_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes256_GCM, "GCM"); provider.addAlgorithm("AlgorithmParameters.CCM", PREFIX + "$AlgParamsCCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes128_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes192_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + NISTObjectIdentifiers.id_aes256_CCM, "CCM"); provider.addAlgorithm("AlgorithmParameterGenerator.AES", PREFIX + "$AlgParamGen"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + wrongAES128, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + wrongAES192, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + wrongAES256, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_CBC, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes192_CBC, "AES"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes256_CBC, "AES"); provider.addAlgorithm("Cipher.AES", PREFIX + "$ECB"); provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES128, "AES"); provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES192, "AES"); provider.addAlgorithm("Alg.Alias.Cipher." + wrongAES256, "AES"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_ECB, PREFIX + "$ECB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_ECB, PREFIX + "$ECB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_ECB, PREFIX + "$ECB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CBC, PREFIX + "$CBC"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CBC, PREFIX + "$CBC"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CBC, PREFIX + "$CBC"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_OFB, PREFIX + "$OFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_OFB, PREFIX + "$OFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_OFB, PREFIX + "$OFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes128_CFB, PREFIX + "$CFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes192_CFB, PREFIX + "$CFB"); provider.addAlgorithm("Cipher", NISTObjectIdentifiers.id_aes256_CFB, PREFIX + "$CFB"); provider.addAlgorithm("Cipher.AESWRAP", PREFIX + "$Wrap"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_wrap, "AESWRAP"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_wrap, "AESWRAP"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_wrap, "AESWRAP"); provider.addAlgorithm("Alg.Alias.Cipher.AESKW", "AESWRAP"); provider.addAlgorithm("Cipher.AESRFC3211WRAP", PREFIX + "$RFC3211Wrap"); provider.addAlgorithm("Cipher.AESRFC5649WRAP", PREFIX + "$RFC5649Wrap"); provider.addAlgorithm("AlgorithmParameterGenerator.CCM", PREFIX + "$AlgParamGenCCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes192_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes256_CCM, "CCM"); provider.addAlgorithm("Cipher.CCM", PREFIX + "$CCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_CCM, "CCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_CCM, "CCM"); provider.addAlgorithm("AlgorithmParameterGenerator.GCM", PREFIX + "$AlgParamGenGCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes128_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes192_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.AlgorithmParameterGenerator." + NISTObjectIdentifiers.id_aes256_GCM, "GCM"); provider.addAlgorithm("Cipher.GCM", PREFIX + "$GCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes128_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes192_GCM, "GCM"); provider.addAlgorithm("Alg.Alias.Cipher", NISTObjectIdentifiers.id_aes256_GCM, "GCM"); provider.addAlgorithm("KeyGenerator.AES", PREFIX + "$KeyGen"); provider.addAlgorithm("KeyGenerator." + wrongAES128, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator." + wrongAES192, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator." + wrongAES256, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_ECB, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_CBC, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_OFB, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_CFB, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_ECB, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_CBC, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_OFB, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_CFB, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_ECB, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_CBC, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_OFB, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_CFB, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator.AESWRAP", PREFIX + "$KeyGen"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_wrap, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_wrap, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_wrap, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_GCM, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_GCM, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_GCM, PREFIX + "$KeyGen256"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes128_CCM, PREFIX + "$KeyGen128"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes192_CCM, PREFIX + "$KeyGen192"); provider.addAlgorithm("KeyGenerator", NISTObjectIdentifiers.id_aes256_CCM, PREFIX + "$KeyGen256"); provider.addAlgorithm("Mac.AESCMAC", PREFIX + "$AESCMAC"); provider.addAlgorithm("Mac.AESCCMMAC", PREFIX + "$AESCCMMAC"); provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes128_CCM.getId(), "AESCCMMAC"); provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes192_CCM.getId(), "AESCCMMAC"); provider.addAlgorithm("Alg.Alias.Mac." + NISTObjectIdentifiers.id_aes256_CCM.getId(), "AESCCMMAC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc, "PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc, "PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc, "PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc, "PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc, "PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc, "PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Cipher.PBEWITHSHAAND128BITAES-CBC-BC", PREFIX + "$PBEWithSHA1AESCBC128"); provider.addAlgorithm("Cipher.PBEWITHSHAAND192BITAES-CBC-BC", PREFIX + "$PBEWithSHA1AESCBC192"); provider.addAlgorithm("Cipher.PBEWITHSHAAND256BITAES-CBC-BC", PREFIX + "$PBEWithSHA1AESCBC256"); provider.addAlgorithm("Cipher.PBEWITHSHA256AND128BITAES-CBC-BC", PREFIX + "$PBEWithSHA256AESCBC128"); provider.addAlgorithm("Cipher.PBEWITHSHA256AND192BITAES-CBC-BC", PREFIX + "$PBEWithSHA256AESCBC192"); provider.addAlgorithm("Cipher.PBEWITHSHA256AND256BITAES-CBC-BC", PREFIX + "$PBEWithSHA256AESCBC256"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHAAND128BITAES-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHAAND192BITAES-BC", "PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHAAND256BITAES-BC", "PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND128BITAES-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND192BITAES-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA1AND256BITAES-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND128BITAES-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND192BITAES-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-1AND256BITAES-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND128BITAES-CBC-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND192BITAES-CBC-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND256BITAES-CBC-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA256AND128BITAES-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA256AND192BITAES-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA256AND256BITAES-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND128BITAES-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND192BITAES-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.Cipher.PBEWITHSHA-256AND256BITAES-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Cipher.PBEWITHMD5AND128BITAES-CBC-OPENSSL", PREFIX + "$PBEWithAESCBC"); provider.addAlgorithm("Cipher.PBEWITHMD5AND192BITAES-CBC-OPENSSL", PREFIX + "$PBEWithAESCBC"); provider.addAlgorithm("Cipher.PBEWITHMD5AND256BITAES-CBC-OPENSSL", PREFIX + "$PBEWithAESCBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHMD5AND128BITAES-CBC-OPENSSL", PREFIX + "$PBEWithMD5And128BitAESCBCOpenSSL"); provider.addAlgorithm("SecretKeyFactory.PBEWITHMD5AND192BITAES-CBC-OPENSSL", PREFIX + "$PBEWithMD5And192BitAESCBCOpenSSL"); provider.addAlgorithm("SecretKeyFactory.PBEWITHMD5AND256BITAES-CBC-OPENSSL", PREFIX + "$PBEWithMD5And256BitAESCBCOpenSSL"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHAAND128BITAES-CBC-BC", PREFIX + "$PBEWithSHAAnd128BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHAAND192BITAES-CBC-BC", PREFIX + "$PBEWithSHAAnd192BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHAAND256BITAES-CBC-BC", PREFIX + "$PBEWithSHAAnd256BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHA256AND128BITAES-CBC-BC", PREFIX + "$PBEWithSHA256And128BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHA256AND192BITAES-CBC-BC", PREFIX + "$PBEWithSHA256And192BitAESBC"); provider.addAlgorithm("SecretKeyFactory.PBEWITHSHA256AND256BITAES-CBC-BC", PREFIX + "$PBEWithSHA256And256BitAESBC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-1AND128BITAES-CBC-BC","PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-1AND192BITAES-CBC-BC","PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-1AND256BITAES-CBC-BC","PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND128BITAES-CBC-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND192BITAES-CBC-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND256BITAES-CBC-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND128BITAES-BC","PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND192BITAES-BC","PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory.PBEWITHSHA-256AND256BITAES-BC","PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc, "PBEWITHSHAAND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc, "PBEWITHSHAAND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc, "PBEWITHSHAAND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc, "PBEWITHSHA256AND128BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc, "PBEWITHSHA256AND192BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.SecretKeyFactory", BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc, "PBEWITHSHA256AND256BITAES-CBC-BC"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHAAND128BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHAAND192BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHAAND256BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA256AND128BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA256AND192BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA256AND256BITAES-CBC-BC", "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA1AND128BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA1AND192BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA1AND256BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-1AND128BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-1AND192BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-1AND256BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-256AND128BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-256AND192BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters.PBEWITHSHA-256AND256BITAES-CBC-BC","PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes128_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes192_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha1_pkcs12_aes256_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes128_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes192_cbc.getId(), "PKCS12PBE"); provider.addAlgorithm("Alg.Alias.AlgorithmParameters." + BCObjectIdentifiers.bc_pbe_sha256_pkcs12_aes256_cbc.getId(), "PKCS12PBE"); addGMacAlgorithm(provider, "AES", PREFIX + "$AESGMAC", PREFIX + "$KeyGen128"); addPoly1305Algorithm(provider, "AES", PREFIX + "$Poly1305", PREFIX + "$Poly1305KeyGen"); } } private static Class lookup(String className) { try { Class def = AES.class.getClassLoader().loadClass(className); return def; } catch (Exception e) { return null; } } }
./CrossVul/dataset_final_sorted/CWE-310/java/good_4756_2
crossvul-java_data_bad_2093_3
404: Not Found
./CrossVul/dataset_final_sorted/CWE-310/java/bad_2093_3
crossvul-java_data_bad_2093_1
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Romain Seguy * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.model; import net.sf.json.JSONObject; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.DataBoundConstructor; import hudson.Extension; import hudson.util.Secret; /** * Parameter whose value is a {@link Secret} and is hidden from the UI. * * @author Kohsuke Kawaguchi * @since 1.319 */ public class PasswordParameterDefinition extends SimpleParameterDefinition { private Secret defaultValue; @DataBoundConstructor public PasswordParameterDefinition(String name, String defaultValue, String description) { super(name, description); this.defaultValue = Secret.fromString(defaultValue); } @Override public ParameterDefinition copyWithDefaultValue(ParameterValue defaultValue) { if (defaultValue instanceof PasswordParameterValue) { PasswordParameterValue value = (PasswordParameterValue) defaultValue; return new PasswordParameterDefinition(getName(), Secret.toString(value.getValue()), getDescription()); } else { return this; } } @Override public ParameterValue createValue(String value) { return new PasswordParameterValue(getName(), value, getDescription()); } @Override public PasswordParameterValue createValue(StaplerRequest req, JSONObject jo) { PasswordParameterValue value = req.bindJSON(PasswordParameterValue.class, jo); value.setDescription(getDescription()); return value; } @Override public ParameterValue getDefaultParameterValue() { return new PasswordParameterValue(getName(), getDefaultValue(), getDescription()); } public String getDefaultValue() { return Secret.toString(defaultValue); } // kept for backward compatibility public void setDefaultValue(String defaultValue) { this.defaultValue = Secret.fromString(defaultValue); } @Extension public final static class ParameterDescriptorImpl extends ParameterDescriptor { @Override public String getDisplayName() { return Messages.PasswordParameterDefinition_DisplayName(); } @Override public String getHelpFile() { return "/help/parameter/string.html"; } } }
./CrossVul/dataset_final_sorted/CWE-310/java/bad_2093_1