file_id
stringlengths
5
10
content
stringlengths
110
36.3k
repo
stringlengths
7
108
path
stringlengths
8
198
token_length
int64
37
8.19k
original_comment
stringlengths
11
5.72k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
62
36.3k
195998_8
/** * Copyright (c) 2012, 2013 SURFnet BV * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * 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. * * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. */ package nl.surfnet.bod.search; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import java.util.List; import nl.surfnet.bod.domain.UniPort; import org.apache.lucene.queryParser.ParseException; import org.junit.Test; public class PhysicalPortIndexAndSearchTest extends AbstractIndexAndSearch<UniPort> { public PhysicalPortIndexAndSearchTest() { super(UniPort.class); } @Test public void testIndexAndSearch() throws Exception { List<UniPort> physicalPorts = searchFor("gamma"); // (N.A.) assertThat(physicalPorts, hasSize(0)); physicalPorts = searchFor("ut"); // (UT One, UT Two) assertThat(physicalPorts, hasSize(2)); physicalPorts = searchFor("Ut"); // (UT One, UT Two) assertThat(physicalPorts, hasSize(2)); physicalPorts = searchFor("Mock"); // (All available (4) PP's) assertThat(physicalPorts, hasSize(4)); physicalPorts = searchFor("ETH-1-13-4"); // (Noc label 4) assertThat(physicalPorts, hasSize(1)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 4 label")); physicalPorts = searchFor("OME"); // (Mock_Ut002A_OME01_ETH-1-2-4, Mock_Ut001A_OME01_ETH-1-2-1) assertThat(physicalPorts, hasSize(2)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1")); assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2")); physicalPorts = searchFor("ETH-1-"); // (All available (4) PP's) assertThat(physicalPorts, hasSize(4)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1")); assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2")); assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label")); assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label")); physicalPorts = searchFor("1"); // (All available (4) PP's) assertThat(physicalPorts, hasSize(4)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1")); assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2")); assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label")); assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label")); physicalPorts = searchFor("1de"); // Mock_port 1de verdieping toren1a assertThat(physicalPorts, hasSize(1)); assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 1de verdieping toren1a")); physicalPorts = searchFor("2de"); // Mock_port 2de verdieping toren1b assertThat(physicalPorts, hasSize(1)); assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 2de verdieping toren1b")); } @Test public void shouldNotCrashOnColon() throws ParseException { List<UniPort> physicalPorts = searchFor("nocLabel:\"Noc 3 label\""); assertThat(physicalPorts, hasSize(1)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 3 label")); } }
zanetworker/bandwidth-on-demand
src/test/java/nl/surfnet/bod/search/PhysicalPortIndexAndSearchTest.java
1,581
// Mock_port 2de verdieping toren1b
line_comment
nl
/** * Copyright (c) 2012, 2013 SURFnet BV * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * 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. * * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. */ package nl.surfnet.bod.search; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; import java.util.List; import nl.surfnet.bod.domain.UniPort; import org.apache.lucene.queryParser.ParseException; import org.junit.Test; public class PhysicalPortIndexAndSearchTest extends AbstractIndexAndSearch<UniPort> { public PhysicalPortIndexAndSearchTest() { super(UniPort.class); } @Test public void testIndexAndSearch() throws Exception { List<UniPort> physicalPorts = searchFor("gamma"); // (N.A.) assertThat(physicalPorts, hasSize(0)); physicalPorts = searchFor("ut"); // (UT One, UT Two) assertThat(physicalPorts, hasSize(2)); physicalPorts = searchFor("Ut"); // (UT One, UT Two) assertThat(physicalPorts, hasSize(2)); physicalPorts = searchFor("Mock"); // (All available (4) PP's) assertThat(physicalPorts, hasSize(4)); physicalPorts = searchFor("ETH-1-13-4"); // (Noc label 4) assertThat(physicalPorts, hasSize(1)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 4 label")); physicalPorts = searchFor("OME"); // (Mock_Ut002A_OME01_ETH-1-2-4, Mock_Ut001A_OME01_ETH-1-2-1) assertThat(physicalPorts, hasSize(2)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1")); assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2")); physicalPorts = searchFor("ETH-1-"); // (All available (4) PP's) assertThat(physicalPorts, hasSize(4)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1")); assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2")); assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label")); assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label")); physicalPorts = searchFor("1"); // (All available (4) PP's) assertThat(physicalPorts, hasSize(4)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1")); assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2")); assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label")); assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label")); physicalPorts = searchFor("1de"); // Mock_port 1de verdieping toren1a assertThat(physicalPorts, hasSize(1)); assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 1de verdieping toren1a")); physicalPorts = searchFor("2de"); // Mock_port 2de<SUF> assertThat(physicalPorts, hasSize(1)); assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 2de verdieping toren1b")); } @Test public void shouldNotCrashOnColon() throws ParseException { List<UniPort> physicalPorts = searchFor("nocLabel:\"Noc 3 label\""); assertThat(physicalPorts, hasSize(1)); assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 3 label")); } }
109159_20
/* * * Paros and its related class files. * * Paros is an HTTP/HTTPS proxy for assessing web application security. * Copyright (C) 2003-2004 Chinotec Technologies Company * * This program is free software; you can redistribute it and/or * modify it under the terms of the Clarified Artistic License * as published by the Free Software Foundation. * * This program 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // ZAP: 2011/04/16 Support for running ZAP as a daemon // ZAP: 2012/03/15 Removed unnecessary castings from methods parse, getArgument and getHelp. // Changed to use the class StringBuilder instead of the class StringBuffer in the method // getHelp. // ZAP: 2012/10/15 Issue 397: Support weekly builds // ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments // ZAP: 2013/03/20 Issue 568: Allow extensions to run from the command line // ZAP: 2013/08/30 Issue 775: Allow host to be set via the command line // ZAP: 2013/12/03 Issue 933: Automatically determine install dir // ZAP: 2013/12/03 Issue 934: Handle files on the command line via extension // ZAP: 2014/01/17 Issue 987: Allow arbitrary config file values to be set via the command line // ZAP: 2014/05/20 Issue 1191: Cmdline session params have no effect // ZAP: 2015/04/02 Issue 321: Support multiple databases and Issue 1582: Low memory option // ZAP: 2015/10/06 Issue 1962: Install and update add-ons from the command line // ZAP: 2016/08/19 Issue 2782: Support -configfile // ZAP: 2016/09/22 JavaDoc tweaks // ZAP: 2016/11/07 Allow to disable default standard output logging // ZAP: 2017/03/26 Allow to obtain configs in the order specified // ZAP: 2017/05/12 Issue 3460: Support -suppinfo // ZAP: 2017/05/31 Handle null args and include a message in all exceptions. // ZAP: 2017/08/31 Use helper method I18N.getString(String, Object...). // ZAP: 2017/11/21 Validate that -cmd and -daemon are not set at the same time (they are mutually // exclusive). // ZAP: 2017/12/26 Remove unused command line arg SP. // ZAP: 2018/06/29 Add command line to run ZAP in dev mode. // ZAP: 2019/06/01 Normalise line endings. // ZAP: 2019/06/05 Normalise format/style. // ZAP: 2019/10/09 Issue 5619: Ensure -configfile maintains key order // ZAP: 2020/11/26 Use Log4j 2 classes for logging. // ZAP: 2021/05/14 Remove redundant type arguments. // ZAP: 2022/02/09 No longer parse host/port and deprecate related code. // ZAP: 2022/02/28 Remove code deprecated in 2.6.0 // ZAP: 2022/04/11 Remove -nouseragent option. // ZAP: 2022/08/18 Support parameters supplied to newly installed or updated add-ons. // ZAP: 2023/01/10 Tidy up logger. // ZAP: 2023/03/23 Read ZAP_SILENT env var. // ZAP: 2023/10/10 Add -sbomzip option. // ZAP: 2024/01/13 Add -loglevel option. package org.parosproxy.paros; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.function.UnaryOperator; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.parosproxy.paros.extension.CommandLineArgument; import org.parosproxy.paros.extension.CommandLineListener; import org.zaproxy.zap.ZAP; import org.zaproxy.zap.extension.autoupdate.ExtensionAutoUpdate; public class CommandLine { private static final Logger LOGGER = LogManager.getLogger(CommandLine.class); // ZAP: Made public public static final String SESSION = "-session"; public static final String NEW_SESSION = "-newsession"; public static final String DAEMON = "-daemon"; public static final String HELP = "-help"; public static final String HELP2 = "-h"; public static final String DIR = "-dir"; public static final String VERSION = "-version"; /** * @deprecated (2.12.0) No longer used/needed. It will be removed in a future release. */ @Deprecated public static final String PORT = "-port"; /** * @deprecated (2.12.0) No longer used/needed. It will be removed in a future release. */ @Deprecated public static final String HOST = "-host"; public static final String CMD = "-cmd"; public static final String INSTALL_DIR = "-installdir"; public static final String CONFIG = "-config"; public static final String CONFIG_FILE = "-configfile"; public static final String LOG_LEVEL = "-loglevel"; public static final String LOWMEM = "-lowmem"; public static final String EXPERIMENTALDB = "-experimentaldb"; public static final String SUPPORT_INFO = "-suppinfo"; public static final String SBOM_ZIP = "-sbomzip"; public static final String SILENT = "-silent"; static final String SILENT_ENV_VAR = "ZAP_SILENT"; /** * Command line option to disable the default logging through standard output. * * @see #isNoStdOutLog() * @since 2.6.0 */ public static final String NOSTDOUT = "-nostdout"; /** * Command line option to enable "dev mode". * * <p>With this option development related utilities/functionalities are enabled. For example, * it's shown an error counter in the footer tool bar and license is implicitly accepted (thus * not requiring to show/accept the license each time a new home is used). * * <p><strong>Note:</strong> this mode is always enabled when running ZAP directly from source * (i.e. not packaged in a JAR) or using a dev build. * * @see #isDevMode() * @since 2.8.0 */ public static final String DEV_MODE = "-dev"; private boolean GUI = true; private boolean daemon = false; private boolean reportVersion = false; private boolean displaySupportInfo = false; private boolean lowMem = false; private boolean experimentalDb = false; private boolean silent = false; private File saveSbomZip; private String[] args; private String[] argsBackup; private final Map<String, String> configs = new LinkedHashMap<>(); private final Hashtable<String, String> keywords = new Hashtable<>(); private List<CommandLineArgument[]> commandList = null; /** * Flag that indicates whether or not the default logging through standard output should be * disabled. */ private boolean noStdOutLog; /** Flag that indicates whether or not the "dev mode" is enabled. */ private boolean devMode; private Level logLevel; public CommandLine(String[] args) throws Exception { this(args, System::getenv); } CommandLine(String[] args, UnaryOperator<String> env) throws Exception { this.args = args == null ? new String[0] : args; this.argsBackup = new String[this.args.length]; System.arraycopy(this.args, 0, argsBackup, 0, this.args.length); parseFirst(this.args); readEnv(env); if (isEnabled(CommandLine.CMD) && isEnabled(CommandLine.DAEMON)) { throw new IllegalArgumentException( "Command line arguments " + CommandLine.CMD + " and " + CommandLine.DAEMON + " cannot be used at the same time."); } } private void readEnv(UnaryOperator<String> env) { if (env.apply(SILENT_ENV_VAR) != null) { setSilent(); } } private void setSilent() { silent = true; Constant.setSilent(true); } private boolean checkPair(String[] args, String paramName, int i) throws Exception { String key = args[i]; String value = null; if (key == null) { return false; } if (key.equalsIgnoreCase(paramName)) { value = args[i + 1]; if (value == null) { throw new Exception("Missing parameter for keyword '" + paramName + "'."); } keywords.put(paramName, value); args[i] = null; args[i + 1] = null; return true; } return false; } private boolean checkSwitch(String[] args, String paramName, int i) throws Exception { String key = args[i]; if (key == null) { return false; } if (key.equalsIgnoreCase(paramName)) { keywords.put(paramName, ""); args[i] = null; return true; } return false; } private void parseFirst(String[] args) throws Exception { for (int i = 0; i < args.length; i++) { if (parseSwitchs(args, i)) { continue; } if (parseKeywords(args, i)) { continue; } } } public void parse( List<CommandLineArgument[]> commandList, Map<String, CommandLineListener> extMap) throws Exception { this.parse(commandList, extMap, true); } /** * Parse the command line arguments * * @param commandList the list of commands * @param extMap a map of the extensions which support command line args * @param reportUnsupported if true will report unsupported args * @throws Exception * @since 2.12.0 */ public void parse( List<CommandLineArgument[]> commandList, Map<String, CommandLineListener> extMap, boolean reportUnsupported) throws Exception { this.commandList = commandList; CommandLineArgument lastArg = null; boolean found = false; int remainingValueCount = 0; boolean installingAddons = false; for (int i = 0; i < args.length; i++) { if (args[i] == null) { continue; } found = false; for (int j = 0; j < commandList.size() && !found; j++) { CommandLineArgument[] extArg = commandList.get(j); for (int k = 0; k < extArg.length && !found; k++) { if (args[i].compareToIgnoreCase(extArg[k].getName()) == 0) { // check if previous keyword satisfied its required no. of parameters if (remainingValueCount > 0) { throw new Exception( "Missing parameters for keyword '" + lastArg.getName() + "'."); } // process this keyword lastArg = extArg[k]; lastArg.setEnabled(true); found = true; if (ExtensionAutoUpdate.ADDON_INSTALL.equals(args[i]) || ExtensionAutoUpdate.ADDON_INSTALL_ALL.equals(args[i])) { installingAddons = true; } args[i] = null; remainingValueCount = lastArg.getNumOfArguments(); } } } // check if current string is a keyword preceded by '-' if (args[i] != null && args[i].startsWith("-")) { continue; } // check if there is no more expected param value if (lastArg != null && remainingValueCount == 0) { continue; } // check if consume remaining for last matched keywords if (!found && lastArg != null) { if (lastArg.getPattern() == null || lastArg.getPattern().matcher(args[i]).find()) { lastArg.getArguments().add(args[i]); if (remainingValueCount > 0) { remainingValueCount--; } args[i] = null; } else { throw new Exception(lastArg.getErrorMessage()); } } } // check if the last keyword satisfied its no. of parameters. if (lastArg != null && remainingValueCount > 0) { throw new Exception("Missing parameters for keyword '" + lastArg.getName() + "'."); } // check for supported extensions for (int i = 0; i < args.length; i++) { if (args[i] == null) { continue; } int dotIndex = args[i].lastIndexOf("."); if (dotIndex < 0) { // Only support files with extensions continue; } File file = new File(args[i]); if (!file.exists() || !file.canRead()) { // Not there or cant read .. move on continue; } String ext = args[i].substring(dotIndex + 1); CommandLineListener cll = extMap.get(ext); if (cll != null) { if (cll.handleFile(file)) { found = true; args[i] = null; } } } if (reportUnsupported && !installingAddons) { // check if there is some unknown keywords or parameters for (String arg : args) { if (arg != null) { if (arg.startsWith("-")) { throw new Exception( Constant.messages.getString("start.cmdline.badparam", arg)); } else { // Assume they were trying to specify a file File f = new File(arg); if (!f.exists()) { throw new Exception( Constant.messages.getString("start.cmdline.nofile", arg)); } else if (!f.canRead()) { throw new Exception( Constant.messages.getString("start.cmdline.noread", arg)); } else { // We probably dont handle this sort of file throw new Exception( Constant.messages.getString("start.cmdline.badfile", arg)); } } } } } } private boolean parseSwitchs(String[] args, int i) throws Exception { boolean result = false; if (checkSwitch(args, CMD, i)) { setDaemon(false); setGUI(false); } else if (checkSwitch(args, DAEMON, i)) { setDaemon(true); setGUI(false); } else if (checkSwitch(args, LOWMEM, i)) { setLowMem(true); } else if (checkSwitch(args, EXPERIMENTALDB, i)) { setExperimentalDb(true); } else if (checkSwitch(args, HELP, i)) { result = true; setGUI(false); } else if (checkSwitch(args, HELP2, i)) { result = true; setGUI(false); } else if (checkSwitch(args, VERSION, i)) { reportVersion = true; setDaemon(false); setGUI(false); } else if (checkSwitch(args, NOSTDOUT, i)) { noStdOutLog = true; } else if (checkSwitch(args, SUPPORT_INFO, i)) { displaySupportInfo = true; setDaemon(false); setGUI(false); } else if (checkSwitch(args, DEV_MODE, i)) { devMode = true; Constant.setDevMode(true); } else if (checkSwitch(args, SILENT, i)) { setSilent(); } return result; } private boolean parseKeywords(String[] args, int i) throws Exception { boolean result = false; if (checkPair(args, NEW_SESSION, i)) { result = true; } else if (checkPair(args, SESSION, i)) { result = true; } else if (checkPair(args, DIR, i)) { Constant.setZapHome(keywords.get(DIR)); result = true; } else if (checkPair(args, LOG_LEVEL, i)) { logLevel = Level.toLevel(keywords.get(LOG_LEVEL), null); if (logLevel == null) { throw new Exception("Invalid log level: \"" + keywords.get(LOG_LEVEL) + "\""); } result = true; } else if (checkPair(args, INSTALL_DIR, i)) { Constant.setZapInstall(keywords.get(INSTALL_DIR)); result = true; } else if (checkPair(args, SBOM_ZIP, i)) { String zipName = keywords.get(SBOM_ZIP); this.saveSbomZip = new File(zipName); setDaemon(false); setGUI(false); result = true; } else if (checkPair(args, CONFIG, i)) { String pair = keywords.get(CONFIG); if (pair != null && pair.indexOf("=") > 0) { int eqIndex = pair.indexOf("="); this.configs.put(pair.substring(0, eqIndex), pair.substring(eqIndex + 1)); result = true; } } else if (checkPair(args, CONFIG_FILE, i)) { String conf = keywords.get(CONFIG_FILE); File confFile = new File(conf); if (!confFile.isFile()) { // We cant use i18n here as the messages wont have been loaded throw new Exception("No such file: " + confFile.getAbsolutePath()); } else if (!confFile.canRead()) { // We cant use i18n here as the messages wont have been loaded throw new Exception("File not readable: " + confFile.getAbsolutePath()); } Properties prop = new Properties() { // Override methods to ensure keys returned in order List<Object> orderedKeys = new ArrayList<>(); private static final long serialVersionUID = 1L; @Override public synchronized Object put(Object key, Object value) { orderedKeys.add(key); return super.put(key, value); } @Override public synchronized Enumeration<Object> keys() { return Collections.enumeration(orderedKeys); } }; try (FileInputStream inStream = new FileInputStream(confFile)) { prop.load(inStream); } Enumeration<Object> keyEnum = prop.keys(); while (keyEnum.hasMoreElements()) { String key = (String) keyEnum.nextElement(); this.configs.put(key, prop.getProperty(key)); } } return result; } /** * Tells whether or not ZAP was started with GUI. * * @return {@code true} if ZAP was started with GUI, {@code false} otherwise */ public boolean isGUI() { return GUI; } /** * Sets whether or not ZAP was started with GUI. * * @param GUI {@code true} if ZAP was started with GUI, {@code false} otherwise */ public void setGUI(boolean GUI) { this.GUI = GUI; } public boolean isDaemon() { return daemon; } public void setDaemon(boolean daemon) { this.daemon = daemon; } public boolean isLowMem() { return lowMem; } public void setLowMem(boolean lowMem) { this.lowMem = lowMem; } public boolean isExperimentalDb() { return experimentalDb; } public void setExperimentalDb(boolean experimentalDb) { this.experimentalDb = experimentalDb; } public boolean isReportVersion() { return this.reportVersion; } public boolean isDisplaySupportInfo() { return this.displaySupportInfo; } public File getSaveSbomZip() { return this.saveSbomZip; } /** * @deprecated (2.12.0) No longer used/needed. It will be removed in a future release. */ @Deprecated public int getPort() { return -1; } /** * @deprecated (2.12.0) No longer used/needed. It will be removed in a future release. */ @Deprecated public String getHost() { return null; } /** * Gets the {@code config} command line arguments, in the order they were specified. * * @return the {@code config} command line arguments. * @since 2.6.0 */ public Map<String, String> getOrderedConfigs() { return configs; } public String getArgument(String keyword) { return keywords.get(keyword); } public String getHelp() { return CommandLine.getHelp(commandList); } /** * Tells whether or not the default logging through standard output should be disabled. * * @return {@code true} if the default logging through standard output should be disabled, * {@code false} otherwise. * @since 2.6.0 */ public boolean isNoStdOutLog() { return noStdOutLog; } /** * Returns the specified log level argument. * * @since 2.15.0 */ public Level getLogLevel() { return logLevel; } /** * Returns true if ZAP should not make any unsolicited requests, e.g. check-for-updates, etc. * * @since 2.8.0 */ public boolean isSilent() { return silent; } /** * Tells whether or not the "dev mode" should be enabled. * * @return {@code true} if the "dev mode" should be enabled, {@code false} otherwise. * @since 2.8.0 * @see #DEV_MODE */ public boolean isDevMode() { return devMode; } public static String getHelp(List<CommandLineArgument[]> cmdList) { String zap; if (Constant.isWindows()) { zap = "zap.bat"; } else { zap = "zap.sh"; } StringBuilder sb = new StringBuilder(); sb.append(Constant.messages.getString("cmdline.help", zap)); if (cmdList != null) { for (CommandLineArgument[] extArgs : cmdList) { for (CommandLineArgument extArg : extArgs) { sb.append("\t"); sb.append(extArg.getHelpMessage()).append("\n"); } } } return sb.toString(); } public boolean isEnabled(String keyword) { Object obj = keywords.get(keyword); return (obj != null) && (obj instanceof String); } /** * Reset the arguments so that they can be parsed again (e.g. after an add-on is installed) * * @since 2.12.0 */ public void resetArgs() { System.arraycopy(argsBackup, 0, args, 0, argsBackup.length); } /** * A method for reporting informational messages in {@link * CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages * are written to the log file and/or written to stdout as appropriate. * * @param str the informational message */ public static void info(String str) { switch (ZAP.getProcessType()) { case cmdline: System.out.println(str); break; default: // Ignore } // Always write to the log LOGGER.info(str); } /** * A method for reporting error messages in {@link * CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages * are written to the log file and/or written to stderr as appropriate. * * @param str the error message */ public static void error(String str) { switch (ZAP.getProcessType()) { case cmdline: System.err.println(str); break; default: // Ignore } // Always write to the log LOGGER.error(str); } /** * A method for reporting error messages in {@link * CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages * are written to the log file and/or written to stderr as appropriate. * * @param str the error message * @param e the cause of the error */ public static void error(String str, Throwable e) { switch (ZAP.getProcessType()) { case cmdline: System.err.println(str); break; default: // Ignore } // Always write to the log LOGGER.error(str, e); } }
zaproxy/zaproxy
zap/src/main/java/org/parosproxy/paros/CommandLine.java
6,974
// ZAP: 2017/08/31 Use helper method I18N.getString(String, Object...).
line_comment
nl
/* * * Paros and its related class files. * * Paros is an HTTP/HTTPS proxy for assessing web application security. * Copyright (C) 2003-2004 Chinotec Technologies Company * * This program is free software; you can redistribute it and/or * modify it under the terms of the Clarified Artistic License * as published by the Free Software Foundation. * * This program 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 * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // ZAP: 2011/04/16 Support for running ZAP as a daemon // ZAP: 2012/03/15 Removed unnecessary castings from methods parse, getArgument and getHelp. // Changed to use the class StringBuilder instead of the class StringBuffer in the method // getHelp. // ZAP: 2012/10/15 Issue 397: Support weekly builds // ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments // ZAP: 2013/03/20 Issue 568: Allow extensions to run from the command line // ZAP: 2013/08/30 Issue 775: Allow host to be set via the command line // ZAP: 2013/12/03 Issue 933: Automatically determine install dir // ZAP: 2013/12/03 Issue 934: Handle files on the command line via extension // ZAP: 2014/01/17 Issue 987: Allow arbitrary config file values to be set via the command line // ZAP: 2014/05/20 Issue 1191: Cmdline session params have no effect // ZAP: 2015/04/02 Issue 321: Support multiple databases and Issue 1582: Low memory option // ZAP: 2015/10/06 Issue 1962: Install and update add-ons from the command line // ZAP: 2016/08/19 Issue 2782: Support -configfile // ZAP: 2016/09/22 JavaDoc tweaks // ZAP: 2016/11/07 Allow to disable default standard output logging // ZAP: 2017/03/26 Allow to obtain configs in the order specified // ZAP: 2017/05/12 Issue 3460: Support -suppinfo // ZAP: 2017/05/31 Handle null args and include a message in all exceptions. // ZAP: 2017/08/31<SUF> // ZAP: 2017/11/21 Validate that -cmd and -daemon are not set at the same time (they are mutually // exclusive). // ZAP: 2017/12/26 Remove unused command line arg SP. // ZAP: 2018/06/29 Add command line to run ZAP in dev mode. // ZAP: 2019/06/01 Normalise line endings. // ZAP: 2019/06/05 Normalise format/style. // ZAP: 2019/10/09 Issue 5619: Ensure -configfile maintains key order // ZAP: 2020/11/26 Use Log4j 2 classes for logging. // ZAP: 2021/05/14 Remove redundant type arguments. // ZAP: 2022/02/09 No longer parse host/port and deprecate related code. // ZAP: 2022/02/28 Remove code deprecated in 2.6.0 // ZAP: 2022/04/11 Remove -nouseragent option. // ZAP: 2022/08/18 Support parameters supplied to newly installed or updated add-ons. // ZAP: 2023/01/10 Tidy up logger. // ZAP: 2023/03/23 Read ZAP_SILENT env var. // ZAP: 2023/10/10 Add -sbomzip option. // ZAP: 2024/01/13 Add -loglevel option. package org.parosproxy.paros; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.function.UnaryOperator; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.parosproxy.paros.extension.CommandLineArgument; import org.parosproxy.paros.extension.CommandLineListener; import org.zaproxy.zap.ZAP; import org.zaproxy.zap.extension.autoupdate.ExtensionAutoUpdate; public class CommandLine { private static final Logger LOGGER = LogManager.getLogger(CommandLine.class); // ZAP: Made public public static final String SESSION = "-session"; public static final String NEW_SESSION = "-newsession"; public static final String DAEMON = "-daemon"; public static final String HELP = "-help"; public static final String HELP2 = "-h"; public static final String DIR = "-dir"; public static final String VERSION = "-version"; /** * @deprecated (2.12.0) No longer used/needed. It will be removed in a future release. */ @Deprecated public static final String PORT = "-port"; /** * @deprecated (2.12.0) No longer used/needed. It will be removed in a future release. */ @Deprecated public static final String HOST = "-host"; public static final String CMD = "-cmd"; public static final String INSTALL_DIR = "-installdir"; public static final String CONFIG = "-config"; public static final String CONFIG_FILE = "-configfile"; public static final String LOG_LEVEL = "-loglevel"; public static final String LOWMEM = "-lowmem"; public static final String EXPERIMENTALDB = "-experimentaldb"; public static final String SUPPORT_INFO = "-suppinfo"; public static final String SBOM_ZIP = "-sbomzip"; public static final String SILENT = "-silent"; static final String SILENT_ENV_VAR = "ZAP_SILENT"; /** * Command line option to disable the default logging through standard output. * * @see #isNoStdOutLog() * @since 2.6.0 */ public static final String NOSTDOUT = "-nostdout"; /** * Command line option to enable "dev mode". * * <p>With this option development related utilities/functionalities are enabled. For example, * it's shown an error counter in the footer tool bar and license is implicitly accepted (thus * not requiring to show/accept the license each time a new home is used). * * <p><strong>Note:</strong> this mode is always enabled when running ZAP directly from source * (i.e. not packaged in a JAR) or using a dev build. * * @see #isDevMode() * @since 2.8.0 */ public static final String DEV_MODE = "-dev"; private boolean GUI = true; private boolean daemon = false; private boolean reportVersion = false; private boolean displaySupportInfo = false; private boolean lowMem = false; private boolean experimentalDb = false; private boolean silent = false; private File saveSbomZip; private String[] args; private String[] argsBackup; private final Map<String, String> configs = new LinkedHashMap<>(); private final Hashtable<String, String> keywords = new Hashtable<>(); private List<CommandLineArgument[]> commandList = null; /** * Flag that indicates whether or not the default logging through standard output should be * disabled. */ private boolean noStdOutLog; /** Flag that indicates whether or not the "dev mode" is enabled. */ private boolean devMode; private Level logLevel; public CommandLine(String[] args) throws Exception { this(args, System::getenv); } CommandLine(String[] args, UnaryOperator<String> env) throws Exception { this.args = args == null ? new String[0] : args; this.argsBackup = new String[this.args.length]; System.arraycopy(this.args, 0, argsBackup, 0, this.args.length); parseFirst(this.args); readEnv(env); if (isEnabled(CommandLine.CMD) && isEnabled(CommandLine.DAEMON)) { throw new IllegalArgumentException( "Command line arguments " + CommandLine.CMD + " and " + CommandLine.DAEMON + " cannot be used at the same time."); } } private void readEnv(UnaryOperator<String> env) { if (env.apply(SILENT_ENV_VAR) != null) { setSilent(); } } private void setSilent() { silent = true; Constant.setSilent(true); } private boolean checkPair(String[] args, String paramName, int i) throws Exception { String key = args[i]; String value = null; if (key == null) { return false; } if (key.equalsIgnoreCase(paramName)) { value = args[i + 1]; if (value == null) { throw new Exception("Missing parameter for keyword '" + paramName + "'."); } keywords.put(paramName, value); args[i] = null; args[i + 1] = null; return true; } return false; } private boolean checkSwitch(String[] args, String paramName, int i) throws Exception { String key = args[i]; if (key == null) { return false; } if (key.equalsIgnoreCase(paramName)) { keywords.put(paramName, ""); args[i] = null; return true; } return false; } private void parseFirst(String[] args) throws Exception { for (int i = 0; i < args.length; i++) { if (parseSwitchs(args, i)) { continue; } if (parseKeywords(args, i)) { continue; } } } public void parse( List<CommandLineArgument[]> commandList, Map<String, CommandLineListener> extMap) throws Exception { this.parse(commandList, extMap, true); } /** * Parse the command line arguments * * @param commandList the list of commands * @param extMap a map of the extensions which support command line args * @param reportUnsupported if true will report unsupported args * @throws Exception * @since 2.12.0 */ public void parse( List<CommandLineArgument[]> commandList, Map<String, CommandLineListener> extMap, boolean reportUnsupported) throws Exception { this.commandList = commandList; CommandLineArgument lastArg = null; boolean found = false; int remainingValueCount = 0; boolean installingAddons = false; for (int i = 0; i < args.length; i++) { if (args[i] == null) { continue; } found = false; for (int j = 0; j < commandList.size() && !found; j++) { CommandLineArgument[] extArg = commandList.get(j); for (int k = 0; k < extArg.length && !found; k++) { if (args[i].compareToIgnoreCase(extArg[k].getName()) == 0) { // check if previous keyword satisfied its required no. of parameters if (remainingValueCount > 0) { throw new Exception( "Missing parameters for keyword '" + lastArg.getName() + "'."); } // process this keyword lastArg = extArg[k]; lastArg.setEnabled(true); found = true; if (ExtensionAutoUpdate.ADDON_INSTALL.equals(args[i]) || ExtensionAutoUpdate.ADDON_INSTALL_ALL.equals(args[i])) { installingAddons = true; } args[i] = null; remainingValueCount = lastArg.getNumOfArguments(); } } } // check if current string is a keyword preceded by '-' if (args[i] != null && args[i].startsWith("-")) { continue; } // check if there is no more expected param value if (lastArg != null && remainingValueCount == 0) { continue; } // check if consume remaining for last matched keywords if (!found && lastArg != null) { if (lastArg.getPattern() == null || lastArg.getPattern().matcher(args[i]).find()) { lastArg.getArguments().add(args[i]); if (remainingValueCount > 0) { remainingValueCount--; } args[i] = null; } else { throw new Exception(lastArg.getErrorMessage()); } } } // check if the last keyword satisfied its no. of parameters. if (lastArg != null && remainingValueCount > 0) { throw new Exception("Missing parameters for keyword '" + lastArg.getName() + "'."); } // check for supported extensions for (int i = 0; i < args.length; i++) { if (args[i] == null) { continue; } int dotIndex = args[i].lastIndexOf("."); if (dotIndex < 0) { // Only support files with extensions continue; } File file = new File(args[i]); if (!file.exists() || !file.canRead()) { // Not there or cant read .. move on continue; } String ext = args[i].substring(dotIndex + 1); CommandLineListener cll = extMap.get(ext); if (cll != null) { if (cll.handleFile(file)) { found = true; args[i] = null; } } } if (reportUnsupported && !installingAddons) { // check if there is some unknown keywords or parameters for (String arg : args) { if (arg != null) { if (arg.startsWith("-")) { throw new Exception( Constant.messages.getString("start.cmdline.badparam", arg)); } else { // Assume they were trying to specify a file File f = new File(arg); if (!f.exists()) { throw new Exception( Constant.messages.getString("start.cmdline.nofile", arg)); } else if (!f.canRead()) { throw new Exception( Constant.messages.getString("start.cmdline.noread", arg)); } else { // We probably dont handle this sort of file throw new Exception( Constant.messages.getString("start.cmdline.badfile", arg)); } } } } } } private boolean parseSwitchs(String[] args, int i) throws Exception { boolean result = false; if (checkSwitch(args, CMD, i)) { setDaemon(false); setGUI(false); } else if (checkSwitch(args, DAEMON, i)) { setDaemon(true); setGUI(false); } else if (checkSwitch(args, LOWMEM, i)) { setLowMem(true); } else if (checkSwitch(args, EXPERIMENTALDB, i)) { setExperimentalDb(true); } else if (checkSwitch(args, HELP, i)) { result = true; setGUI(false); } else if (checkSwitch(args, HELP2, i)) { result = true; setGUI(false); } else if (checkSwitch(args, VERSION, i)) { reportVersion = true; setDaemon(false); setGUI(false); } else if (checkSwitch(args, NOSTDOUT, i)) { noStdOutLog = true; } else if (checkSwitch(args, SUPPORT_INFO, i)) { displaySupportInfo = true; setDaemon(false); setGUI(false); } else if (checkSwitch(args, DEV_MODE, i)) { devMode = true; Constant.setDevMode(true); } else if (checkSwitch(args, SILENT, i)) { setSilent(); } return result; } private boolean parseKeywords(String[] args, int i) throws Exception { boolean result = false; if (checkPair(args, NEW_SESSION, i)) { result = true; } else if (checkPair(args, SESSION, i)) { result = true; } else if (checkPair(args, DIR, i)) { Constant.setZapHome(keywords.get(DIR)); result = true; } else if (checkPair(args, LOG_LEVEL, i)) { logLevel = Level.toLevel(keywords.get(LOG_LEVEL), null); if (logLevel == null) { throw new Exception("Invalid log level: \"" + keywords.get(LOG_LEVEL) + "\""); } result = true; } else if (checkPair(args, INSTALL_DIR, i)) { Constant.setZapInstall(keywords.get(INSTALL_DIR)); result = true; } else if (checkPair(args, SBOM_ZIP, i)) { String zipName = keywords.get(SBOM_ZIP); this.saveSbomZip = new File(zipName); setDaemon(false); setGUI(false); result = true; } else if (checkPair(args, CONFIG, i)) { String pair = keywords.get(CONFIG); if (pair != null && pair.indexOf("=") > 0) { int eqIndex = pair.indexOf("="); this.configs.put(pair.substring(0, eqIndex), pair.substring(eqIndex + 1)); result = true; } } else if (checkPair(args, CONFIG_FILE, i)) { String conf = keywords.get(CONFIG_FILE); File confFile = new File(conf); if (!confFile.isFile()) { // We cant use i18n here as the messages wont have been loaded throw new Exception("No such file: " + confFile.getAbsolutePath()); } else if (!confFile.canRead()) { // We cant use i18n here as the messages wont have been loaded throw new Exception("File not readable: " + confFile.getAbsolutePath()); } Properties prop = new Properties() { // Override methods to ensure keys returned in order List<Object> orderedKeys = new ArrayList<>(); private static final long serialVersionUID = 1L; @Override public synchronized Object put(Object key, Object value) { orderedKeys.add(key); return super.put(key, value); } @Override public synchronized Enumeration<Object> keys() { return Collections.enumeration(orderedKeys); } }; try (FileInputStream inStream = new FileInputStream(confFile)) { prop.load(inStream); } Enumeration<Object> keyEnum = prop.keys(); while (keyEnum.hasMoreElements()) { String key = (String) keyEnum.nextElement(); this.configs.put(key, prop.getProperty(key)); } } return result; } /** * Tells whether or not ZAP was started with GUI. * * @return {@code true} if ZAP was started with GUI, {@code false} otherwise */ public boolean isGUI() { return GUI; } /** * Sets whether or not ZAP was started with GUI. * * @param GUI {@code true} if ZAP was started with GUI, {@code false} otherwise */ public void setGUI(boolean GUI) { this.GUI = GUI; } public boolean isDaemon() { return daemon; } public void setDaemon(boolean daemon) { this.daemon = daemon; } public boolean isLowMem() { return lowMem; } public void setLowMem(boolean lowMem) { this.lowMem = lowMem; } public boolean isExperimentalDb() { return experimentalDb; } public void setExperimentalDb(boolean experimentalDb) { this.experimentalDb = experimentalDb; } public boolean isReportVersion() { return this.reportVersion; } public boolean isDisplaySupportInfo() { return this.displaySupportInfo; } public File getSaveSbomZip() { return this.saveSbomZip; } /** * @deprecated (2.12.0) No longer used/needed. It will be removed in a future release. */ @Deprecated public int getPort() { return -1; } /** * @deprecated (2.12.0) No longer used/needed. It will be removed in a future release. */ @Deprecated public String getHost() { return null; } /** * Gets the {@code config} command line arguments, in the order they were specified. * * @return the {@code config} command line arguments. * @since 2.6.0 */ public Map<String, String> getOrderedConfigs() { return configs; } public String getArgument(String keyword) { return keywords.get(keyword); } public String getHelp() { return CommandLine.getHelp(commandList); } /** * Tells whether or not the default logging through standard output should be disabled. * * @return {@code true} if the default logging through standard output should be disabled, * {@code false} otherwise. * @since 2.6.0 */ public boolean isNoStdOutLog() { return noStdOutLog; } /** * Returns the specified log level argument. * * @since 2.15.0 */ public Level getLogLevel() { return logLevel; } /** * Returns true if ZAP should not make any unsolicited requests, e.g. check-for-updates, etc. * * @since 2.8.0 */ public boolean isSilent() { return silent; } /** * Tells whether or not the "dev mode" should be enabled. * * @return {@code true} if the "dev mode" should be enabled, {@code false} otherwise. * @since 2.8.0 * @see #DEV_MODE */ public boolean isDevMode() { return devMode; } public static String getHelp(List<CommandLineArgument[]> cmdList) { String zap; if (Constant.isWindows()) { zap = "zap.bat"; } else { zap = "zap.sh"; } StringBuilder sb = new StringBuilder(); sb.append(Constant.messages.getString("cmdline.help", zap)); if (cmdList != null) { for (CommandLineArgument[] extArgs : cmdList) { for (CommandLineArgument extArg : extArgs) { sb.append("\t"); sb.append(extArg.getHelpMessage()).append("\n"); } } } return sb.toString(); } public boolean isEnabled(String keyword) { Object obj = keywords.get(keyword); return (obj != null) && (obj instanceof String); } /** * Reset the arguments so that they can be parsed again (e.g. after an add-on is installed) * * @since 2.12.0 */ public void resetArgs() { System.arraycopy(argsBackup, 0, args, 0, argsBackup.length); } /** * A method for reporting informational messages in {@link * CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages * are written to the log file and/or written to stdout as appropriate. * * @param str the informational message */ public static void info(String str) { switch (ZAP.getProcessType()) { case cmdline: System.out.println(str); break; default: // Ignore } // Always write to the log LOGGER.info(str); } /** * A method for reporting error messages in {@link * CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages * are written to the log file and/or written to stderr as appropriate. * * @param str the error message */ public static void error(String str) { switch (ZAP.getProcessType()) { case cmdline: System.err.println(str); break; default: // Ignore } // Always write to the log LOGGER.error(str); } /** * A method for reporting error messages in {@link * CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages * are written to the log file and/or written to stderr as appropriate. * * @param str the error message * @param e the cause of the error */ public static void error(String str, Throwable e) { switch (ZAP.getProcessType()) { case cmdline: System.err.println(str); break; default: // Ignore } // Always write to the log LOGGER.error(str, e); } }
83718_1
/* * Copyright (c) 2013-2015 Frank de Jonge * * 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 com.flysystem.core; /** * @author Zeger Hoogeboom */ public interface Adapter extends Read, Write { }
zegerhoogeboom/flysystem-java
src/main/java/com/flysystem/core/Adapter.java
351
/** * @author Zeger Hoogeboom */
block_comment
nl
/* * Copyright (c) 2013-2015 Frank de Jonge * * 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 com.flysystem.core; /** * @author Zeger Hoogeboom<SUF>*/ public interface Adapter extends Read, Write { }
177181_25
/* * @version 2018/10/02 * - setEcho for accessibility * @version 2017/07/14 * - bug fix for readInt/Double/Boolean/Line with null prompt * @version 2017/04/26 * - bug fix for captured output with printf() method * @version 2016/10/02 * - moved some I/O code to AbstractConsoleProgram superclass * @version 2016/05/17 * - moved some menuAction code to AbstractConsoleProgram superclass * - added getFont() method to fix null-font-before-set issue * @version 2016/04/18 * - modified readBoolean, readLine to work with override input feature (e.g. HW2 autograder) * @version 2015/05/12 * - added scroll__() methods for scrolling around in the console * (these are called by ProgramMenuBar but are made public in case clients want them) */ /* * @(#)ConsoleProgram.java 1.99.1 08/12/08 */ // ************************************************************************ // * Copyright (c) 2008 by the Association for Computing Machinery * // * * // * The Java Task Force seeks to impose few restrictions on the use of * // * these packages so that users have as much freedom as possible to * // * use this software in constructive ways and can make the benefits of * // * that work available to others. In view of the legal complexities * // * of software development, however, it is essential for the ACM to * // * maintain its copyright to guard against attempts by others to * // * claim ownership rights. The full text of the JTF Software License * // * is available at the following URL: * // * * // * http://www.acm.org/jtf/jtf-software-license.pdf * // * * // ************************************************************************ package acm.program; import acm.io.*; import java.awt.*; import java.io.*; import java.util.*; import java.util.List; /* Class: ConsoleProgram() */ /** * This class is a standard subclass of <code><a href="Program.html">Program</a></code> * that installs a console in the window. */ public abstract class ConsoleProgram extends AbstractConsoleProgram { /* Constructor: ConsoleProgram() */ /** * Creates a new console program. * * @usage ConsoleProgram program = new ConsoleProgram(); */ public ConsoleProgram() { add(getConsole(), CENTER); validate(); } /* Method: run() */ /** * Specifies the code to be executed as the program runs. * The <code>run</code> method is required for applications that have * a thread of control that runs even in the absence of user actions, * such as a program that uses console interation or that involves * animation. GUI-based programs that operate by setting up an initial * configuration and then wait for user events usually do not specify a * <code>run</code> method and supply a new definition for <code>init</code> * instead. */ public void run() { /* Empty */ } /* Method: init() */ /** * Specifies the code to be executed as startup time before the * <code>run</code> method is called. Subclasses can override this * method to perform any initialization code that would ordinarily * be included in an applet <code>init</code> method. In general, * subclasses will override <code>init</code> in GUI-based programs * where the program simply sets up an initial state and then waits * for events from the user. The <code>run</code> method is required * for applications in which there needs to be some control thread * while the program runs, as in a typical animation. * * @usage program.init(); */ public void init() { /* Empty */ } /* Factory method: createConsole() */ /** * Creates the console used by the <code>ConsoleProgram</code>. * * @usage IOConsole console = program.createConsole(); * @return The console to be used by the program */ protected IOConsole createConsole() { return new IOConsole(); } // METHODS ADDED BY MARTY // BEGIN SNEAKY AUTOGRADER CODE // /* Instance Variables */ private InputFileReader inputReader = null; private boolean outputCapture = false; private boolean inputOverride = false; private List<String> echoedComments = null; private StringBuilder capturedOutput = new StringBuilder(); /* Static Constants */ private static final String absolveStudentStr = "[NOT THE STUDENT'S FAULT!]"; /* Administrative Methods */ private boolean shouldOverrideInput() { return inputOverride && (inputReader != null && inputReader.peekInputLine() != null); } /** * Signals the ConsoleProgram to use the input profile read from the file * with inputFilename, rather than prompt the user for input. * @param inputFilename File to draw the input from. */ public void overrideInput(String inputFilename) { if (!inputOverride) { inputOverride = true; inputReader = new InputFileReader(inputFilename); echoedComments = new ArrayList<String>(); String newTitle = getTitle() + " [Input from " + inputFilename + "]"; setTitle(newTitle); } } /** * Signals the ConsoleProgram to use the input profile read from the given stream, * rather than prompt the user for input. * @param inputFilename File to draw the input from. */ public void overrideInput(InputStream stream) { if (!inputOverride) { inputOverride = true; inputReader = new InputFileReader(stream); echoedComments = new ArrayList<String>(); String newTitle = getTitle() + " [Input from file]"; setTitle(newTitle); } } /** * Signals the ConsoleProgram to use the input profile read from the given reader, * rather than prompt the user for input. * @param inputFilename File to draw the input from. */ public void overrideInput(Reader reader) { if (!inputOverride) { inputOverride = true; inputReader = new InputFileReader(reader); echoedComments = new ArrayList<String>(); String newTitle = getTitle() + " [Input from file]"; setTitle(newTitle); } } public void captureOutput() { captureOutput(true); } public void captureOutput(boolean capture) { outputCapture = capture; if (capturedOutput == null) { capturedOutput = new StringBuilder(); } if (!outputCapture && capturedOutput.length() > 0) { capturedOutput.delete(0, capturedOutput.length()); } } public String getCapturedOutput() { return capturedOutput.toString(); } /** * Print all echoed comments from the input override file onscreen. */ public void echoComments() { println(getComments()); } /** * Print all echoed comments from the input override file onscreen. */ public String getComments() { StringBuilder builder = new StringBuilder(); if (inputOverride) { inputReader.flush(); Iterator<String> iter = echoedComments.iterator(); while (iter.hasNext()) { builder.append(iter.next().replace("#> ", "")); builder.append('\n'); } } return builder.toString(); } /* Overridden "Hijacked" Methods */ public void print(String value) { // all other print()s call print(String) if (outputCapture) { capturedOutput.append(value); } super.print(value); } public void print(String value, Color color) { // all other print()s call print(String) if (outputCapture) { capturedOutput.append(value); } super.print(value, color); } public void printf(String format, Object... args) { // BUGFIX: used to append captured output here, but implementation // of super.printf() calls super.print(), which made it print twice super.printf(format, args); } public void println() { if (outputCapture) { capturedOutput.append('\n'); } super.println(); } public void println(String value) { // all other println()s call println(String) if (outputCapture) { capturedOutput.append(value); capturedOutput.append('\n'); } super.println(value); } public void println(String value, Color color) { // all other println()s call println(String) if (outputCapture) { capturedOutput.append(value); capturedOutput.append('\n'); } super.println(value, color); } @Override public int readInt(String prompt, int min, int max) { int result; if (shouldOverrideInput()) { if (prompt != null && !prompt.endsWith(" ")) { prompt += " "; } result = getInputInt(); checkRange(result, min, max); // super.println(prompt + result + "\t<readInt>"); if (prompt != null) { print(prompt); } print(result, Color.BLUE); println("\t<readInt>"); } else { result = super.readInt(prompt, min, max); if (outputCapture) { capturedOutput.append(result); capturedOutput.append("\n"); } } return result; } @Override public double readDouble(String prompt, double min, double max) { double result; if (shouldOverrideInput()) { if (prompt != null && !prompt.endsWith(" ")) { prompt += " "; } result = getInputDouble(); checkRange(result, min, max); // super.println(prompt + result + "\t<readDouble>"); if (prompt != null) { print(prompt); } print(result, Color.BLUE); println("\t<readDouble>"); } else { result = super.readDouble(prompt, min, max); if (outputCapture) { capturedOutput.append(result); capturedOutput.append("\n"); } } return result; } @Override public boolean readBoolean(String prompt, String y, String n) { Boolean result = false; if (shouldOverrideInput()) { if (prompt != null && !prompt.endsWith(" ")) { prompt += " "; } if (prompt != null) { print(prompt); } result = getInputBoolean(y, n); println("\t<readBoolean>"); } else { result = super.readBoolean(prompt, y, n); } return result == null ? false : (boolean) result; } @Override public String readLine(String prompt) { String line = ""; if (shouldOverrideInput()) { if (prompt != null && !prompt.endsWith(" ")) { prompt += " "; } if (prompt != null) { print(prompt); } line = inputReader.readInputLine(); println(line + "\t<readLine>"); } else { line = super.readLine(prompt); } return line; } public void setEcho() { setEcho(true); } public void setEcho(boolean echo) { if (getOutputModel() instanceof IOConsole) { ((IOConsole) getOutputModel()).setEcho(echo); } } /* Support Methods */ private int getInputInt() { String line = null; try { line = inputReader.readInputLine(); return Integer.parseInt(line); } catch (NumberFormatException e) { throw new RuntimeException(absolveStudentStr + " Poorly formatted integer input: \"" + line + "\"", e); } } private double getInputDouble() { String line = null; try { line = inputReader.readInputLine(); return Double.parseDouble(line); } catch (NumberFormatException e) { throw new RuntimeException(absolveStudentStr + " Poorly formatted double input: \"" + line + "\"", e); } } private Boolean getInputBoolean(String t, String f) { String line = null; if (inputReader != null) { line = inputReader.readInputLine(); } print(line, Color.BLUE); return (t != null && t.equalsIgnoreCase(line)) ? Boolean.TRUE : (f != null && f.equalsIgnoreCase(line)) ? Boolean.FALSE : null; } private static void checkRange(int value, int min, int max) { if ((min > value) || (max < value)) throw new RuntimeException(absolveStudentStr + " Out of range [" + min + ", " + max + "] integer input: " + value); } private static void checkRange(double value, double min, double max) { if ((min > value) || (max < value)) throw new RuntimeException(absolveStudentStr + " Out of range [" + min + ", " + max + "] double input: " + value); } /* Input File Reader class */ class InputFileReader { /* Instance Variables */ private BufferedReader inputReader; private String cachedLine; /* Constructor */ public InputFileReader(String inputFilename) { try { cachedLine = null; if (inputFilename != null) inputReader = new BufferedReader(new FileReader(inputFilename)); } catch (IOException e) { throw new RuntimeException(absolveStudentStr + " Error while opening file: " + inputFilename, e); } } /* Constructor */ public InputFileReader(InputStream stream) { cachedLine = null; inputReader = new BufferedReader(new InputStreamReader(stream)); } /* Constructor */ public InputFileReader(Reader reader) { cachedLine = null; inputReader = new BufferedReader(reader); } /* Input file reading operations */ public String readInputLine() { String result = peekInputLine(); cachedLine = null; return result; } public String peekInputLine() { if (cachedLine == null) advanceLine(); return cachedLine; } /* Advances lines in the file until end of file, or a non-comment line appears. * Stores said line into the cachedLine instance variable. */ private void advanceLine() { if (inputReader == null) return; try { cachedLine = inputReader.readLine(); while (isComment(cachedLine)) { // should we echo this line? if (cachedLine.startsWith(echoCommentBeginStr)) echoedComments.add(cachedLine); cachedLine = inputReader.readLine(); } if (cachedLine == null) { print("[INPUT FILE EXHAUSTED!] "); inputReader = null; } } catch (IOException e) { throw new RuntimeException(absolveStudentStr + " Error while reading file.", e); } } private void flush() { if (inputReader == null) return; try { cachedLine = inputReader.readLine(); while (cachedLine != null) { // should we echo this line? if (cachedLine.startsWith(echoCommentBeginStr)) echoedComments.add(cachedLine); cachedLine = inputReader.readLine(); } } catch (IOException e) { throw new RuntimeException(absolveStudentStr + " Error while reading file.", e); } } /* A string is a comment iff it is non-null * and has beginning string "#" */ private boolean isComment(String str) { return (str != null) && (str.startsWith(commentBeginStr)); } /* Static/String Constants */ private static final String commentBeginStr = "#"; private static final String echoCommentBeginStr = "#>"; } }
zelenski/stanford-cpp-library
Archived/JavaBackEnd/eclipseproject/src/acm/program/ConsoleProgram.java
4,435
/* Overridden "Hijacked" Methods */
block_comment
nl
/* * @version 2018/10/02 * - setEcho for accessibility * @version 2017/07/14 * - bug fix for readInt/Double/Boolean/Line with null prompt * @version 2017/04/26 * - bug fix for captured output with printf() method * @version 2016/10/02 * - moved some I/O code to AbstractConsoleProgram superclass * @version 2016/05/17 * - moved some menuAction code to AbstractConsoleProgram superclass * - added getFont() method to fix null-font-before-set issue * @version 2016/04/18 * - modified readBoolean, readLine to work with override input feature (e.g. HW2 autograder) * @version 2015/05/12 * - added scroll__() methods for scrolling around in the console * (these are called by ProgramMenuBar but are made public in case clients want them) */ /* * @(#)ConsoleProgram.java 1.99.1 08/12/08 */ // ************************************************************************ // * Copyright (c) 2008 by the Association for Computing Machinery * // * * // * The Java Task Force seeks to impose few restrictions on the use of * // * these packages so that users have as much freedom as possible to * // * use this software in constructive ways and can make the benefits of * // * that work available to others. In view of the legal complexities * // * of software development, however, it is essential for the ACM to * // * maintain its copyright to guard against attempts by others to * // * claim ownership rights. The full text of the JTF Software License * // * is available at the following URL: * // * * // * http://www.acm.org/jtf/jtf-software-license.pdf * // * * // ************************************************************************ package acm.program; import acm.io.*; import java.awt.*; import java.io.*; import java.util.*; import java.util.List; /* Class: ConsoleProgram() */ /** * This class is a standard subclass of <code><a href="Program.html">Program</a></code> * that installs a console in the window. */ public abstract class ConsoleProgram extends AbstractConsoleProgram { /* Constructor: ConsoleProgram() */ /** * Creates a new console program. * * @usage ConsoleProgram program = new ConsoleProgram(); */ public ConsoleProgram() { add(getConsole(), CENTER); validate(); } /* Method: run() */ /** * Specifies the code to be executed as the program runs. * The <code>run</code> method is required for applications that have * a thread of control that runs even in the absence of user actions, * such as a program that uses console interation or that involves * animation. GUI-based programs that operate by setting up an initial * configuration and then wait for user events usually do not specify a * <code>run</code> method and supply a new definition for <code>init</code> * instead. */ public void run() { /* Empty */ } /* Method: init() */ /** * Specifies the code to be executed as startup time before the * <code>run</code> method is called. Subclasses can override this * method to perform any initialization code that would ordinarily * be included in an applet <code>init</code> method. In general, * subclasses will override <code>init</code> in GUI-based programs * where the program simply sets up an initial state and then waits * for events from the user. The <code>run</code> method is required * for applications in which there needs to be some control thread * while the program runs, as in a typical animation. * * @usage program.init(); */ public void init() { /* Empty */ } /* Factory method: createConsole() */ /** * Creates the console used by the <code>ConsoleProgram</code>. * * @usage IOConsole console = program.createConsole(); * @return The console to be used by the program */ protected IOConsole createConsole() { return new IOConsole(); } // METHODS ADDED BY MARTY // BEGIN SNEAKY AUTOGRADER CODE // /* Instance Variables */ private InputFileReader inputReader = null; private boolean outputCapture = false; private boolean inputOverride = false; private List<String> echoedComments = null; private StringBuilder capturedOutput = new StringBuilder(); /* Static Constants */ private static final String absolveStudentStr = "[NOT THE STUDENT'S FAULT!]"; /* Administrative Methods */ private boolean shouldOverrideInput() { return inputOverride && (inputReader != null && inputReader.peekInputLine() != null); } /** * Signals the ConsoleProgram to use the input profile read from the file * with inputFilename, rather than prompt the user for input. * @param inputFilename File to draw the input from. */ public void overrideInput(String inputFilename) { if (!inputOverride) { inputOverride = true; inputReader = new InputFileReader(inputFilename); echoedComments = new ArrayList<String>(); String newTitle = getTitle() + " [Input from " + inputFilename + "]"; setTitle(newTitle); } } /** * Signals the ConsoleProgram to use the input profile read from the given stream, * rather than prompt the user for input. * @param inputFilename File to draw the input from. */ public void overrideInput(InputStream stream) { if (!inputOverride) { inputOverride = true; inputReader = new InputFileReader(stream); echoedComments = new ArrayList<String>(); String newTitle = getTitle() + " [Input from file]"; setTitle(newTitle); } } /** * Signals the ConsoleProgram to use the input profile read from the given reader, * rather than prompt the user for input. * @param inputFilename File to draw the input from. */ public void overrideInput(Reader reader) { if (!inputOverride) { inputOverride = true; inputReader = new InputFileReader(reader); echoedComments = new ArrayList<String>(); String newTitle = getTitle() + " [Input from file]"; setTitle(newTitle); } } public void captureOutput() { captureOutput(true); } public void captureOutput(boolean capture) { outputCapture = capture; if (capturedOutput == null) { capturedOutput = new StringBuilder(); } if (!outputCapture && capturedOutput.length() > 0) { capturedOutput.delete(0, capturedOutput.length()); } } public String getCapturedOutput() { return capturedOutput.toString(); } /** * Print all echoed comments from the input override file onscreen. */ public void echoComments() { println(getComments()); } /** * Print all echoed comments from the input override file onscreen. */ public String getComments() { StringBuilder builder = new StringBuilder(); if (inputOverride) { inputReader.flush(); Iterator<String> iter = echoedComments.iterator(); while (iter.hasNext()) { builder.append(iter.next().replace("#> ", "")); builder.append('\n'); } } return builder.toString(); } /* Overridden "Hijacked" Methods<SUF>*/ public void print(String value) { // all other print()s call print(String) if (outputCapture) { capturedOutput.append(value); } super.print(value); } public void print(String value, Color color) { // all other print()s call print(String) if (outputCapture) { capturedOutput.append(value); } super.print(value, color); } public void printf(String format, Object... args) { // BUGFIX: used to append captured output here, but implementation // of super.printf() calls super.print(), which made it print twice super.printf(format, args); } public void println() { if (outputCapture) { capturedOutput.append('\n'); } super.println(); } public void println(String value) { // all other println()s call println(String) if (outputCapture) { capturedOutput.append(value); capturedOutput.append('\n'); } super.println(value); } public void println(String value, Color color) { // all other println()s call println(String) if (outputCapture) { capturedOutput.append(value); capturedOutput.append('\n'); } super.println(value, color); } @Override public int readInt(String prompt, int min, int max) { int result; if (shouldOverrideInput()) { if (prompt != null && !prompt.endsWith(" ")) { prompt += " "; } result = getInputInt(); checkRange(result, min, max); // super.println(prompt + result + "\t<readInt>"); if (prompt != null) { print(prompt); } print(result, Color.BLUE); println("\t<readInt>"); } else { result = super.readInt(prompt, min, max); if (outputCapture) { capturedOutput.append(result); capturedOutput.append("\n"); } } return result; } @Override public double readDouble(String prompt, double min, double max) { double result; if (shouldOverrideInput()) { if (prompt != null && !prompt.endsWith(" ")) { prompt += " "; } result = getInputDouble(); checkRange(result, min, max); // super.println(prompt + result + "\t<readDouble>"); if (prompt != null) { print(prompt); } print(result, Color.BLUE); println("\t<readDouble>"); } else { result = super.readDouble(prompt, min, max); if (outputCapture) { capturedOutput.append(result); capturedOutput.append("\n"); } } return result; } @Override public boolean readBoolean(String prompt, String y, String n) { Boolean result = false; if (shouldOverrideInput()) { if (prompt != null && !prompt.endsWith(" ")) { prompt += " "; } if (prompt != null) { print(prompt); } result = getInputBoolean(y, n); println("\t<readBoolean>"); } else { result = super.readBoolean(prompt, y, n); } return result == null ? false : (boolean) result; } @Override public String readLine(String prompt) { String line = ""; if (shouldOverrideInput()) { if (prompt != null && !prompt.endsWith(" ")) { prompt += " "; } if (prompt != null) { print(prompt); } line = inputReader.readInputLine(); println(line + "\t<readLine>"); } else { line = super.readLine(prompt); } return line; } public void setEcho() { setEcho(true); } public void setEcho(boolean echo) { if (getOutputModel() instanceof IOConsole) { ((IOConsole) getOutputModel()).setEcho(echo); } } /* Support Methods */ private int getInputInt() { String line = null; try { line = inputReader.readInputLine(); return Integer.parseInt(line); } catch (NumberFormatException e) { throw new RuntimeException(absolveStudentStr + " Poorly formatted integer input: \"" + line + "\"", e); } } private double getInputDouble() { String line = null; try { line = inputReader.readInputLine(); return Double.parseDouble(line); } catch (NumberFormatException e) { throw new RuntimeException(absolveStudentStr + " Poorly formatted double input: \"" + line + "\"", e); } } private Boolean getInputBoolean(String t, String f) { String line = null; if (inputReader != null) { line = inputReader.readInputLine(); } print(line, Color.BLUE); return (t != null && t.equalsIgnoreCase(line)) ? Boolean.TRUE : (f != null && f.equalsIgnoreCase(line)) ? Boolean.FALSE : null; } private static void checkRange(int value, int min, int max) { if ((min > value) || (max < value)) throw new RuntimeException(absolveStudentStr + " Out of range [" + min + ", " + max + "] integer input: " + value); } private static void checkRange(double value, double min, double max) { if ((min > value) || (max < value)) throw new RuntimeException(absolveStudentStr + " Out of range [" + min + ", " + max + "] double input: " + value); } /* Input File Reader class */ class InputFileReader { /* Instance Variables */ private BufferedReader inputReader; private String cachedLine; /* Constructor */ public InputFileReader(String inputFilename) { try { cachedLine = null; if (inputFilename != null) inputReader = new BufferedReader(new FileReader(inputFilename)); } catch (IOException e) { throw new RuntimeException(absolveStudentStr + " Error while opening file: " + inputFilename, e); } } /* Constructor */ public InputFileReader(InputStream stream) { cachedLine = null; inputReader = new BufferedReader(new InputStreamReader(stream)); } /* Constructor */ public InputFileReader(Reader reader) { cachedLine = null; inputReader = new BufferedReader(reader); } /* Input file reading operations */ public String readInputLine() { String result = peekInputLine(); cachedLine = null; return result; } public String peekInputLine() { if (cachedLine == null) advanceLine(); return cachedLine; } /* Advances lines in the file until end of file, or a non-comment line appears. * Stores said line into the cachedLine instance variable. */ private void advanceLine() { if (inputReader == null) return; try { cachedLine = inputReader.readLine(); while (isComment(cachedLine)) { // should we echo this line? if (cachedLine.startsWith(echoCommentBeginStr)) echoedComments.add(cachedLine); cachedLine = inputReader.readLine(); } if (cachedLine == null) { print("[INPUT FILE EXHAUSTED!] "); inputReader = null; } } catch (IOException e) { throw new RuntimeException(absolveStudentStr + " Error while reading file.", e); } } private void flush() { if (inputReader == null) return; try { cachedLine = inputReader.readLine(); while (cachedLine != null) { // should we echo this line? if (cachedLine.startsWith(echoCommentBeginStr)) echoedComments.add(cachedLine); cachedLine = inputReader.readLine(); } } catch (IOException e) { throw new RuntimeException(absolveStudentStr + " Error while reading file.", e); } } /* A string is a comment iff it is non-null * and has beginning string "#" */ private boolean isComment(String str) { return (str != null) && (str.startsWith(commentBeginStr)); } /* Static/String Constants */ private static final String commentBeginStr = "#"; private static final String echoCommentBeginStr = "#>"; } }
3160_2
/* * ZeroTier One - Network Virtualization Everywhere * Copyright (C) 2011-2015 ZeroTier, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * -- * * ZeroTier may be used and distributed under the terms of the GPLv3, which * are available at: http://www.gnu.org/licenses/gpl-3.0.html * * If you would like to embed ZeroTier into a commercial application or * redistribute it in a modified binary form, please contact ZeroTier Networks * LLC. Start here: http://www.zerotier.com/ */ package com.zerotier.sdk; import android.util.Log; import com.zerotier.sdk.util.StringUtils; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; /** * Virtual network configuration * <p> * Defined in ZeroTierOne.h as ZT_VirtualNetworkConfig */ public class VirtualNetworkConfig implements Comparable<VirtualNetworkConfig> { private final static String TAG = "VirtualNetworkConfig"; public static final int MAX_MULTICAST_SUBSCRIPTIONS = 4096; public static final int ZT_MAX_ZT_ASSIGNED_ADDRESSES = 16; private final long nwid; private final long mac; private final String name; private final VirtualNetworkStatus status; private final VirtualNetworkType type; private final int mtu; private final boolean dhcp; private final boolean bridge; private final boolean broadcastEnabled; private final int portError; private final long netconfRevision; private final InetSocketAddress[] assignedAddresses; private final VirtualNetworkRoute[] routes; private final VirtualNetworkDNS dns; public VirtualNetworkConfig(long nwid, long mac, String name, VirtualNetworkStatus status, VirtualNetworkType type, int mtu, boolean dhcp, boolean bridge, boolean broadcastEnabled, int portError, long netconfRevision, InetSocketAddress[] assignedAddresses, VirtualNetworkRoute[] routes, VirtualNetworkDNS dns) { this.nwid = nwid; this.mac = mac; this.name = name; this.status = status; this.type = type; if (mtu < 0) { throw new RuntimeException("mtu < 0: " + mtu); } this.mtu = mtu; this.dhcp = dhcp; this.bridge = bridge; this.broadcastEnabled = broadcastEnabled; this.portError = portError; if (netconfRevision < 0) { throw new RuntimeException("netconfRevision < 0: " + netconfRevision); } this.netconfRevision = netconfRevision; this.assignedAddresses = assignedAddresses; this.routes = routes; this.dns = dns; } @Override public String toString() { return "VirtualNetworkConfig(" + StringUtils.networkIdToString(nwid) + ", " + StringUtils.macAddressToString(mac) + ", " + name + ", " + status + ", " + type + ", " + mtu + ", " + dhcp + ", " + bridge + ", " + broadcastEnabled + ", " + portError + ", " + netconfRevision + ", " + Arrays.toString(assignedAddresses) + ", " + Arrays.toString(routes) + ", " + dns + ")"; } @Override public boolean equals(Object o) { if (o == null) { Log.i(TAG, "Old is null"); return false; } if (!(o instanceof VirtualNetworkConfig)) { Log.i(TAG, "Old is not an instance of VirtualNetworkConfig: " + o); return false; } VirtualNetworkConfig old = (VirtualNetworkConfig) o; if (this.nwid != old.nwid) { Log.i(TAG, "NetworkID Changed. New: " + StringUtils.networkIdToString(this.nwid) + " (" + this.nwid + "), " + "Old: " + StringUtils.networkIdToString(old.nwid) + " (" + old.nwid + ")"); return false; } if (this.mac != old.mac) { Log.i(TAG, "MAC Changed. New: " + StringUtils.macAddressToString(this.mac) + ", Old: " + StringUtils.macAddressToString(old.mac)); return false; } if (!this.name.equals(old.name)) { Log.i(TAG, "Name Changed. New: " + this.name + ", Old: " + old.name); return false; } if (this.status != old.status) { Log.i(TAG, "Status Changed. New: " + this.status + ", Old: " + old.status); return false; } if (this.type != old.type) { Log.i(TAG, "Type changed. New: " + this.type + ", Old: " + old.type); return false; } if (this.mtu != old.mtu) { Log.i(TAG, "MTU Changed. New: " + this.mtu + ", Old: " + old.mtu); return false; } if (this.dhcp != old.dhcp) { Log.i(TAG, "DHCP Flag Changed. New: " + this.dhcp + ", Old: " + old.dhcp); return false; } if (this.bridge != old.bridge) { Log.i(TAG, "Bridge Flag Changed. New: " + this.bridge + ", Old: " + old.bridge); return false; } if (this.broadcastEnabled != old.broadcastEnabled) { Log.i(TAG, "Broadcast Flag Changed. New: "+ this.broadcastEnabled + ", Old: " + old.broadcastEnabled); return false; } if (this.portError != old.portError) { Log.i(TAG, "Port Error Changed. New: " + this.portError + ", Old: " + old.portError); return false; } if (this.netconfRevision != old.netconfRevision) { Log.i(TAG, "NetConfRevision Changed. New: " + this.netconfRevision + ", Old: " + old.netconfRevision); return false; } if (!Arrays.equals(assignedAddresses, old.assignedAddresses)) { ArrayList<String> aaNew = new ArrayList<>(); ArrayList<String> aaOld = new ArrayList<>(); for (InetSocketAddress s : assignedAddresses) { aaNew.add(s.toString()); } for (InetSocketAddress s : old.assignedAddresses) { aaOld.add(s.toString()); } Collections.sort(aaNew); Collections.sort(aaOld); Log.i(TAG, "Assigned Addresses Changed"); Log.i(TAG, "New:"); for (String s : aaNew) { Log.i(TAG, " " + s); } Log.i(TAG, ""); Log.i(TAG, "Old:"); for (String s : aaOld) { Log.i(TAG, " " +s); } Log.i(TAG, ""); return false; } if (!Arrays.equals(routes, old.routes)) { ArrayList<String> rNew = new ArrayList<>(); ArrayList<String> rOld = new ArrayList<>(); for (VirtualNetworkRoute r : routes) { rNew.add(r.toString()); } for (VirtualNetworkRoute r : old.routes) { rOld.add(r.toString()); } Collections.sort(rNew); Collections.sort(rOld); Log.i(TAG, "Managed Routes Changed"); Log.i(TAG, "New:"); for (String s : rNew) { Log.i(TAG, " " + s); } Log.i(TAG, ""); Log.i(TAG, "Old:"); for (String s : rOld) { Log.i(TAG, " " + s); } Log.i(TAG, ""); return false; } boolean dnsEquals; if (this.dns == null) { //noinspection RedundantIfStatement if (old.dns == null) { dnsEquals = true; } else { dnsEquals = false; } } else { if (old.dns == null) { dnsEquals = false; } else { dnsEquals = this.dns.equals(old.dns); } } if (!dnsEquals) { Log.i(TAG, "DNS Changed. New: " + this.dns + ", Old: " + old.dns); return false; } return true; } @Override public int compareTo(VirtualNetworkConfig cfg) { return Long.compare(this.nwid, cfg.nwid); } @Override public int hashCode() { int result = 17; result = 37 * result + (int) (nwid ^ (nwid >>> 32)); result = 37 * result + (int) (mac ^ (mac >>> 32)); result = 37 * result + name.hashCode(); result = 37 * result + status.hashCode(); result = 37 * result + type.hashCode(); result = 37 * result + mtu; result = 37 * result + (dhcp ? 1 : 0); result = 37 * result + (bridge ? 1 : 0); result = 37 * result + (broadcastEnabled ? 1 : 0); result = 37 * result + portError; result = 37 * result + (int) (netconfRevision ^ (netconfRevision >>> 32)); result = 37 * result + Arrays.hashCode(assignedAddresses); result = 37 * result + Arrays.hashCode(routes); result = 37 * result + (dns == null ? 0 : dns.hashCode()); return result; } /** * 64-bit ZeroTier network ID */ public long getNwid() { return nwid; } /** * Ethernet MAC (48 bits) that should be assigned to port */ public long getMac() { return mac; } /** * Network name (from network configuration master) */ public String getName() { return name; } /** * Network configuration request status */ public VirtualNetworkStatus getStatus() { return status; } /** * Network type */ public VirtualNetworkType getType() { return type; } /** * Maximum interface MTU */ public int getMtu() { return mtu; } /** * If the network this port belongs to indicates DHCP availability * * <p>This is a suggestion. The underlying implementation is free to ignore it * for security or other reasons. This is simply a netconf parameter that * means 'DHCP is available on this network.'</p> */ public boolean isDhcp() { return dhcp; } /** * If this port is allowed to bridge to other networks * * <p>This is informational. If this is false, bridged packets will simply * be dropped and bridging won't work.</p> */ public boolean isBridge() { return bridge; } /** * If true, this network supports and allows broadcast (ff:ff:ff:ff:ff:ff) traffic */ public boolean isBroadcastEnabled() { return broadcastEnabled; } /** * If the network is in PORT_ERROR state, this is the error most recently returned by the port config callback */ public int getPortError() { return portError; } /** * Network config revision as reported by netconf master * * <p>If this is zero, it means we're still waiting for our netconf.</p> */ public long getNetconfRevision() { return netconfRevision; } /** * ZeroTier-assigned addresses (in {@link InetSocketAddress} objects) * <p> * For IP, the port number of the sockaddr_XX structure contains the number * of bits in the address netmask. Only the IP address and port are used. * Other fields like interface number can be ignored. * <p> * This is only used for ZeroTier-managed address assignments sent by the * virtual network's configuration master. */ public InetSocketAddress[] getAssignedAddresses() { return assignedAddresses; } /** * ZeroTier-assigned routes (in {@link VirtualNetworkRoute} objects) */ public VirtualNetworkRoute[] getRoutes() { return routes; } /** * Network specific DNS configuration */ public VirtualNetworkDNS getDns() { return dns; } }
zerotier/ZeroTierOne
java/src/com/zerotier/sdk/VirtualNetworkConfig.java
3,594
/** * 64-bit ZeroTier network ID */
block_comment
nl
/* * ZeroTier One - Network Virtualization Everywhere * Copyright (C) 2011-2015 ZeroTier, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * -- * * ZeroTier may be used and distributed under the terms of the GPLv3, which * are available at: http://www.gnu.org/licenses/gpl-3.0.html * * If you would like to embed ZeroTier into a commercial application or * redistribute it in a modified binary form, please contact ZeroTier Networks * LLC. Start here: http://www.zerotier.com/ */ package com.zerotier.sdk; import android.util.Log; import com.zerotier.sdk.util.StringUtils; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; /** * Virtual network configuration * <p> * Defined in ZeroTierOne.h as ZT_VirtualNetworkConfig */ public class VirtualNetworkConfig implements Comparable<VirtualNetworkConfig> { private final static String TAG = "VirtualNetworkConfig"; public static final int MAX_MULTICAST_SUBSCRIPTIONS = 4096; public static final int ZT_MAX_ZT_ASSIGNED_ADDRESSES = 16; private final long nwid; private final long mac; private final String name; private final VirtualNetworkStatus status; private final VirtualNetworkType type; private final int mtu; private final boolean dhcp; private final boolean bridge; private final boolean broadcastEnabled; private final int portError; private final long netconfRevision; private final InetSocketAddress[] assignedAddresses; private final VirtualNetworkRoute[] routes; private final VirtualNetworkDNS dns; public VirtualNetworkConfig(long nwid, long mac, String name, VirtualNetworkStatus status, VirtualNetworkType type, int mtu, boolean dhcp, boolean bridge, boolean broadcastEnabled, int portError, long netconfRevision, InetSocketAddress[] assignedAddresses, VirtualNetworkRoute[] routes, VirtualNetworkDNS dns) { this.nwid = nwid; this.mac = mac; this.name = name; this.status = status; this.type = type; if (mtu < 0) { throw new RuntimeException("mtu < 0: " + mtu); } this.mtu = mtu; this.dhcp = dhcp; this.bridge = bridge; this.broadcastEnabled = broadcastEnabled; this.portError = portError; if (netconfRevision < 0) { throw new RuntimeException("netconfRevision < 0: " + netconfRevision); } this.netconfRevision = netconfRevision; this.assignedAddresses = assignedAddresses; this.routes = routes; this.dns = dns; } @Override public String toString() { return "VirtualNetworkConfig(" + StringUtils.networkIdToString(nwid) + ", " + StringUtils.macAddressToString(mac) + ", " + name + ", " + status + ", " + type + ", " + mtu + ", " + dhcp + ", " + bridge + ", " + broadcastEnabled + ", " + portError + ", " + netconfRevision + ", " + Arrays.toString(assignedAddresses) + ", " + Arrays.toString(routes) + ", " + dns + ")"; } @Override public boolean equals(Object o) { if (o == null) { Log.i(TAG, "Old is null"); return false; } if (!(o instanceof VirtualNetworkConfig)) { Log.i(TAG, "Old is not an instance of VirtualNetworkConfig: " + o); return false; } VirtualNetworkConfig old = (VirtualNetworkConfig) o; if (this.nwid != old.nwid) { Log.i(TAG, "NetworkID Changed. New: " + StringUtils.networkIdToString(this.nwid) + " (" + this.nwid + "), " + "Old: " + StringUtils.networkIdToString(old.nwid) + " (" + old.nwid + ")"); return false; } if (this.mac != old.mac) { Log.i(TAG, "MAC Changed. New: " + StringUtils.macAddressToString(this.mac) + ", Old: " + StringUtils.macAddressToString(old.mac)); return false; } if (!this.name.equals(old.name)) { Log.i(TAG, "Name Changed. New: " + this.name + ", Old: " + old.name); return false; } if (this.status != old.status) { Log.i(TAG, "Status Changed. New: " + this.status + ", Old: " + old.status); return false; } if (this.type != old.type) { Log.i(TAG, "Type changed. New: " + this.type + ", Old: " + old.type); return false; } if (this.mtu != old.mtu) { Log.i(TAG, "MTU Changed. New: " + this.mtu + ", Old: " + old.mtu); return false; } if (this.dhcp != old.dhcp) { Log.i(TAG, "DHCP Flag Changed. New: " + this.dhcp + ", Old: " + old.dhcp); return false; } if (this.bridge != old.bridge) { Log.i(TAG, "Bridge Flag Changed. New: " + this.bridge + ", Old: " + old.bridge); return false; } if (this.broadcastEnabled != old.broadcastEnabled) { Log.i(TAG, "Broadcast Flag Changed. New: "+ this.broadcastEnabled + ", Old: " + old.broadcastEnabled); return false; } if (this.portError != old.portError) { Log.i(TAG, "Port Error Changed. New: " + this.portError + ", Old: " + old.portError); return false; } if (this.netconfRevision != old.netconfRevision) { Log.i(TAG, "NetConfRevision Changed. New: " + this.netconfRevision + ", Old: " + old.netconfRevision); return false; } if (!Arrays.equals(assignedAddresses, old.assignedAddresses)) { ArrayList<String> aaNew = new ArrayList<>(); ArrayList<String> aaOld = new ArrayList<>(); for (InetSocketAddress s : assignedAddresses) { aaNew.add(s.toString()); } for (InetSocketAddress s : old.assignedAddresses) { aaOld.add(s.toString()); } Collections.sort(aaNew); Collections.sort(aaOld); Log.i(TAG, "Assigned Addresses Changed"); Log.i(TAG, "New:"); for (String s : aaNew) { Log.i(TAG, " " + s); } Log.i(TAG, ""); Log.i(TAG, "Old:"); for (String s : aaOld) { Log.i(TAG, " " +s); } Log.i(TAG, ""); return false; } if (!Arrays.equals(routes, old.routes)) { ArrayList<String> rNew = new ArrayList<>(); ArrayList<String> rOld = new ArrayList<>(); for (VirtualNetworkRoute r : routes) { rNew.add(r.toString()); } for (VirtualNetworkRoute r : old.routes) { rOld.add(r.toString()); } Collections.sort(rNew); Collections.sort(rOld); Log.i(TAG, "Managed Routes Changed"); Log.i(TAG, "New:"); for (String s : rNew) { Log.i(TAG, " " + s); } Log.i(TAG, ""); Log.i(TAG, "Old:"); for (String s : rOld) { Log.i(TAG, " " + s); } Log.i(TAG, ""); return false; } boolean dnsEquals; if (this.dns == null) { //noinspection RedundantIfStatement if (old.dns == null) { dnsEquals = true; } else { dnsEquals = false; } } else { if (old.dns == null) { dnsEquals = false; } else { dnsEquals = this.dns.equals(old.dns); } } if (!dnsEquals) { Log.i(TAG, "DNS Changed. New: " + this.dns + ", Old: " + old.dns); return false; } return true; } @Override public int compareTo(VirtualNetworkConfig cfg) { return Long.compare(this.nwid, cfg.nwid); } @Override public int hashCode() { int result = 17; result = 37 * result + (int) (nwid ^ (nwid >>> 32)); result = 37 * result + (int) (mac ^ (mac >>> 32)); result = 37 * result + name.hashCode(); result = 37 * result + status.hashCode(); result = 37 * result + type.hashCode(); result = 37 * result + mtu; result = 37 * result + (dhcp ? 1 : 0); result = 37 * result + (bridge ? 1 : 0); result = 37 * result + (broadcastEnabled ? 1 : 0); result = 37 * result + portError; result = 37 * result + (int) (netconfRevision ^ (netconfRevision >>> 32)); result = 37 * result + Arrays.hashCode(assignedAddresses); result = 37 * result + Arrays.hashCode(routes); result = 37 * result + (dns == null ? 0 : dns.hashCode()); return result; } /** * 64-bit ZeroTier network<SUF>*/ public long getNwid() { return nwid; } /** * Ethernet MAC (48 bits) that should be assigned to port */ public long getMac() { return mac; } /** * Network name (from network configuration master) */ public String getName() { return name; } /** * Network configuration request status */ public VirtualNetworkStatus getStatus() { return status; } /** * Network type */ public VirtualNetworkType getType() { return type; } /** * Maximum interface MTU */ public int getMtu() { return mtu; } /** * If the network this port belongs to indicates DHCP availability * * <p>This is a suggestion. The underlying implementation is free to ignore it * for security or other reasons. This is simply a netconf parameter that * means 'DHCP is available on this network.'</p> */ public boolean isDhcp() { return dhcp; } /** * If this port is allowed to bridge to other networks * * <p>This is informational. If this is false, bridged packets will simply * be dropped and bridging won't work.</p> */ public boolean isBridge() { return bridge; } /** * If true, this network supports and allows broadcast (ff:ff:ff:ff:ff:ff) traffic */ public boolean isBroadcastEnabled() { return broadcastEnabled; } /** * If the network is in PORT_ERROR state, this is the error most recently returned by the port config callback */ public int getPortError() { return portError; } /** * Network config revision as reported by netconf master * * <p>If this is zero, it means we're still waiting for our netconf.</p> */ public long getNetconfRevision() { return netconfRevision; } /** * ZeroTier-assigned addresses (in {@link InetSocketAddress} objects) * <p> * For IP, the port number of the sockaddr_XX structure contains the number * of bits in the address netmask. Only the IP address and port are used. * Other fields like interface number can be ignored. * <p> * This is only used for ZeroTier-managed address assignments sent by the * virtual network's configuration master. */ public InetSocketAddress[] getAssignedAddresses() { return assignedAddresses; } /** * ZeroTier-assigned routes (in {@link VirtualNetworkRoute} objects) */ public VirtualNetworkRoute[] getRoutes() { return routes; } /** * Network specific DNS configuration */ public VirtualNetworkDNS getDns() { return dns; } }
141996_2
package com.dianping.cat.context.context; import com.dianping.cat.CatConstants; /** * 1、继承、扩展CatConstants常量类,添加一些常用的Type * 2、添加header常量,用于http协议传输rootId、parentId、childId三个context属性 * @author soar * @date 2019-01-10 */ public class CatConstantsExt extends CatConstants { /** * Type 常量 */ public static final String Type_URL_METHOD = "URL.method"; public static final String Type_URL_CLIENT = "URL.client"; public static final String Type_URL_FORWORD = "URL.forword"; public static final String Type_Service = "Service"; public static final String Type_Service_METHOD= "Service.method"; public static final String Type_Service_CLIENT = "Service.client"; public static final String Type_SQL = "SQL"; public static final String Type_SQL_METHOD= "SQL.method"; public static final String Type_SQL_CLIENT = "SQL.client"; public static final String Type_Cache = "Cache"; public static final String Type_Cache_METHOD= "Cache.method"; public static final String Type_Cache_CLIENT = "Cache.client"; public static final String Type_Call = "Call"; public static final String Type_Call_METHOD= "Call.method"; public static final String Type_Call_CLIENT = "Call.client"; /** * http header 常量 */ public static final String CAT_HTTP_HEADER_ROOT_MESSAGE_ID = "X-CAT-ROOT-MESSAGE-ID"; public static final String CAT_HTTP_HEADER_PARENT_MESSAGE_ID = "X-CAT-ROOT-PARENT-ID"; public static final String CAT_HTTP_HEADER_CHILD_MESSAGE_ID = "X-CAT-ROOT-CHILD-ID"; }
zhangwei9757/cat
cat-master/integration/context/CatConstantsExt.java
488
/** * http header 常量 */
block_comment
nl
package com.dianping.cat.context.context; import com.dianping.cat.CatConstants; /** * 1、继承、扩展CatConstants常量类,添加一些常用的Type * 2、添加header常量,用于http协议传输rootId、parentId、childId三个context属性 * @author soar * @date 2019-01-10 */ public class CatConstantsExt extends CatConstants { /** * Type 常量 */ public static final String Type_URL_METHOD = "URL.method"; public static final String Type_URL_CLIENT = "URL.client"; public static final String Type_URL_FORWORD = "URL.forword"; public static final String Type_Service = "Service"; public static final String Type_Service_METHOD= "Service.method"; public static final String Type_Service_CLIENT = "Service.client"; public static final String Type_SQL = "SQL"; public static final String Type_SQL_METHOD= "SQL.method"; public static final String Type_SQL_CLIENT = "SQL.client"; public static final String Type_Cache = "Cache"; public static final String Type_Cache_METHOD= "Cache.method"; public static final String Type_Cache_CLIENT = "Cache.client"; public static final String Type_Call = "Call"; public static final String Type_Call_METHOD= "Call.method"; public static final String Type_Call_CLIENT = "Call.client"; /** * http header 常量<SUF>*/ public static final String CAT_HTTP_HEADER_ROOT_MESSAGE_ID = "X-CAT-ROOT-MESSAGE-ID"; public static final String CAT_HTTP_HEADER_PARENT_MESSAGE_ID = "X-CAT-ROOT-PARENT-ID"; public static final String CAT_HTTP_HEADER_CHILD_MESSAGE_ID = "X-CAT-ROOT-CHILD-ID"; }
143205_47
/* * 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.jasper; import java.io.File; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.compiler.JspConfig; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.compiler.TagPluginManager; import org.apache.jasper.compiler.TldCache; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * A class to hold all init parameters specific to the JSP engine. * * @author Anil K. Vijendran * @author Hans Bergsten * @author Pierre Delisle */ public final class EmbeddedServletOptions implements Options { // Logger private final Log log = LogFactory.getLog(EmbeddedServletOptions.class); private Properties settings = new Properties(); /** * Is Jasper being used in development mode? */ private boolean development = true; /** * Should Ant fork its java compiles of JSP pages. */ public boolean fork = true; /** * Do you want to keep the generated Java files around? */ private boolean keepGenerated = true; /** * Should white spaces between directives or actions be trimmed? */ private boolean trimSpaces = false; /** * Determines whether tag handler pooling is enabled. */ private boolean isPoolingEnabled = true; /** * Do you want support for "mapped" files? This will generate * servlet that has a print statement per line of the JSP file. * This seems like a really nice feature to have for debugging. */ private boolean mappedFile = true; /** * Do we want to include debugging information in the class file? */ private boolean classDebugInfo = true; /** * Background compile thread check interval in seconds. */ private int checkInterval = 0; /** * Is the generation of SMAP info for JSR45 debugging suppressed? */ private boolean isSmapSuppressed = false; /** * Should SMAP info for JSR45 debugging be dumped to a file? */ private boolean isSmapDumped = false; /** * Are Text strings to be generated as char arrays? */ private boolean genStringAsCharArray = false; private boolean errorOnUseBeanInvalidClassAttribute = true; /** * I want to see my generated servlets. Which directory are they * in? */ private File scratchDir; /** * Need to have this as is for versions 4 and 5 of IE. Can be set from * the initParams so if it changes in the future all that is needed is * to have a jsp initParam of type ieClassId="<value>" */ private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"; /** * What classpath should I use while compiling generated servlets? */ private String classpath = null; /** * Compiler to use. */ private String compiler = null; /** * Compiler target VM. */ private String compilerTargetVM = "1.8"; /** * The compiler source VM. */ private String compilerSourceVM = "1.8"; /** * The compiler class name. */ private String compilerClassName = null; /** * Cache for the TLD URIs, resource paths and parsed files. */ private TldCache tldCache = null; /** * Jsp config information */ private JspConfig jspConfig = null; /** * TagPluginManager */ private TagPluginManager tagPluginManager = null; /** * Java platform encoding to generate the JSP * page servlet. */ private String javaEncoding = "UTF8"; /** * Modification test interval. */ private int modificationTestInterval = 4; /** * Is re-compilation attempted immediately after a failure? */ private boolean recompileOnFail = false; /** * Is generation of X-Powered-By response header enabled/disabled? */ private boolean xpoweredBy; /** * Should we include a source fragment in exception messages, which could be displayed * to the developer ? */ private boolean displaySourceFragment = true; /** * The maximum number of loaded jsps per web-application. If there are more * jsps loaded, they will be unloaded. */ private int maxLoadedJsps = -1; /** * The idle time in seconds after which a JSP is unloaded. * If unset or less or equal than 0, no jsps are unloaded. */ private int jspIdleTimeout = -1; /** * Should JSP.1.6 be applied strictly to attributes defined using scriptlet * expressions? */ private boolean strictQuoteEscaping = true; private boolean quoteAttributeEL = false; public String getProperty(String name ) { return settings.getProperty( name ); } public void setProperty(String name, String value ) { if (name != null && value != null){ settings.setProperty( name, value ); } } public void setQuoteAttributeEL(boolean b) { this.quoteAttributeEL = b; } @Override public boolean getQuoteAttributeEL() { return quoteAttributeEL; } /** * Are we keeping generated code around? */ @Override public boolean getKeepGenerated() { return keepGenerated; } /** * Should white spaces between directives or actions be trimmed? */ @Override public boolean getTrimSpaces() { return trimSpaces; } @Override public boolean isPoolingEnabled() { return isPoolingEnabled; } /** * Are we supporting HTML mapped servlets? */ @Override public boolean getMappedFile() { return mappedFile; } /** * Should class files be compiled with debug information? */ @Override public boolean getClassDebugInfo() { return classDebugInfo; } /** * Background JSP compile thread check interval */ @Override public int getCheckInterval() { return checkInterval; } /** * Modification test interval. */ @Override public int getModificationTestInterval() { return modificationTestInterval; } /** * Re-compile on failure. */ @Override public boolean getRecompileOnFail() { return recompileOnFail; } /** * Is Jasper being used in development mode? */ @Override public boolean getDevelopment() { return development; } /** * Is the generation of SMAP info for JSR45 debugging suppressed? */ @Override public boolean isSmapSuppressed() { return isSmapSuppressed; } /** * Should SMAP info for JSR45 debugging be dumped to a file? */ @Override public boolean isSmapDumped() { return isSmapDumped; } /** * Are Text strings to be generated as char arrays? */ @Override public boolean genStringAsCharArray() { return this.genStringAsCharArray; } /** * Class ID for use in the plugin tag when the browser is IE. */ @Override public String getIeClassId() { return ieClassId; } /** * What is my scratch dir? */ @Override public File getScratchDir() { return scratchDir; } /** * What classpath should I use while compiling the servlets * generated from JSP files? */ @Override public String getClassPath() { return classpath; } /** * Is generation of X-Powered-By response header enabled/disabled? */ @Override public boolean isXpoweredBy() { return xpoweredBy; } /** * Compiler to use. */ @Override public String getCompiler() { return compiler; } /** * @see Options#getCompilerTargetVM */ @Override public String getCompilerTargetVM() { return compilerTargetVM; } /** * @see Options#getCompilerSourceVM */ @Override public String getCompilerSourceVM() { return compilerSourceVM; } /** * Java compiler class to use. */ @Override public String getCompilerClassName() { return compilerClassName; } @Override public boolean getErrorOnUseBeanInvalidClassAttribute() { return errorOnUseBeanInvalidClassAttribute; } public void setErrorOnUseBeanInvalidClassAttribute(boolean b) { errorOnUseBeanInvalidClassAttribute = b; } @Override public TldCache getTldCache() { return tldCache; } public void setTldCache(TldCache tldCache) { this.tldCache = tldCache; } @Override public String getJavaEncoding() { return javaEncoding; } @Override public boolean getFork() { return fork; } @Override public JspConfig getJspConfig() { return jspConfig; } @Override public TagPluginManager getTagPluginManager() { return tagPluginManager; } @Override public boolean isCaching() { return false; } @Override public Map<String, TagLibraryInfo> getCache() { return null; } /** * Should we include a source fragment in exception messages, which could be displayed * to the developer ? */ @Override public boolean getDisplaySourceFragment() { return displaySourceFragment; } /** * Should jsps be unloaded if to many are loaded? * If set to a value greater than 0 eviction of jsps is started. Default: -1 */ @Override public int getMaxLoadedJsps() { return maxLoadedJsps; } /** * Should any jsps be unloaded when being idle for this time in seconds? * If set to a value greater than 0 eviction of jsps is started. Default: -1 */ @Override public int getJspIdleTimeout() { return jspIdleTimeout; } @Override public boolean getStrictQuoteEscaping() { return strictQuoteEscaping; } /** * Create an EmbeddedServletOptions object using data available from * ServletConfig and ServletContext. */ public EmbeddedServletOptions(ServletConfig config, ServletContext context) { Enumeration<String> enumeration=config.getInitParameterNames(); while( enumeration.hasMoreElements() ) { String k=enumeration.nextElement(); String v=config.getInitParameter( k ); setProperty( k, v); } String keepgen = config.getInitParameter("keepgenerated"); if (keepgen != null) { if (keepgen.equalsIgnoreCase("true")) { this.keepGenerated = true; } else if (keepgen.equalsIgnoreCase("false")) { this.keepGenerated = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.keepgen")); } } } String trimsp = config.getInitParameter("trimSpaces"); if (trimsp != null) { if (trimsp.equalsIgnoreCase("true")) { trimSpaces = true; } else if (trimsp.equalsIgnoreCase("false")) { trimSpaces = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.trimspaces")); } } } this.isPoolingEnabled = true; String poolingEnabledParam = config.getInitParameter("enablePooling"); if (poolingEnabledParam != null && !poolingEnabledParam.equalsIgnoreCase("true")) { if (poolingEnabledParam.equalsIgnoreCase("false")) { this.isPoolingEnabled = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.enablePooling")); } } } String mapFile = config.getInitParameter("mappedfile"); if (mapFile != null) { if (mapFile.equalsIgnoreCase("true")) { this.mappedFile = true; } else if (mapFile.equalsIgnoreCase("false")) { this.mappedFile = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.mappedFile")); } } } String debugInfo = config.getInitParameter("classdebuginfo"); if (debugInfo != null) { if (debugInfo.equalsIgnoreCase("true")) { this.classDebugInfo = true; } else if (debugInfo.equalsIgnoreCase("false")) { this.classDebugInfo = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.classDebugInfo")); } } } String checkInterval = config.getInitParameter("checkInterval"); if (checkInterval != null) { try { this.checkInterval = Integer.parseInt(checkInterval); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.checkInterval")); } } } String modificationTestInterval = config.getInitParameter("modificationTestInterval"); if (modificationTestInterval != null) { try { this.modificationTestInterval = Integer.parseInt(modificationTestInterval); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval")); } } } String recompileOnFail = config.getInitParameter("recompileOnFail"); if (recompileOnFail != null) { if (recompileOnFail.equalsIgnoreCase("true")) { this.recompileOnFail = true; } else if (recompileOnFail.equalsIgnoreCase("false")) { this.recompileOnFail = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.recompileOnFail")); } } } String development = config.getInitParameter("development"); if (development != null) { if (development.equalsIgnoreCase("true")) { this.development = true; } else if (development.equalsIgnoreCase("false")) { this.development = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.development")); } } } String suppressSmap = config.getInitParameter("suppressSmap"); if (suppressSmap != null) { if (suppressSmap.equalsIgnoreCase("true")) { isSmapSuppressed = true; } else if (suppressSmap.equalsIgnoreCase("false")) { isSmapSuppressed = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.suppressSmap")); } } } String dumpSmap = config.getInitParameter("dumpSmap"); if (dumpSmap != null) { if (dumpSmap.equalsIgnoreCase("true")) { isSmapDumped = true; } else if (dumpSmap.equalsIgnoreCase("false")) { isSmapDumped = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.dumpSmap")); } } } String genCharArray = config.getInitParameter("genStringAsCharArray"); if (genCharArray != null) { if (genCharArray.equalsIgnoreCase("true")) { genStringAsCharArray = true; } else if (genCharArray.equalsIgnoreCase("false")) { genStringAsCharArray = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.genchararray")); } } } String errBeanClass = config.getInitParameter("errorOnUseBeanInvalidClassAttribute"); if (errBeanClass != null) { if (errBeanClass.equalsIgnoreCase("true")) { errorOnUseBeanInvalidClassAttribute = true; } else if (errBeanClass.equalsIgnoreCase("false")) { errorOnUseBeanInvalidClassAttribute = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.errBean")); } } } String ieClassId = config.getInitParameter("ieClassId"); if (ieClassId != null) this.ieClassId = ieClassId; String classpath = config.getInitParameter("classpath"); if (classpath != null) this.classpath = classpath; /* * scratchdir */ String dir = config.getInitParameter("scratchdir"); if (dir != null) { scratchDir = new File(dir); } else { // First try the Servlet 2.2 javax.servlet.context.tempdir property scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR); if (scratchDir == null) { // Not running in a Servlet 2.2 container. // Try to get the JDK 1.2 java.io.tmpdir property dir = System.getProperty("java.io.tmpdir"); if (dir != null) scratchDir = new File(dir); } } if (this.scratchDir == null) { log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir")); return; } if (!(scratchDir.exists() && scratchDir.canRead() && scratchDir.canWrite() && scratchDir.isDirectory())) log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir", scratchDir.getAbsolutePath())); this.compiler = config.getInitParameter("compiler"); String compilerTargetVM = config.getInitParameter("compilerTargetVM"); if(compilerTargetVM != null) { this.compilerTargetVM = compilerTargetVM; } String compilerSourceVM = config.getInitParameter("compilerSourceVM"); if(compilerSourceVM != null) { this.compilerSourceVM = compilerSourceVM; } String javaEncoding = config.getInitParameter("javaEncoding"); if (javaEncoding != null) { this.javaEncoding = javaEncoding; } String compilerClassName = config.getInitParameter("compilerClassName"); if (compilerClassName != null) { this.compilerClassName = compilerClassName; } String fork = config.getInitParameter("fork"); if (fork != null) { if (fork.equalsIgnoreCase("true")) { this.fork = true; } else if (fork.equalsIgnoreCase("false")) { this.fork = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.fork")); } } } String xpoweredBy = config.getInitParameter("xpoweredBy"); if (xpoweredBy != null) { if (xpoweredBy.equalsIgnoreCase("true")) { this.xpoweredBy = true; } else if (xpoweredBy.equalsIgnoreCase("false")) { this.xpoweredBy = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.xpoweredBy")); } } } String displaySourceFragment = config.getInitParameter("displaySourceFragment"); if (displaySourceFragment != null) { if (displaySourceFragment.equalsIgnoreCase("true")) { this.displaySourceFragment = true; } else if (displaySourceFragment.equalsIgnoreCase("false")) { this.displaySourceFragment = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment")); } } } String maxLoadedJsps = config.getInitParameter("maxLoadedJsps"); if (maxLoadedJsps != null) { try { this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps)); } } } String jspIdleTimeout = config.getInitParameter("jspIdleTimeout"); if (jspIdleTimeout != null) { try { this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout)); } } } String strictQuoteEscaping = config.getInitParameter("strictQuoteEscaping"); if (strictQuoteEscaping != null) { if (strictQuoteEscaping.equalsIgnoreCase("true")) { this.strictQuoteEscaping = true; } else if (strictQuoteEscaping.equalsIgnoreCase("false")) { this.strictQuoteEscaping = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.strictQuoteEscaping")); } } } String quoteAttributeEL = config.getInitParameter("quoteAttributeEL"); if (quoteAttributeEL != null) { if (quoteAttributeEL.equalsIgnoreCase("true")) { this.quoteAttributeEL = true; } else if (quoteAttributeEL.equalsIgnoreCase("false")) { this.quoteAttributeEL = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.quoteAttributeEL")); } } } // Setup the global Tag Libraries location cache for this // web-application. tldCache = TldCache.getInstance(context); // Setup the jsp config info for this web app. jspConfig = new JspConfig(context); // Create a Tag plugin instance tagPluginManager = new TagPluginManager(context); } }
zhaohjf/tomcat9
java/org/apache/jasper/EmbeddedServletOptions.java
6,868
/** * @see Options#getCompilerTargetVM */
block_comment
nl
/* * 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.jasper; import java.io.File; import java.util.Enumeration; import java.util.Map; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.compiler.JspConfig; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.compiler.TagPluginManager; import org.apache.jasper.compiler.TldCache; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * A class to hold all init parameters specific to the JSP engine. * * @author Anil K. Vijendran * @author Hans Bergsten * @author Pierre Delisle */ public final class EmbeddedServletOptions implements Options { // Logger private final Log log = LogFactory.getLog(EmbeddedServletOptions.class); private Properties settings = new Properties(); /** * Is Jasper being used in development mode? */ private boolean development = true; /** * Should Ant fork its java compiles of JSP pages. */ public boolean fork = true; /** * Do you want to keep the generated Java files around? */ private boolean keepGenerated = true; /** * Should white spaces between directives or actions be trimmed? */ private boolean trimSpaces = false; /** * Determines whether tag handler pooling is enabled. */ private boolean isPoolingEnabled = true; /** * Do you want support for "mapped" files? This will generate * servlet that has a print statement per line of the JSP file. * This seems like a really nice feature to have for debugging. */ private boolean mappedFile = true; /** * Do we want to include debugging information in the class file? */ private boolean classDebugInfo = true; /** * Background compile thread check interval in seconds. */ private int checkInterval = 0; /** * Is the generation of SMAP info for JSR45 debugging suppressed? */ private boolean isSmapSuppressed = false; /** * Should SMAP info for JSR45 debugging be dumped to a file? */ private boolean isSmapDumped = false; /** * Are Text strings to be generated as char arrays? */ private boolean genStringAsCharArray = false; private boolean errorOnUseBeanInvalidClassAttribute = true; /** * I want to see my generated servlets. Which directory are they * in? */ private File scratchDir; /** * Need to have this as is for versions 4 and 5 of IE. Can be set from * the initParams so if it changes in the future all that is needed is * to have a jsp initParam of type ieClassId="<value>" */ private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"; /** * What classpath should I use while compiling generated servlets? */ private String classpath = null; /** * Compiler to use. */ private String compiler = null; /** * Compiler target VM. */ private String compilerTargetVM = "1.8"; /** * The compiler source VM. */ private String compilerSourceVM = "1.8"; /** * The compiler class name. */ private String compilerClassName = null; /** * Cache for the TLD URIs, resource paths and parsed files. */ private TldCache tldCache = null; /** * Jsp config information */ private JspConfig jspConfig = null; /** * TagPluginManager */ private TagPluginManager tagPluginManager = null; /** * Java platform encoding to generate the JSP * page servlet. */ private String javaEncoding = "UTF8"; /** * Modification test interval. */ private int modificationTestInterval = 4; /** * Is re-compilation attempted immediately after a failure? */ private boolean recompileOnFail = false; /** * Is generation of X-Powered-By response header enabled/disabled? */ private boolean xpoweredBy; /** * Should we include a source fragment in exception messages, which could be displayed * to the developer ? */ private boolean displaySourceFragment = true; /** * The maximum number of loaded jsps per web-application. If there are more * jsps loaded, they will be unloaded. */ private int maxLoadedJsps = -1; /** * The idle time in seconds after which a JSP is unloaded. * If unset or less or equal than 0, no jsps are unloaded. */ private int jspIdleTimeout = -1; /** * Should JSP.1.6 be applied strictly to attributes defined using scriptlet * expressions? */ private boolean strictQuoteEscaping = true; private boolean quoteAttributeEL = false; public String getProperty(String name ) { return settings.getProperty( name ); } public void setProperty(String name, String value ) { if (name != null && value != null){ settings.setProperty( name, value ); } } public void setQuoteAttributeEL(boolean b) { this.quoteAttributeEL = b; } @Override public boolean getQuoteAttributeEL() { return quoteAttributeEL; } /** * Are we keeping generated code around? */ @Override public boolean getKeepGenerated() { return keepGenerated; } /** * Should white spaces between directives or actions be trimmed? */ @Override public boolean getTrimSpaces() { return trimSpaces; } @Override public boolean isPoolingEnabled() { return isPoolingEnabled; } /** * Are we supporting HTML mapped servlets? */ @Override public boolean getMappedFile() { return mappedFile; } /** * Should class files be compiled with debug information? */ @Override public boolean getClassDebugInfo() { return classDebugInfo; } /** * Background JSP compile thread check interval */ @Override public int getCheckInterval() { return checkInterval; } /** * Modification test interval. */ @Override public int getModificationTestInterval() { return modificationTestInterval; } /** * Re-compile on failure. */ @Override public boolean getRecompileOnFail() { return recompileOnFail; } /** * Is Jasper being used in development mode? */ @Override public boolean getDevelopment() { return development; } /** * Is the generation of SMAP info for JSR45 debugging suppressed? */ @Override public boolean isSmapSuppressed() { return isSmapSuppressed; } /** * Should SMAP info for JSR45 debugging be dumped to a file? */ @Override public boolean isSmapDumped() { return isSmapDumped; } /** * Are Text strings to be generated as char arrays? */ @Override public boolean genStringAsCharArray() { return this.genStringAsCharArray; } /** * Class ID for use in the plugin tag when the browser is IE. */ @Override public String getIeClassId() { return ieClassId; } /** * What is my scratch dir? */ @Override public File getScratchDir() { return scratchDir; } /** * What classpath should I use while compiling the servlets * generated from JSP files? */ @Override public String getClassPath() { return classpath; } /** * Is generation of X-Powered-By response header enabled/disabled? */ @Override public boolean isXpoweredBy() { return xpoweredBy; } /** * Compiler to use. */ @Override public String getCompiler() { return compiler; } /** * @see Options#getCompilerTargetVM <SUF>*/ @Override public String getCompilerTargetVM() { return compilerTargetVM; } /** * @see Options#getCompilerSourceVM */ @Override public String getCompilerSourceVM() { return compilerSourceVM; } /** * Java compiler class to use. */ @Override public String getCompilerClassName() { return compilerClassName; } @Override public boolean getErrorOnUseBeanInvalidClassAttribute() { return errorOnUseBeanInvalidClassAttribute; } public void setErrorOnUseBeanInvalidClassAttribute(boolean b) { errorOnUseBeanInvalidClassAttribute = b; } @Override public TldCache getTldCache() { return tldCache; } public void setTldCache(TldCache tldCache) { this.tldCache = tldCache; } @Override public String getJavaEncoding() { return javaEncoding; } @Override public boolean getFork() { return fork; } @Override public JspConfig getJspConfig() { return jspConfig; } @Override public TagPluginManager getTagPluginManager() { return tagPluginManager; } @Override public boolean isCaching() { return false; } @Override public Map<String, TagLibraryInfo> getCache() { return null; } /** * Should we include a source fragment in exception messages, which could be displayed * to the developer ? */ @Override public boolean getDisplaySourceFragment() { return displaySourceFragment; } /** * Should jsps be unloaded if to many are loaded? * If set to a value greater than 0 eviction of jsps is started. Default: -1 */ @Override public int getMaxLoadedJsps() { return maxLoadedJsps; } /** * Should any jsps be unloaded when being idle for this time in seconds? * If set to a value greater than 0 eviction of jsps is started. Default: -1 */ @Override public int getJspIdleTimeout() { return jspIdleTimeout; } @Override public boolean getStrictQuoteEscaping() { return strictQuoteEscaping; } /** * Create an EmbeddedServletOptions object using data available from * ServletConfig and ServletContext. */ public EmbeddedServletOptions(ServletConfig config, ServletContext context) { Enumeration<String> enumeration=config.getInitParameterNames(); while( enumeration.hasMoreElements() ) { String k=enumeration.nextElement(); String v=config.getInitParameter( k ); setProperty( k, v); } String keepgen = config.getInitParameter("keepgenerated"); if (keepgen != null) { if (keepgen.equalsIgnoreCase("true")) { this.keepGenerated = true; } else if (keepgen.equalsIgnoreCase("false")) { this.keepGenerated = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.keepgen")); } } } String trimsp = config.getInitParameter("trimSpaces"); if (trimsp != null) { if (trimsp.equalsIgnoreCase("true")) { trimSpaces = true; } else if (trimsp.equalsIgnoreCase("false")) { trimSpaces = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.trimspaces")); } } } this.isPoolingEnabled = true; String poolingEnabledParam = config.getInitParameter("enablePooling"); if (poolingEnabledParam != null && !poolingEnabledParam.equalsIgnoreCase("true")) { if (poolingEnabledParam.equalsIgnoreCase("false")) { this.isPoolingEnabled = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.enablePooling")); } } } String mapFile = config.getInitParameter("mappedfile"); if (mapFile != null) { if (mapFile.equalsIgnoreCase("true")) { this.mappedFile = true; } else if (mapFile.equalsIgnoreCase("false")) { this.mappedFile = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.mappedFile")); } } } String debugInfo = config.getInitParameter("classdebuginfo"); if (debugInfo != null) { if (debugInfo.equalsIgnoreCase("true")) { this.classDebugInfo = true; } else if (debugInfo.equalsIgnoreCase("false")) { this.classDebugInfo = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.classDebugInfo")); } } } String checkInterval = config.getInitParameter("checkInterval"); if (checkInterval != null) { try { this.checkInterval = Integer.parseInt(checkInterval); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.checkInterval")); } } } String modificationTestInterval = config.getInitParameter("modificationTestInterval"); if (modificationTestInterval != null) { try { this.modificationTestInterval = Integer.parseInt(modificationTestInterval); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval")); } } } String recompileOnFail = config.getInitParameter("recompileOnFail"); if (recompileOnFail != null) { if (recompileOnFail.equalsIgnoreCase("true")) { this.recompileOnFail = true; } else if (recompileOnFail.equalsIgnoreCase("false")) { this.recompileOnFail = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.recompileOnFail")); } } } String development = config.getInitParameter("development"); if (development != null) { if (development.equalsIgnoreCase("true")) { this.development = true; } else if (development.equalsIgnoreCase("false")) { this.development = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.development")); } } } String suppressSmap = config.getInitParameter("suppressSmap"); if (suppressSmap != null) { if (suppressSmap.equalsIgnoreCase("true")) { isSmapSuppressed = true; } else if (suppressSmap.equalsIgnoreCase("false")) { isSmapSuppressed = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.suppressSmap")); } } } String dumpSmap = config.getInitParameter("dumpSmap"); if (dumpSmap != null) { if (dumpSmap.equalsIgnoreCase("true")) { isSmapDumped = true; } else if (dumpSmap.equalsIgnoreCase("false")) { isSmapDumped = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.dumpSmap")); } } } String genCharArray = config.getInitParameter("genStringAsCharArray"); if (genCharArray != null) { if (genCharArray.equalsIgnoreCase("true")) { genStringAsCharArray = true; } else if (genCharArray.equalsIgnoreCase("false")) { genStringAsCharArray = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.genchararray")); } } } String errBeanClass = config.getInitParameter("errorOnUseBeanInvalidClassAttribute"); if (errBeanClass != null) { if (errBeanClass.equalsIgnoreCase("true")) { errorOnUseBeanInvalidClassAttribute = true; } else if (errBeanClass.equalsIgnoreCase("false")) { errorOnUseBeanInvalidClassAttribute = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.errBean")); } } } String ieClassId = config.getInitParameter("ieClassId"); if (ieClassId != null) this.ieClassId = ieClassId; String classpath = config.getInitParameter("classpath"); if (classpath != null) this.classpath = classpath; /* * scratchdir */ String dir = config.getInitParameter("scratchdir"); if (dir != null) { scratchDir = new File(dir); } else { // First try the Servlet 2.2 javax.servlet.context.tempdir property scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR); if (scratchDir == null) { // Not running in a Servlet 2.2 container. // Try to get the JDK 1.2 java.io.tmpdir property dir = System.getProperty("java.io.tmpdir"); if (dir != null) scratchDir = new File(dir); } } if (this.scratchDir == null) { log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir")); return; } if (!(scratchDir.exists() && scratchDir.canRead() && scratchDir.canWrite() && scratchDir.isDirectory())) log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir", scratchDir.getAbsolutePath())); this.compiler = config.getInitParameter("compiler"); String compilerTargetVM = config.getInitParameter("compilerTargetVM"); if(compilerTargetVM != null) { this.compilerTargetVM = compilerTargetVM; } String compilerSourceVM = config.getInitParameter("compilerSourceVM"); if(compilerSourceVM != null) { this.compilerSourceVM = compilerSourceVM; } String javaEncoding = config.getInitParameter("javaEncoding"); if (javaEncoding != null) { this.javaEncoding = javaEncoding; } String compilerClassName = config.getInitParameter("compilerClassName"); if (compilerClassName != null) { this.compilerClassName = compilerClassName; } String fork = config.getInitParameter("fork"); if (fork != null) { if (fork.equalsIgnoreCase("true")) { this.fork = true; } else if (fork.equalsIgnoreCase("false")) { this.fork = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.fork")); } } } String xpoweredBy = config.getInitParameter("xpoweredBy"); if (xpoweredBy != null) { if (xpoweredBy.equalsIgnoreCase("true")) { this.xpoweredBy = true; } else if (xpoweredBy.equalsIgnoreCase("false")) { this.xpoweredBy = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.xpoweredBy")); } } } String displaySourceFragment = config.getInitParameter("displaySourceFragment"); if (displaySourceFragment != null) { if (displaySourceFragment.equalsIgnoreCase("true")) { this.displaySourceFragment = true; } else if (displaySourceFragment.equalsIgnoreCase("false")) { this.displaySourceFragment = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment")); } } } String maxLoadedJsps = config.getInitParameter("maxLoadedJsps"); if (maxLoadedJsps != null) { try { this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps)); } } } String jspIdleTimeout = config.getInitParameter("jspIdleTimeout"); if (jspIdleTimeout != null) { try { this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout); } catch(NumberFormatException ex) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout)); } } } String strictQuoteEscaping = config.getInitParameter("strictQuoteEscaping"); if (strictQuoteEscaping != null) { if (strictQuoteEscaping.equalsIgnoreCase("true")) { this.strictQuoteEscaping = true; } else if (strictQuoteEscaping.equalsIgnoreCase("false")) { this.strictQuoteEscaping = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.strictQuoteEscaping")); } } } String quoteAttributeEL = config.getInitParameter("quoteAttributeEL"); if (quoteAttributeEL != null) { if (quoteAttributeEL.equalsIgnoreCase("true")) { this.quoteAttributeEL = true; } else if (quoteAttributeEL.equalsIgnoreCase("false")) { this.quoteAttributeEL = false; } else { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage("jsp.warning.quoteAttributeEL")); } } } // Setup the global Tag Libraries location cache for this // web-application. tldCache = TldCache.getInstance(context); // Setup the jsp config info for this web app. jspConfig = new JspConfig(context); // Create a Tag plugin instance tagPluginManager = new TagPluginManager(context); } }
170394_0
package Tema11; import java.io.*; import javax.annotation.processing.ProcessingEnvironment; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.*; public class LeerDesdeFichero { //Miembros Dato private JFrame ventana; private JButton bCargar, bLeer; private JTextArea areaTexto; private FileDialog cuadroDialogo; private JPanel panelSuperior, panelInferior; private JOptionPane mensajeError; private JFileChooser cuadroDialogoFicheros; private String ruta; private BufferedReader flujoBr; File fichero; boolean pulsadoBotonCargar = false; public LeerDesdeFichero() { crearComponentes(); colocarComponentes(); registrarEventos(); } public void crearComponentes() { ventana = new JFrame(); ventana.setTitle("Creacion/Grabacion de Fichero"); ventana.setSize(400, 400); ventana.setResizable(true); //mensajeError = new Dialog(ventana,"Mensaje de Error",false); bCargar = new JButton("Cargar Fichero"); bLeer = new JButton("Leer Fichero"); areaTexto = new JTextArea(10, 30); areaTexto.setEnabled(false); panelSuperior = new JPanel(); panelInferior = new JPanel(); } public void colocarComponentes() { //Establecemos el Gestor, Colocamos los Objetos en el Panel Superior panelSuperior.add(areaTexto); //Establecemos el Gestor, Colocamos los Objetos en el Panel Inferior panelInferior.add(bCargar); panelInferior.add(bLeer); //Colocamos los Paneles en la Ventana ventana.add("North", panelSuperior); ventana.add("South", panelInferior); ventana.setVisible(true); } public void registrarEventos() { bCargar.addActionListener(new ManejadorBotones()); bLeer.addActionListener(new ManejadorBotones()); } class ManejadorBotones implements ActionListener { public void actionPerformed(ActionEvent e) { //getSource devuelve la referencia del objeto fuente que ha detectado el evento Object fuente = e.getSource(); if (fuente == bCargar) { /* VARIANTE USANDO FileDialog de AWT */ cuadroDialogo = new FileDialog(ventana, "Guardar", FileDialog.LOAD); cuadroDialogo.setVisible(true); ruta = cuadroDialogo.getDirectory() + cuadroDialogo.getFile(); pulsadoBotonCargar = true; } else if (fuente == bLeer) { if (pulsadoBotonCargar) { String linea; String eof = null; try { areaTexto.setEnabled(true); fichero = new File(ruta); flujoBr = new BufferedReader(new FileReader(ruta)); while ((linea = flujoBr.readLine()) != eof) { areaTexto.append(linea + "\n"); } flujoBr.close(); } catch (IOException error) { System.out.println(error.getMessage()); } } else { //mensajerError JOptionPane.showMessageDialog(ventana, "No Ha Pulsado el Boton de Carga de fichero"); } } } } public static void main(String args[]) { LeerDesdeFichero fichero = new LeerDesdeFichero(); } }
zhimbaya/curso-daw-2022
PROGRAMACION/TEMA-11/EJERCICIOS/Soluciones Actividades UT11.-20230503/ActividadUT11-4-LeerFichero/LeerDesdeFichero.java
1,116
//mensajeError = new Dialog(ventana,"Mensaje de Error",false);
line_comment
nl
package Tema11; import java.io.*; import javax.annotation.processing.ProcessingEnvironment; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.*; public class LeerDesdeFichero { //Miembros Dato private JFrame ventana; private JButton bCargar, bLeer; private JTextArea areaTexto; private FileDialog cuadroDialogo; private JPanel panelSuperior, panelInferior; private JOptionPane mensajeError; private JFileChooser cuadroDialogoFicheros; private String ruta; private BufferedReader flujoBr; File fichero; boolean pulsadoBotonCargar = false; public LeerDesdeFichero() { crearComponentes(); colocarComponentes(); registrarEventos(); } public void crearComponentes() { ventana = new JFrame(); ventana.setTitle("Creacion/Grabacion de Fichero"); ventana.setSize(400, 400); ventana.setResizable(true); //mensajeError =<SUF> bCargar = new JButton("Cargar Fichero"); bLeer = new JButton("Leer Fichero"); areaTexto = new JTextArea(10, 30); areaTexto.setEnabled(false); panelSuperior = new JPanel(); panelInferior = new JPanel(); } public void colocarComponentes() { //Establecemos el Gestor, Colocamos los Objetos en el Panel Superior panelSuperior.add(areaTexto); //Establecemos el Gestor, Colocamos los Objetos en el Panel Inferior panelInferior.add(bCargar); panelInferior.add(bLeer); //Colocamos los Paneles en la Ventana ventana.add("North", panelSuperior); ventana.add("South", panelInferior); ventana.setVisible(true); } public void registrarEventos() { bCargar.addActionListener(new ManejadorBotones()); bLeer.addActionListener(new ManejadorBotones()); } class ManejadorBotones implements ActionListener { public void actionPerformed(ActionEvent e) { //getSource devuelve la referencia del objeto fuente que ha detectado el evento Object fuente = e.getSource(); if (fuente == bCargar) { /* VARIANTE USANDO FileDialog de AWT */ cuadroDialogo = new FileDialog(ventana, "Guardar", FileDialog.LOAD); cuadroDialogo.setVisible(true); ruta = cuadroDialogo.getDirectory() + cuadroDialogo.getFile(); pulsadoBotonCargar = true; } else if (fuente == bLeer) { if (pulsadoBotonCargar) { String linea; String eof = null; try { areaTexto.setEnabled(true); fichero = new File(ruta); flujoBr = new BufferedReader(new FileReader(ruta)); while ((linea = flujoBr.readLine()) != eof) { areaTexto.append(linea + "\n"); } flujoBr.close(); } catch (IOException error) { System.out.println(error.getMessage()); } } else { //mensajerError JOptionPane.showMessageDialog(ventana, "No Ha Pulsado el Boton de Carga de fichero"); } } } } public static void main(String args[]) { LeerDesdeFichero fichero = new LeerDesdeFichero(); } }
136041_5
package com.zhisheng.examples.streaming.sideoutput; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.ProcessFunction; import org.apache.flink.util.Collector; import org.apache.flink.util.OutputTag; /** * Desc: SideOutput * Created by zhisheng on 2019-06-02 * blog:http://www.54tianzhisheng.cn/ * 微信公众号:zhisheng */ public class Main { private static final OutputTag<String> overFiveTag = new OutputTag<String>("overFive") { }; private static final OutputTag<String> equalFiveTag = new OutputTag<String>("equalFive") { }; public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime); env.getConfig().setGlobalJobParameters(params); SingleOutputStreamOperator<Tuple2<String, Integer>> tokenizer = env.fromElements(WORDS) .keyBy(new KeySelector<String, Integer>() { private static final long serialVersionUID = 1L; @Override public Integer getKey(String value) throws Exception { return 0; } }) .process(new Tokenizer()); // tokenizer.getSideOutput(overFiveTag).print(); //将字符串长度大于 5 的打印出来 // tokenizer.getSideOutput(equalFiveTag).print(); //将字符串长度等于 5 的打印出来 // tokenizer.print(); //这个打印出来的是字符串长度小于 5 的 tokenizer.keyBy(0) .sum(1) .print(); //做 word count 后打印出来 env.execute("Streaming WordCount SideOutput"); } public static final class Tokenizer extends ProcessFunction<String, Tuple2<String, Integer>> { private static final long serialVersionUID = 1L; @Override public void processElement(String value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception { String[] tokens = value.toLowerCase().split("\\W+"); for (String token : tokens) { if (token.length() > 5) { ctx.output(overFiveTag, token); //将字符串长度大于 5 的 word 放到 overFiveTag 中去 } else if (token.length() == 5) { ctx.output(equalFiveTag, token); //将字符串长度等于 5 的 word 放到 equalFiveTag 中去 } else if (token.length() < 5) { out.collect(new Tuple2<>(token, 1)); } } } } public static final String[] WORDS = new String[]{ "To be, or not to be,--that is the question:--", "Whether 'tis nobler in the mind to suffer", "The slings and arrows of outrageous fortune", "Or to take arms against a sea of troubles,", "And by opposing end them?--To die,--to sleep,--", "No more; and by a sleep to say we end", "The heartache, and the thousand natural shocks", "That flesh is heir to,--'tis a consummation", "Devoutly to be wish'd. To die,--to sleep;--", "To sleep! perchance to dream:--ay, there's the rub;", "For in that sleep of death what dreams may come,", "When we have shuffled off this mortal coil,", "Must give us pause: there's the respect", "That makes calamity of so long life;", "For who would bear the whips and scorns of time,", "The oppressor's wrong, the proud man's contumely,", "The pangs of despis'd love, the law's delay,", "The insolence of office, and the spurns", "That patient merit of the unworthy takes,", "When he himself might his quietus make", "With a bare bodkin? who would these fardels bear,", "To grunt and sweat under a weary life,", "But that the dread of something after death,--", "The undiscover'd country, from whose bourn", "No traveller returns,--puzzles the will,", "And makes us rather bear those ills we have", "Than fly to others that we know not of?", "Thus conscience does make cowards of us all;", "And thus the native hue of resolution", "Is sicklied o'er with the pale cast of thought;", "And enterprises of great pith and moment,", "With this regard, their currents turn awry,", "And lose the name of action.--Soft you now!", "The fair Ophelia!--Nymph, in thy orisons", "Be all my sins remember'd." }; }
zhisheng17/flink-learning
flink-learning-examples/src/main/java/com/zhisheng/examples/streaming/sideoutput/Main.java
1,413
//将字符串长度大于 5 的 word 放到 overFiveTag 中去
line_comment
nl
package com.zhisheng.examples.streaming.sideoutput; import org.apache.flink.api.java.functions.KeySelector; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.api.java.utils.ParameterTool; import org.apache.flink.streaming.api.TimeCharacteristic; import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.streaming.api.functions.ProcessFunction; import org.apache.flink.util.Collector; import org.apache.flink.util.OutputTag; /** * Desc: SideOutput * Created by zhisheng on 2019-06-02 * blog:http://www.54tianzhisheng.cn/ * 微信公众号:zhisheng */ public class Main { private static final OutputTag<String> overFiveTag = new OutputTag<String>("overFive") { }; private static final OutputTag<String> equalFiveTag = new OutputTag<String>("equalFive") { }; public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime); env.getConfig().setGlobalJobParameters(params); SingleOutputStreamOperator<Tuple2<String, Integer>> tokenizer = env.fromElements(WORDS) .keyBy(new KeySelector<String, Integer>() { private static final long serialVersionUID = 1L; @Override public Integer getKey(String value) throws Exception { return 0; } }) .process(new Tokenizer()); // tokenizer.getSideOutput(overFiveTag).print(); //将字符串长度大于 5 的打印出来 // tokenizer.getSideOutput(equalFiveTag).print(); //将字符串长度等于 5 的打印出来 // tokenizer.print(); //这个打印出来的是字符串长度小于 5 的 tokenizer.keyBy(0) .sum(1) .print(); //做 word count 后打印出来 env.execute("Streaming WordCount SideOutput"); } public static final class Tokenizer extends ProcessFunction<String, Tuple2<String, Integer>> { private static final long serialVersionUID = 1L; @Override public void processElement(String value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception { String[] tokens = value.toLowerCase().split("\\W+"); for (String token : tokens) { if (token.length() > 5) { ctx.output(overFiveTag, token); //将字符串长度大于 5<SUF> } else if (token.length() == 5) { ctx.output(equalFiveTag, token); //将字符串长度等于 5 的 word 放到 equalFiveTag 中去 } else if (token.length() < 5) { out.collect(new Tuple2<>(token, 1)); } } } } public static final String[] WORDS = new String[]{ "To be, or not to be,--that is the question:--", "Whether 'tis nobler in the mind to suffer", "The slings and arrows of outrageous fortune", "Or to take arms against a sea of troubles,", "And by opposing end them?--To die,--to sleep,--", "No more; and by a sleep to say we end", "The heartache, and the thousand natural shocks", "That flesh is heir to,--'tis a consummation", "Devoutly to be wish'd. To die,--to sleep;--", "To sleep! perchance to dream:--ay, there's the rub;", "For in that sleep of death what dreams may come,", "When we have shuffled off this mortal coil,", "Must give us pause: there's the respect", "That makes calamity of so long life;", "For who would bear the whips and scorns of time,", "The oppressor's wrong, the proud man's contumely,", "The pangs of despis'd love, the law's delay,", "The insolence of office, and the spurns", "That patient merit of the unworthy takes,", "When he himself might his quietus make", "With a bare bodkin? who would these fardels bear,", "To grunt and sweat under a weary life,", "But that the dread of something after death,--", "The undiscover'd country, from whose bourn", "No traveller returns,--puzzles the will,", "And makes us rather bear those ills we have", "Than fly to others that we know not of?", "Thus conscience does make cowards of us all;", "And thus the native hue of resolution", "Is sicklied o'er with the pale cast of thought;", "And enterprises of great pith and moment,", "With this regard, their currents turn awry,", "And lose the name of action.--Soft you now!", "The fair Ophelia!--Nymph, in thy orisons", "Be all my sins remember'd." }; }
45542_27
package bayou.async; import _bayou._async._Asyncs; import _bayou._async._Fiber_Stack_Trace_; import bayou.util.Result; import bayou.util.function.FunctionX; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.function.Consumer; import static _bayou._tmp._Util.cast; @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter", "ConstantConditions"}) class AsyncThen<T2> implements Async<T2> { volatile Pending<?,T2> pending_volatile; volatile Async<T2> target_volatile; /* initially in Pending state, pending=={async1, func}, target==null. operations in this phase must synchronize on the pending object. if((pending=pending_volatile)!=null) synchronized (pending) if((pending=pending_volatile)!=null) after `async1` is completed to result1, we compute async2=func(result1), then `this` /collapses/ to and /links/ to async2. `pending` is discarded. guaranteed: pending_volatile==null => target_volatile!=null no need for synchronization after collapse. (though target_volatile may still change) assuming no circles, the collapse relation forms trees. for simplicity, think of a non-AsyncThen as an AsyncThen that never collapses. if X links to Y, X may ask Y to /back-link/ to X, so that when Y collapses to Z, Y /updates/ X to link to Z. and so on. if X0 links to X1, we write X0--->X1. if X1 back-links to X0, we write X0<---X1. if both, X0<-->X1 initially there is X0. when it collapses to X1 X0--->X1 we then add a back link: X0<-->X1 when X1 collapses to X2, X1 updates X0 to X2 X0--->X2, X1--->X2 X0<-->X2, X1--->X2 but we don't want to establish X1<---X2. X1 is likely an intermediary object that nobody else references, so we don't want X2 to back-link to X1 with a strong reference. instead we do X1--->X0 X0<-->X2, X1--->X0 and so on: X0<-->Xn, X1--->X0, X2--->X0, ... X0 is the top level action. (likely nobody else references X0 either. that's fine, just one extra object) Xn is a pending action. (a non-AsyncThen is considered in Pending state for this purpose) others are intermediary actions that can usually be GC-ed. the goal is to reduce chaining. chaining is not a concern in sequential then(), e.g. a.then(...).then(...) but in nested then(), e.g. a.then( b.then(..) ) usually because of recursion, e.g. Async<Void> echo() read().then(::write).then(::echo) upon collapse, if a node has no back link, it's a "top" node; if it has back links, it's a "mid" node, it'll re-link to one of the back link and never changes. so any chain (eventually) contains at most 3 nodes mid ---> top <--> pending if X1 already links to X2 when X0 asks X1 to back-link, X0 will ask X2 to back-link instead. usually when X0 collapses to X1, X1 has not collapsed yet. this is especially true because our async exec serializes and postpone tasks. when X1 is created, it cannot collapse yet even if X1.async1 is completed. there may be legit cases where X1 collapses before X0. for example, X1 is a cached object, and multiple request processors call a method that returns X1. X1 then maintains multiple back links. that's fine. it can also occur due to scheduling uncertainty, occasionally some intermediary nodes are back linked to. that can accumulate and increasingly slow down the system during long time of recursions. we try to reduce that problem through weak references. hopefully this is rare. */ // naming convention of nodes: // `this` object is "y". it links to "z". it back-links to "x". public <T1> AsyncThen(Async<T1> async1, FunctionX<? super Result<T1>, ? extends Async<T2>> func) { ForEachNoAsync.warn(); Pending<T1,T2> pending = Fiber.enableTrace ? new PendingDebug<>(this, async1, func) : new Pending <>(this, async1, func); pending_volatile = pending; async1.onCompletion(pending); // leak `this` in constructor } static class Pending<T1,T2> implements Consumer<Result<T1>> { // could make this class an inner class. make it static to be more clear. final AsyncThen<T2> then; // enclosing object final Async<T1> async1; final FunctionX<? super Result<T1>, ? extends Async<T2>> func; Object backLinks; // either null, a single AsyncThen<T2>, or an ArrayList<WeakReference<AsyncThen<T2>>> void addBackLink(AsyncThen<T2> x) { if(backLinks ==null) // most common { backLinks = x; } else if(backLinks instanceof ArrayList) { ArrayList<WeakReference<AsyncThen<T2>>> list = cast(backLinks); list.add(new WeakReference<>(x)); } else // a single back link { AsyncThen<T2> x0 = cast(backLinks); ArrayList<WeakReference<AsyncThen<T2>>> list = new ArrayList<>(); list.add(new WeakReference<>(x0)); list.add(new WeakReference<>(x)); backLinks = list; } } Exception cancelReason; Consumer<Result<T2>> callbacks; // null, a single callback, or a CallbackList Pending(AsyncThen<T2> then, Async<T1> async1, FunctionX<? super Result<T1>, ? extends Async<T2>> func) { this.then = then; this.async1 = async1; this.func = func; } @Override // Consumer<Result<T1>>, async1 completes public void accept(Result<T1> result1) { Async<T2> async2 = Asyncs.applyRA(result1, func); then.collapseTo(this, async2); } } // for debugging, we do not do tail call elimination on fiber stack trace // so deep recursions may cause OOM error. // may fix this in future with a flag: fiberStackTraceTCO static class PendingDebug<T1,T2> extends Pending<T1,T2> { Fiber fiber; // can be null StackTraceElement[] trace; PendingDebug(AsyncThen<T2> then, Async<T1> async1, FunctionX<? super Result<T1>, ? extends Async<T2>> func) { super(then, async1, func); fiber = Fiber.current(); // can be null if(fiber!=null) trace = _Fiber_Stack_Trace_.captureTrace(); } @Override public void accept(Result<T1> result1) { if(fiber!=null) fiber.pushStackTrace(trace); Async<T2> async2 = Asyncs.applyRA(result1, func); if(fiber!=null) async2.onCompletion( v-> fiber.popStackTrace(trace) ); then.collapseTo(this, async2); } } void collapseTo(Pending<?, T2> pending, Async<T2> z) { assert pending_volatile==pending; synchronized (pending) { target_volatile = z; pending_volatile = null; } if(pending.cancelReason!=null) z.cancel(pending.cancelReason); // during pending phase, the cancel request was already sent to async1. // however async1 might have missed it, therefore we send it to z as well. // if async1 didn't miss it, "z" should be completed, and z.cancel() has no effect. // for each callback, do z.onCompletion(callback) CallbackList.registerTo(pending.callbacks, z); final AsyncThen<T2> y = this; if(pending.backLinks ==null) { makeBackLink(z, y); } else if(pending.backLinks instanceof ArrayList) // multiple back links, not common { AsyncThen<T2> x = null; ArrayList<WeakReference<AsyncThen<T2>>> list = cast(pending.backLinks); // size>=2 for(WeakReference<AsyncThen<T2>> xRef : list) { x = xRef.get(); if(x==null) // hopefully, all but one survives. continue; x.target_volatile = z; makeBackLink(z, x); } if(x!=null) y.target_volatile = x; else // all back links became garbage. there's actually no back-link. unlikely makeBackLink(z, y); } else // a single back link { AsyncThen<T2> x = cast(pending.backLinks); x.target_volatile = z; makeBackLink(z, x); y.target_volatile = x; // do this after x-->z } // `pending` is now garbage } // try to make X<--Y static <T2> void makeBackLink(Async<T2> y, AsyncThen<T2> x) { /* pseudo code with recursion: void makeBackLink(y, x) // x--->y if(y is pending) x<---y else // y--->z x--->z makeBackLink(z, x); */ while(y instanceof AsyncThen) { AsyncThen<T2> y_ = cast(y); Async<T2> z = y_.tryBackLinkTo(x); if(z==null) // y is pending, added back link to x return; // else, y is linking to z x.target_volatile = z; y = z; } } Async<T2> tryBackLinkTo(AsyncThen<T2> x) { Pending<?,T2> pending; if((pending=pending_volatile)!=null) { synchronized (pending) { if((pending=pending_volatile)!=null) { pending.addBackLink(x); return null; } } } // not pending. linking to z. return z. return target_volatile; // z } // Async methods ------------------------------------------------ @Override public String toString() { Async<T2> target = target_volatile; if(target==null) return "Async:Pending"; else return target.toString(); } @Override public Result<T2> pollResult() { Async<T2> target = target_volatile; if(target==null) return null; else return target.pollResult(); } @Override public void onCompletion(Consumer<Result<T2>> callback) { callback = _Asyncs.bindToCurrExec(callback); Pending<?,T2> pending; if((pending=pending_volatile)!=null) { synchronized (pending) { if((pending=pending_volatile)!=null) { pending.callbacks = CallbackList.concat(pending.callbacks, callback); return; } } } Async<T2> target = target_volatile; target.onCompletion(callback); } @Override public void cancel(Exception reason) { Pending<?,T2> pending; if((pending=pending_volatile)!=null) { synchronized (pending) { if((pending=pending_volatile)!=null) { if(pending.cancelReason!=null) return; pending.cancelReason = reason; // will do async1.cancel(reason); } } } Async<?> cancelTarget; if(pending!=null) cancelTarget = pending.async1; else cancelTarget = target_volatile; // direct cancelTarget.cancel() may cause deep stack. so do it async-ly Fiber.currentExecutor().execute(() -> cancelTarget.cancel(reason)); } }
zhong-j-yu/bayou
src/bayou/async/AsyncThen.java
3,514
// else, y is linking to z
line_comment
nl
package bayou.async; import _bayou._async._Asyncs; import _bayou._async._Fiber_Stack_Trace_; import bayou.util.Result; import bayou.util.function.FunctionX; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.function.Consumer; import static _bayou._tmp._Util.cast; @SuppressWarnings({"SynchronizationOnLocalVariableOrMethodParameter", "ConstantConditions"}) class AsyncThen<T2> implements Async<T2> { volatile Pending<?,T2> pending_volatile; volatile Async<T2> target_volatile; /* initially in Pending state, pending=={async1, func}, target==null. operations in this phase must synchronize on the pending object. if((pending=pending_volatile)!=null) synchronized (pending) if((pending=pending_volatile)!=null) after `async1` is completed to result1, we compute async2=func(result1), then `this` /collapses/ to and /links/ to async2. `pending` is discarded. guaranteed: pending_volatile==null => target_volatile!=null no need for synchronization after collapse. (though target_volatile may still change) assuming no circles, the collapse relation forms trees. for simplicity, think of a non-AsyncThen as an AsyncThen that never collapses. if X links to Y, X may ask Y to /back-link/ to X, so that when Y collapses to Z, Y /updates/ X to link to Z. and so on. if X0 links to X1, we write X0--->X1. if X1 back-links to X0, we write X0<---X1. if both, X0<-->X1 initially there is X0. when it collapses to X1 X0--->X1 we then add a back link: X0<-->X1 when X1 collapses to X2, X1 updates X0 to X2 X0--->X2, X1--->X2 X0<-->X2, X1--->X2 but we don't want to establish X1<---X2. X1 is likely an intermediary object that nobody else references, so we don't want X2 to back-link to X1 with a strong reference. instead we do X1--->X0 X0<-->X2, X1--->X0 and so on: X0<-->Xn, X1--->X0, X2--->X0, ... X0 is the top level action. (likely nobody else references X0 either. that's fine, just one extra object) Xn is a pending action. (a non-AsyncThen is considered in Pending state for this purpose) others are intermediary actions that can usually be GC-ed. the goal is to reduce chaining. chaining is not a concern in sequential then(), e.g. a.then(...).then(...) but in nested then(), e.g. a.then( b.then(..) ) usually because of recursion, e.g. Async<Void> echo() read().then(::write).then(::echo) upon collapse, if a node has no back link, it's a "top" node; if it has back links, it's a "mid" node, it'll re-link to one of the back link and never changes. so any chain (eventually) contains at most 3 nodes mid ---> top <--> pending if X1 already links to X2 when X0 asks X1 to back-link, X0 will ask X2 to back-link instead. usually when X0 collapses to X1, X1 has not collapsed yet. this is especially true because our async exec serializes and postpone tasks. when X1 is created, it cannot collapse yet even if X1.async1 is completed. there may be legit cases where X1 collapses before X0. for example, X1 is a cached object, and multiple request processors call a method that returns X1. X1 then maintains multiple back links. that's fine. it can also occur due to scheduling uncertainty, occasionally some intermediary nodes are back linked to. that can accumulate and increasingly slow down the system during long time of recursions. we try to reduce that problem through weak references. hopefully this is rare. */ // naming convention of nodes: // `this` object is "y". it links to "z". it back-links to "x". public <T1> AsyncThen(Async<T1> async1, FunctionX<? super Result<T1>, ? extends Async<T2>> func) { ForEachNoAsync.warn(); Pending<T1,T2> pending = Fiber.enableTrace ? new PendingDebug<>(this, async1, func) : new Pending <>(this, async1, func); pending_volatile = pending; async1.onCompletion(pending); // leak `this` in constructor } static class Pending<T1,T2> implements Consumer<Result<T1>> { // could make this class an inner class. make it static to be more clear. final AsyncThen<T2> then; // enclosing object final Async<T1> async1; final FunctionX<? super Result<T1>, ? extends Async<T2>> func; Object backLinks; // either null, a single AsyncThen<T2>, or an ArrayList<WeakReference<AsyncThen<T2>>> void addBackLink(AsyncThen<T2> x) { if(backLinks ==null) // most common { backLinks = x; } else if(backLinks instanceof ArrayList) { ArrayList<WeakReference<AsyncThen<T2>>> list = cast(backLinks); list.add(new WeakReference<>(x)); } else // a single back link { AsyncThen<T2> x0 = cast(backLinks); ArrayList<WeakReference<AsyncThen<T2>>> list = new ArrayList<>(); list.add(new WeakReference<>(x0)); list.add(new WeakReference<>(x)); backLinks = list; } } Exception cancelReason; Consumer<Result<T2>> callbacks; // null, a single callback, or a CallbackList Pending(AsyncThen<T2> then, Async<T1> async1, FunctionX<? super Result<T1>, ? extends Async<T2>> func) { this.then = then; this.async1 = async1; this.func = func; } @Override // Consumer<Result<T1>>, async1 completes public void accept(Result<T1> result1) { Async<T2> async2 = Asyncs.applyRA(result1, func); then.collapseTo(this, async2); } } // for debugging, we do not do tail call elimination on fiber stack trace // so deep recursions may cause OOM error. // may fix this in future with a flag: fiberStackTraceTCO static class PendingDebug<T1,T2> extends Pending<T1,T2> { Fiber fiber; // can be null StackTraceElement[] trace; PendingDebug(AsyncThen<T2> then, Async<T1> async1, FunctionX<? super Result<T1>, ? extends Async<T2>> func) { super(then, async1, func); fiber = Fiber.current(); // can be null if(fiber!=null) trace = _Fiber_Stack_Trace_.captureTrace(); } @Override public void accept(Result<T1> result1) { if(fiber!=null) fiber.pushStackTrace(trace); Async<T2> async2 = Asyncs.applyRA(result1, func); if(fiber!=null) async2.onCompletion( v-> fiber.popStackTrace(trace) ); then.collapseTo(this, async2); } } void collapseTo(Pending<?, T2> pending, Async<T2> z) { assert pending_volatile==pending; synchronized (pending) { target_volatile = z; pending_volatile = null; } if(pending.cancelReason!=null) z.cancel(pending.cancelReason); // during pending phase, the cancel request was already sent to async1. // however async1 might have missed it, therefore we send it to z as well. // if async1 didn't miss it, "z" should be completed, and z.cancel() has no effect. // for each callback, do z.onCompletion(callback) CallbackList.registerTo(pending.callbacks, z); final AsyncThen<T2> y = this; if(pending.backLinks ==null) { makeBackLink(z, y); } else if(pending.backLinks instanceof ArrayList) // multiple back links, not common { AsyncThen<T2> x = null; ArrayList<WeakReference<AsyncThen<T2>>> list = cast(pending.backLinks); // size>=2 for(WeakReference<AsyncThen<T2>> xRef : list) { x = xRef.get(); if(x==null) // hopefully, all but one survives. continue; x.target_volatile = z; makeBackLink(z, x); } if(x!=null) y.target_volatile = x; else // all back links became garbage. there's actually no back-link. unlikely makeBackLink(z, y); } else // a single back link { AsyncThen<T2> x = cast(pending.backLinks); x.target_volatile = z; makeBackLink(z, x); y.target_volatile = x; // do this after x-->z } // `pending` is now garbage } // try to make X<--Y static <T2> void makeBackLink(Async<T2> y, AsyncThen<T2> x) { /* pseudo code with recursion: void makeBackLink(y, x) // x--->y if(y is pending) x<---y else // y--->z x--->z makeBackLink(z, x); */ while(y instanceof AsyncThen) { AsyncThen<T2> y_ = cast(y); Async<T2> z = y_.tryBackLinkTo(x); if(z==null) // y is pending, added back link to x return; // else, y<SUF> x.target_volatile = z; y = z; } } Async<T2> tryBackLinkTo(AsyncThen<T2> x) { Pending<?,T2> pending; if((pending=pending_volatile)!=null) { synchronized (pending) { if((pending=pending_volatile)!=null) { pending.addBackLink(x); return null; } } } // not pending. linking to z. return z. return target_volatile; // z } // Async methods ------------------------------------------------ @Override public String toString() { Async<T2> target = target_volatile; if(target==null) return "Async:Pending"; else return target.toString(); } @Override public Result<T2> pollResult() { Async<T2> target = target_volatile; if(target==null) return null; else return target.pollResult(); } @Override public void onCompletion(Consumer<Result<T2>> callback) { callback = _Asyncs.bindToCurrExec(callback); Pending<?,T2> pending; if((pending=pending_volatile)!=null) { synchronized (pending) { if((pending=pending_volatile)!=null) { pending.callbacks = CallbackList.concat(pending.callbacks, callback); return; } } } Async<T2> target = target_volatile; target.onCompletion(callback); } @Override public void cancel(Exception reason) { Pending<?,T2> pending; if((pending=pending_volatile)!=null) { synchronized (pending) { if((pending=pending_volatile)!=null) { if(pending.cancelReason!=null) return; pending.cancelReason = reason; // will do async1.cancel(reason); } } } Async<?> cancelTarget; if(pending!=null) cancelTarget = pending.async1; else cancelTarget = target_volatile; // direct cancelTarget.cancel() may cause deep stack. so do it async-ly Fiber.currentExecutor().execute(() -> cancelTarget.cancel(reason)); } }
113811_4
package com.jmd.util; import java.util.ArrayList; import java.util.List; import com.jmd.entity.geo.Bound; import com.jmd.entity.geo.LngLatPoint; import com.jmd.entity.geo.MercatorPoint; import com.jmd.entity.geo.Polygon; import com.jmd.entity.geo.Tile; public class GeoUtils { // 卫星椭球坐标投影到平面坐标系的投影因子 private static final double A = 6378245.0; // 椭球的偏心率 private static final double EE = 0.00669342162296594323; // 容差 private static final double PRECISION = 2e-10; // 默认2e-10 /** * MAX_MERC = 20037508.3427892;<br> * minMerc = -20037508.3427892;<br> * 经纬度为[0,0]时墨卡托坐标为[0,0]<br> * MAX_MERC对应纬度180<br> * MIN_MERC对应纬度-180<br> * 墨卡托投影图左上角,即[x:0,y:0]左上角,坐标为[minMerc,MAX_MERC]<br> * 墨卡托投影图右上角,即[x:m,y:0]右上角,坐标为[MAX_MERC,MAX_MERC]<br> * 墨卡托投影图左下角,即[x:0,y:m]左下角,坐标为[minMerc,minMerc]<br> * 墨卡托投影图右下角,即[x:m,y:m]右下角,坐标为[MAX_MERC,minMerc]<br> * [-20037508,20037508]----------------[20037508,20037508]<br> * -------------------------------------------------------<br> * -------------------------[0,0]-------------------------<br> * -------------------------------------------------------<br> * [-20037508,-20037508]--------------[20037508,-20037508]<br> * 为了方便计算,算法中使用如下坐标系<br> * [0,0]--------------------------------------[40075016,0]<br> * -------------------------------------------------------<br> * ------------------[20037508,20037508]------------------<br> * -------------------------------------------------------<br> * [0,40075016]------------------------[40075016,40075016]<br> * 自定义坐标系转TSM坐标系方法:<br> * Ty = MAX_MERC - y<br> * Tx = x - MAX_MERC<br> * TSM坐标系转自定义坐标系方法:<br> * y = MAX_MERC - Ty<br> * x = Tx + MAX_MERC<br> */ public static final double MAX_MERC = 20037508.3427892; /** 经纬度转墨卡托 */ public static MercatorPoint LngLat2Mercator(LngLatPoint point) { double x = point.getLng() * MAX_MERC / 180; double y = Math.log(Math.tan((90 + point.getLat()) * Math.PI / 360)) / (Math.PI / 180); y = y * MAX_MERC / 180; return new MercatorPoint(x, y); } /** 墨卡托转经纬度 */ public static LngLatPoint Mercator2LngLat(MercatorPoint point) { double x = point.getLng() / MAX_MERC * 180; double y = point.getLat() / MAX_MERC * 180; y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2); return new LngLatPoint(x, y); } /** 通过XYZ获取Tile实例 */ public static Tile getTile(int z, int x, int y) { Tile tile = new Tile(); tile.setZ(z); tile.setX(x); tile.setY(y); int count = (int) Math.pow(2, z); double each = MAX_MERC / ((double) count / 2); double each_x = each * x; double each_x_1 = each * (x + 1); double each_y = each * y; double each_y_1 = each * (y + 1); tile.setTopLeft(new MercatorPoint(each_x - MAX_MERC, MAX_MERC - each_y)); tile.setTopRight(new MercatorPoint(each_x_1 - MAX_MERC, MAX_MERC - each_y)); tile.setBottomLeft(new MercatorPoint(each_x - MAX_MERC, MAX_MERC - each_y_1)); tile.setBottomRight(new MercatorPoint(each_x_1 - MAX_MERC, MAX_MERC - each_y_1)); return tile; } /** 通过墨卡托坐标获取Tile实例 */ public static Tile getTile(int zoom, MercatorPoint point) { double cx = point.getLng() + MAX_MERC; double cy = MAX_MERC - point.getLat(); int count = (int) Math.pow(2, zoom); double each = MAX_MERC / ((double) count / 2); int count_x = (int) Math.floor(cx / each); int count_y = (int) Math.floor(cy / each); Tile tile = getTile(zoom, count_x, count_y); return tile; } /** 通过经纬度坐标获取Tile实例 */ public static Tile getTile(int zoom, LngLatPoint point) { return getTile(zoom, LngLat2Mercator(point)); } /** 获取多边形bounds */ public static Bound getPolygonBound(Polygon polygon) { Bound bound = new Bound(); Double minX = null, minY = null, maxX = null, maxY = null; for (MercatorPoint point : polygon.getPath()) { minX = minX != null ? (minX > point.getLng() ? point.getLng() : minX) : point.getLng(); minY = minY != null ? (minY > point.getLat() ? point.getLat() : minY) : point.getLat(); maxX = maxX != null ? (maxX < point.getLng() ? point.getLng() : maxX) : point.getLng(); maxY = maxY != null ? (maxY < point.getLat() ? point.getLat() : maxY) : point.getLat(); } bound.setTopLeft(new MercatorPoint(minX, maxY)); bound.setTopRight(new MercatorPoint(maxX, maxY)); bound.setBottomLeft(new MercatorPoint(minX, minY)); bound.setBottomRight(new MercatorPoint(maxX, minY)); return bound; } /** 获取多边形bounds(多个) */ public static Bound getPolygonsBound(List<Polygon> polygons) { Bound bound = new Bound(); Double minX = null, minY = null, maxX = null, maxY = null; for (Polygon polygon : polygons) { for (MercatorPoint point : polygon.getPath()) { minX = minX != null ? (minX > point.getLng() ? point.getLng() : minX) : point.getLng(); minY = minY != null ? (minY > point.getLat() ? point.getLat() : minY) : point.getLat(); maxX = maxX != null ? (maxX < point.getLng() ? point.getLng() : maxX) : point.getLng(); maxY = maxY != null ? (maxY < point.getLat() ? point.getLat() : maxY) : point.getLat(); } } bound.setTopLeft(new MercatorPoint(minX, maxY)); bound.setTopRight(new MercatorPoint(maxX, maxY)); bound.setBottomLeft(new MercatorPoint(minX, minY)); bound.setBottomRight(new MercatorPoint(maxX, minY)); return bound; } /** 判断瓦片图是否在多边形内 */ public static boolean isTileInPolygon(Tile tile, Polygon polygon) { return isPointInPolygon(tile.getTopLeft(), polygon) || isPointInPolygon(tile.getTopRight(), polygon) || isPointInPolygon(tile.getBottomLeft(), polygon) || isPointInPolygon(tile.getBottomRight(), polygon); } /** 判断多边形是否在瓦片图区块内 */ public static boolean isPolygonInTile(Tile tile, Polygon polygon) { ArrayList<MercatorPoint> path = new ArrayList<MercatorPoint>(); path.add(tile.getTopLeft()); path.add(tile.getTopRight()); path.add(tile.getBottomRight()); path.add(tile.getBottomLeft()); Polygon tilePolygon = new Polygon(path); for (MercatorPoint point : polygon.getPath()) { if (isPointInPolygon(point, tilePolygon)) { return true; } } return false; } /** 判断点是否在多边形内 */ /** 提取自百度地图API */ public static boolean isPointInPolygon(MercatorPoint markerPoint, Polygon polygon) { // 下述代码来源:http://paulbourke.net/geometry/insidepoly/,进行了部分修改 // 基本思想是利用射线法,计算射线与多边形各边的交点,如果是偶数,则点在多边形外,否则 // 在多边形内。还会考虑一些特殊情况,如点在多边形顶点上,点在多边形边上等特殊情况。 int N = polygon.getPath().size(); boolean boundOrVertex = true; // 如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true int intersectCount = 0; // cross points count of x double precision = PRECISION; // 浮点类型计算时候与0比较时候的容差 MercatorPoint p1, p2; // neighbour bound vertices MercatorPoint p = markerPoint; // 测试点 p1 = polygon.getPath().get(0); // left vertex for (int i = 1; i <= N; ++i) { // check all rays if (p.equals(p1)) { return boundOrVertex; // p is an vertex } p2 = polygon.getPath().get(i % N); // right vertex // ray is outside of our interests if (p.getLat() < Math.min(p1.getLat(), p2.getLat()) || p.getLat() > Math.max(p1.getLat(), p2.getLat())) { p1 = p2; continue; // next ray left point } // ray is crossing over by the algorithm (common part of) if (p.getLat() > Math.min(p1.getLat(), p2.getLat()) && p.getLat() < Math.max(p1.getLat(), p2.getLat())) { // x is before of ray if (p.getLng() <= Math.max(p1.getLng(), p2.getLng())) { // overlies on a horizontal ray if (p1.getLat() == p2.getLat() && p.getLng() >= Math.min(p1.getLng(), p2.getLng())) { return boundOrVertex; } if (p1.getLng() == p2.getLng()) { // ray is vertical if (p1.getLng() == p.getLng()) { // overlies on a vertical ray return boundOrVertex; } else { // before ray ++intersectCount; } } else { // cross point on the left side // cross point of lng double xinters = (p.getLat() - p1.getLat()) * (p2.getLng() - p1.getLng()) / (p2.getLat() - p1.getLat()) + p1.getLng(); // overlies on a ray if (Math.abs(p.getLng() - xinters) < precision) { return boundOrVertex; } if (p.getLng() < xinters) { // before ray ++intersectCount; } } } } else { // special case when ray is crossing through the vertex if (p.getLat() == p2.getLat() && p.getLng() <= p2.getLng()) { // p crossing over p2 MercatorPoint p3 = polygon.getPath().get((i + 1) % N); // next vertex if (p.getLat() >= Math.min(p1.getLat(), p3.getLat()) && p.getLat() <= Math.max(p1.getLat(), p3.getLat())) { // p.lat lies between p1.lat & p3.lat ++intersectCount; } else { intersectCount += 2; } } } p1 = p2; // next ray left point } if (intersectCount % 2 == 0) { // 偶数在多边形外 return false; } else { // 奇数在多边形内 return true; } } /** XYZ转必应坐标 */ public static String xyz2Bing(int _z, int _x, int _y) { StringBuffer result = new StringBuffer(); double x = _x + 1; double y = _y + 1; int z_all = (int) Math.pow(2, _z); for (int i = 1; i <= _z; i++) { double z0 = z_all / Math.pow(2, i - 1); // 左上 if (x / z0 <= 0.5 && y / z0 <= 0.5) { result.append("0"); } // 右上 if (x / z0 > 0.5 && y / z0 <= 0.5) { result.append("1"); x = x - z0 / 2; } // 左下 if (x / z0 <= 0.5 && y / z0 > 0.5) { result.append("2"); y = y - z0 / 2; } // 右下 if (x / z0 > 0.5 && y / z0 > 0.5) { result.append("3"); x = x - z0 / 2; y = y - z0 / 2; } } return result.toString(); } /** 是否超出中国范围 */ private static boolean outOfChina(LngLatPoint pt) { double lat = +pt.getLat(); double lng = +pt.getLng(); // 纬度3.86~53.55,经度73.66~135.05 return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55); } /** WGS84坐标转GCJ02坐标 */ public static LngLatPoint wgs84_To_gcj02(LngLatPoint pt) { double lng = pt.getLng(); double lat = pt.getLat(); if (outOfChina(pt)) { return pt; } else { double dLat = transformLat(lng - 105.0, lat - 35.0); double dLng = transformLng(lng - 105.0, lat - 35.0); double radLat = lat / 180.0 * Math.PI; double magic = Math.sin(radLat); magic = 1 - EE * magic * magic; double sqrtMagic = Math.sqrt(magic); dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * Math.PI); dLng = (dLng * 180.0) / (A / sqrtMagic * Math.cos(radLat) * Math.PI); double mgLat = lat + dLat; double mgLng = lng + dLng; return new LngLatPoint(mgLng, mgLat); } } /** GCJ02坐标转WGS84坐标 */ public static LngLatPoint gcj02_To_wgs84(LngLatPoint pt) { double lng = pt.getLng(); double lat = pt.getLat(); if (outOfChina(pt)) { return pt; } else { double dlat = transformLat(lng - 105.0, lat - 35.0); double dlng = transformLng(lng - 105.0, lat - 35.0); double radlat = lat / 180.0 * Math.PI; double magic = Math.sin(radlat); magic = 1 - EE * magic * magic; double sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((A * (1 - EE)) / (magic * sqrtmagic) * Math.PI); dlng = (dlng * 180.0) / (A / sqrtmagic * Math.cos(radlat) * Math.PI); double mglat = lat + dlat; double mglng = lng + dlng; return new LngLatPoint(lng * 2 - mglng, lat * 2 - mglat); } } private static double transformLat(double lat, double lng) { double ret = -100.0 + 2.0 * lat + 3.0 * lng + 0.2 * lng * lng + 0.1 * lat * lng + 0.2 * Math.sqrt(Math.abs(lat)); ret += (20.0 * Math.sin(6.0 * lat * Math.PI) + 20.0 * Math.sin(2.0 * lat * Math.PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lng * Math.PI) + 40.0 * Math.sin(lng / 3.0 * Math.PI)) * 2.0 / 3.0; ret += (160.0 * Math.sin(lng / 12.0 * Math.PI) + 320 * Math.sin(lng * Math.PI / 30.0)) * 2.0 / 3.0; return ret; } private static double transformLng(double lat, double lng) { double ret = 300.0 + lat + 2.0 * lng + 0.1 * lat * lat + 0.1 * lat * lng + 0.1 * Math.sqrt(Math.abs(lat)); ret += (20.0 * Math.sin(6.0 * lat * Math.PI) + 20.0 * Math.sin(2.0 * lat * Math.PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lat * Math.PI) + 40.0 * Math.sin(lat / 3.0 * Math.PI)) * 2.0 / 3.0; ret += (150.0 * Math.sin(lat / 12.0 * Math.PI) + 300.0 * Math.sin(lat / 30.0 * Math.PI)) * 2.0 / 3.0; return ret; } }
zhou-fuyi/java_map_download
Code/src/main/java/com/jmd/util/GeoUtils.java
5,138
// p is an vertex
line_comment
nl
package com.jmd.util; import java.util.ArrayList; import java.util.List; import com.jmd.entity.geo.Bound; import com.jmd.entity.geo.LngLatPoint; import com.jmd.entity.geo.MercatorPoint; import com.jmd.entity.geo.Polygon; import com.jmd.entity.geo.Tile; public class GeoUtils { // 卫星椭球坐标投影到平面坐标系的投影因子 private static final double A = 6378245.0; // 椭球的偏心率 private static final double EE = 0.00669342162296594323; // 容差 private static final double PRECISION = 2e-10; // 默认2e-10 /** * MAX_MERC = 20037508.3427892;<br> * minMerc = -20037508.3427892;<br> * 经纬度为[0,0]时墨卡托坐标为[0,0]<br> * MAX_MERC对应纬度180<br> * MIN_MERC对应纬度-180<br> * 墨卡托投影图左上角,即[x:0,y:0]左上角,坐标为[minMerc,MAX_MERC]<br> * 墨卡托投影图右上角,即[x:m,y:0]右上角,坐标为[MAX_MERC,MAX_MERC]<br> * 墨卡托投影图左下角,即[x:0,y:m]左下角,坐标为[minMerc,minMerc]<br> * 墨卡托投影图右下角,即[x:m,y:m]右下角,坐标为[MAX_MERC,minMerc]<br> * [-20037508,20037508]----------------[20037508,20037508]<br> * -------------------------------------------------------<br> * -------------------------[0,0]-------------------------<br> * -------------------------------------------------------<br> * [-20037508,-20037508]--------------[20037508,-20037508]<br> * 为了方便计算,算法中使用如下坐标系<br> * [0,0]--------------------------------------[40075016,0]<br> * -------------------------------------------------------<br> * ------------------[20037508,20037508]------------------<br> * -------------------------------------------------------<br> * [0,40075016]------------------------[40075016,40075016]<br> * 自定义坐标系转TSM坐标系方法:<br> * Ty = MAX_MERC - y<br> * Tx = x - MAX_MERC<br> * TSM坐标系转自定义坐标系方法:<br> * y = MAX_MERC - Ty<br> * x = Tx + MAX_MERC<br> */ public static final double MAX_MERC = 20037508.3427892; /** 经纬度转墨卡托 */ public static MercatorPoint LngLat2Mercator(LngLatPoint point) { double x = point.getLng() * MAX_MERC / 180; double y = Math.log(Math.tan((90 + point.getLat()) * Math.PI / 360)) / (Math.PI / 180); y = y * MAX_MERC / 180; return new MercatorPoint(x, y); } /** 墨卡托转经纬度 */ public static LngLatPoint Mercator2LngLat(MercatorPoint point) { double x = point.getLng() / MAX_MERC * 180; double y = point.getLat() / MAX_MERC * 180; y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2); return new LngLatPoint(x, y); } /** 通过XYZ获取Tile实例 */ public static Tile getTile(int z, int x, int y) { Tile tile = new Tile(); tile.setZ(z); tile.setX(x); tile.setY(y); int count = (int) Math.pow(2, z); double each = MAX_MERC / ((double) count / 2); double each_x = each * x; double each_x_1 = each * (x + 1); double each_y = each * y; double each_y_1 = each * (y + 1); tile.setTopLeft(new MercatorPoint(each_x - MAX_MERC, MAX_MERC - each_y)); tile.setTopRight(new MercatorPoint(each_x_1 - MAX_MERC, MAX_MERC - each_y)); tile.setBottomLeft(new MercatorPoint(each_x - MAX_MERC, MAX_MERC - each_y_1)); tile.setBottomRight(new MercatorPoint(each_x_1 - MAX_MERC, MAX_MERC - each_y_1)); return tile; } /** 通过墨卡托坐标获取Tile实例 */ public static Tile getTile(int zoom, MercatorPoint point) { double cx = point.getLng() + MAX_MERC; double cy = MAX_MERC - point.getLat(); int count = (int) Math.pow(2, zoom); double each = MAX_MERC / ((double) count / 2); int count_x = (int) Math.floor(cx / each); int count_y = (int) Math.floor(cy / each); Tile tile = getTile(zoom, count_x, count_y); return tile; } /** 通过经纬度坐标获取Tile实例 */ public static Tile getTile(int zoom, LngLatPoint point) { return getTile(zoom, LngLat2Mercator(point)); } /** 获取多边形bounds */ public static Bound getPolygonBound(Polygon polygon) { Bound bound = new Bound(); Double minX = null, minY = null, maxX = null, maxY = null; for (MercatorPoint point : polygon.getPath()) { minX = minX != null ? (minX > point.getLng() ? point.getLng() : minX) : point.getLng(); minY = minY != null ? (minY > point.getLat() ? point.getLat() : minY) : point.getLat(); maxX = maxX != null ? (maxX < point.getLng() ? point.getLng() : maxX) : point.getLng(); maxY = maxY != null ? (maxY < point.getLat() ? point.getLat() : maxY) : point.getLat(); } bound.setTopLeft(new MercatorPoint(minX, maxY)); bound.setTopRight(new MercatorPoint(maxX, maxY)); bound.setBottomLeft(new MercatorPoint(minX, minY)); bound.setBottomRight(new MercatorPoint(maxX, minY)); return bound; } /** 获取多边形bounds(多个) */ public static Bound getPolygonsBound(List<Polygon> polygons) { Bound bound = new Bound(); Double minX = null, minY = null, maxX = null, maxY = null; for (Polygon polygon : polygons) { for (MercatorPoint point : polygon.getPath()) { minX = minX != null ? (minX > point.getLng() ? point.getLng() : minX) : point.getLng(); minY = minY != null ? (minY > point.getLat() ? point.getLat() : minY) : point.getLat(); maxX = maxX != null ? (maxX < point.getLng() ? point.getLng() : maxX) : point.getLng(); maxY = maxY != null ? (maxY < point.getLat() ? point.getLat() : maxY) : point.getLat(); } } bound.setTopLeft(new MercatorPoint(minX, maxY)); bound.setTopRight(new MercatorPoint(maxX, maxY)); bound.setBottomLeft(new MercatorPoint(minX, minY)); bound.setBottomRight(new MercatorPoint(maxX, minY)); return bound; } /** 判断瓦片图是否在多边形内 */ public static boolean isTileInPolygon(Tile tile, Polygon polygon) { return isPointInPolygon(tile.getTopLeft(), polygon) || isPointInPolygon(tile.getTopRight(), polygon) || isPointInPolygon(tile.getBottomLeft(), polygon) || isPointInPolygon(tile.getBottomRight(), polygon); } /** 判断多边形是否在瓦片图区块内 */ public static boolean isPolygonInTile(Tile tile, Polygon polygon) { ArrayList<MercatorPoint> path = new ArrayList<MercatorPoint>(); path.add(tile.getTopLeft()); path.add(tile.getTopRight()); path.add(tile.getBottomRight()); path.add(tile.getBottomLeft()); Polygon tilePolygon = new Polygon(path); for (MercatorPoint point : polygon.getPath()) { if (isPointInPolygon(point, tilePolygon)) { return true; } } return false; } /** 判断点是否在多边形内 */ /** 提取自百度地图API */ public static boolean isPointInPolygon(MercatorPoint markerPoint, Polygon polygon) { // 下述代码来源:http://paulbourke.net/geometry/insidepoly/,进行了部分修改 // 基本思想是利用射线法,计算射线与多边形各边的交点,如果是偶数,则点在多边形外,否则 // 在多边形内。还会考虑一些特殊情况,如点在多边形顶点上,点在多边形边上等特殊情况。 int N = polygon.getPath().size(); boolean boundOrVertex = true; // 如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true int intersectCount = 0; // cross points count of x double precision = PRECISION; // 浮点类型计算时候与0比较时候的容差 MercatorPoint p1, p2; // neighbour bound vertices MercatorPoint p = markerPoint; // 测试点 p1 = polygon.getPath().get(0); // left vertex for (int i = 1; i <= N; ++i) { // check all rays if (p.equals(p1)) { return boundOrVertex; // p is<SUF> } p2 = polygon.getPath().get(i % N); // right vertex // ray is outside of our interests if (p.getLat() < Math.min(p1.getLat(), p2.getLat()) || p.getLat() > Math.max(p1.getLat(), p2.getLat())) { p1 = p2; continue; // next ray left point } // ray is crossing over by the algorithm (common part of) if (p.getLat() > Math.min(p1.getLat(), p2.getLat()) && p.getLat() < Math.max(p1.getLat(), p2.getLat())) { // x is before of ray if (p.getLng() <= Math.max(p1.getLng(), p2.getLng())) { // overlies on a horizontal ray if (p1.getLat() == p2.getLat() && p.getLng() >= Math.min(p1.getLng(), p2.getLng())) { return boundOrVertex; } if (p1.getLng() == p2.getLng()) { // ray is vertical if (p1.getLng() == p.getLng()) { // overlies on a vertical ray return boundOrVertex; } else { // before ray ++intersectCount; } } else { // cross point on the left side // cross point of lng double xinters = (p.getLat() - p1.getLat()) * (p2.getLng() - p1.getLng()) / (p2.getLat() - p1.getLat()) + p1.getLng(); // overlies on a ray if (Math.abs(p.getLng() - xinters) < precision) { return boundOrVertex; } if (p.getLng() < xinters) { // before ray ++intersectCount; } } } } else { // special case when ray is crossing through the vertex if (p.getLat() == p2.getLat() && p.getLng() <= p2.getLng()) { // p crossing over p2 MercatorPoint p3 = polygon.getPath().get((i + 1) % N); // next vertex if (p.getLat() >= Math.min(p1.getLat(), p3.getLat()) && p.getLat() <= Math.max(p1.getLat(), p3.getLat())) { // p.lat lies between p1.lat & p3.lat ++intersectCount; } else { intersectCount += 2; } } } p1 = p2; // next ray left point } if (intersectCount % 2 == 0) { // 偶数在多边形外 return false; } else { // 奇数在多边形内 return true; } } /** XYZ转必应坐标 */ public static String xyz2Bing(int _z, int _x, int _y) { StringBuffer result = new StringBuffer(); double x = _x + 1; double y = _y + 1; int z_all = (int) Math.pow(2, _z); for (int i = 1; i <= _z; i++) { double z0 = z_all / Math.pow(2, i - 1); // 左上 if (x / z0 <= 0.5 && y / z0 <= 0.5) { result.append("0"); } // 右上 if (x / z0 > 0.5 && y / z0 <= 0.5) { result.append("1"); x = x - z0 / 2; } // 左下 if (x / z0 <= 0.5 && y / z0 > 0.5) { result.append("2"); y = y - z0 / 2; } // 右下 if (x / z0 > 0.5 && y / z0 > 0.5) { result.append("3"); x = x - z0 / 2; y = y - z0 / 2; } } return result.toString(); } /** 是否超出中国范围 */ private static boolean outOfChina(LngLatPoint pt) { double lat = +pt.getLat(); double lng = +pt.getLng(); // 纬度3.86~53.55,经度73.66~135.05 return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55); } /** WGS84坐标转GCJ02坐标 */ public static LngLatPoint wgs84_To_gcj02(LngLatPoint pt) { double lng = pt.getLng(); double lat = pt.getLat(); if (outOfChina(pt)) { return pt; } else { double dLat = transformLat(lng - 105.0, lat - 35.0); double dLng = transformLng(lng - 105.0, lat - 35.0); double radLat = lat / 180.0 * Math.PI; double magic = Math.sin(radLat); magic = 1 - EE * magic * magic; double sqrtMagic = Math.sqrt(magic); dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * Math.PI); dLng = (dLng * 180.0) / (A / sqrtMagic * Math.cos(radLat) * Math.PI); double mgLat = lat + dLat; double mgLng = lng + dLng; return new LngLatPoint(mgLng, mgLat); } } /** GCJ02坐标转WGS84坐标 */ public static LngLatPoint gcj02_To_wgs84(LngLatPoint pt) { double lng = pt.getLng(); double lat = pt.getLat(); if (outOfChina(pt)) { return pt; } else { double dlat = transformLat(lng - 105.0, lat - 35.0); double dlng = transformLng(lng - 105.0, lat - 35.0); double radlat = lat / 180.0 * Math.PI; double magic = Math.sin(radlat); magic = 1 - EE * magic * magic; double sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((A * (1 - EE)) / (magic * sqrtmagic) * Math.PI); dlng = (dlng * 180.0) / (A / sqrtmagic * Math.cos(radlat) * Math.PI); double mglat = lat + dlat; double mglng = lng + dlng; return new LngLatPoint(lng * 2 - mglng, lat * 2 - mglat); } } private static double transformLat(double lat, double lng) { double ret = -100.0 + 2.0 * lat + 3.0 * lng + 0.2 * lng * lng + 0.1 * lat * lng + 0.2 * Math.sqrt(Math.abs(lat)); ret += (20.0 * Math.sin(6.0 * lat * Math.PI) + 20.0 * Math.sin(2.0 * lat * Math.PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lng * Math.PI) + 40.0 * Math.sin(lng / 3.0 * Math.PI)) * 2.0 / 3.0; ret += (160.0 * Math.sin(lng / 12.0 * Math.PI) + 320 * Math.sin(lng * Math.PI / 30.0)) * 2.0 / 3.0; return ret; } private static double transformLng(double lat, double lng) { double ret = 300.0 + lat + 2.0 * lng + 0.1 * lat * lat + 0.1 * lat * lng + 0.1 * Math.sqrt(Math.abs(lat)); ret += (20.0 * Math.sin(6.0 * lat * Math.PI) + 20.0 * Math.sin(2.0 * lat * Math.PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lat * Math.PI) + 40.0 * Math.sin(lat / 3.0 * Math.PI)) * 2.0 / 3.0; ret += (150.0 * Math.sin(lat / 12.0 * Math.PI) + 300.0 * Math.sin(lat / 30.0 * Math.PI)) * 2.0 / 3.0; return ret; } }
204421_45
/* * Copyright (c) 2016 Martin Davis. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html * and the Eclipse Distribution License is available at * * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.locationtech.jts.operation.buffer; import org.locationtech.jts.algorithm.Angle; import org.locationtech.jts.algorithm.HCoordinate; import org.locationtech.jts.algorithm.Intersection; import org.locationtech.jts.algorithm.LineIntersector; import org.locationtech.jts.algorithm.NotRepresentableException; import org.locationtech.jts.algorithm.Orientation; import org.locationtech.jts.algorithm.RobustLineIntersector; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.LineSegment; import org.locationtech.jts.geom.PrecisionModel; import org.locationtech.jts.geomgraph.Position; /** * Generates segments which form an offset curve. * Supports all end cap and join options * provided for buffering. * This algorithm implements various heuristics to * produce smoother, simpler curves which are * still within a reasonable tolerance of the * true curve. * * @author Martin Davis * */ class OffsetSegmentGenerator { /** * Factor which controls how close offset segments can be to * skip adding a filler or mitre. */ private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices on inside turns can be to be snapped */ private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices can be to be snapped */ private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6; /** * Factor which determines how short closing segs can be for round buffers */ private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80; /** * the max error of approximation (distance) between a quad segment and the true fillet curve */ private double maxCurveSegmentError = 0.0; /** * The angle quantum with which to approximate a fillet curve * (based on the input # of quadrant segments) */ private double filletAngleQuantum; /** * The Closing Segment Length Factor controls how long * "closing segments" are. Closing segments are added * at the middle of inside corners to ensure a smoother * boundary for the buffer offset curve. * In some cases (particularly for round joins with default-or-better * quantization) the closing segments can be made quite short. * This substantially improves performance (due to fewer intersections being created). * * A closingSegFactor of 0 results in lines to the corner vertex * A closingSegFactor of 1 results in lines halfway to the corner vertex * A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex * (this option is reasonable for the very common default situation of round joins * and quadrantSegs >= 8) */ private int closingSegLengthFactor = 1; private OffsetSegmentString segList; private double distance = 0.0; private PrecisionModel precisionModel; private BufferParameters bufParams; private LineIntersector li; private Coordinate s0, s1, s2; private LineSegment seg0 = new LineSegment(); private LineSegment seg1 = new LineSegment(); private LineSegment offset0 = new LineSegment(); private LineSegment offset1 = new LineSegment(); private int side = 0; private boolean hasNarrowConcaveAngle = false; public OffsetSegmentGenerator(PrecisionModel precisionModel, BufferParameters bufParams, double distance) { this.precisionModel = precisionModel; this.bufParams = bufParams; // compute intersections in full precision, to provide accuracy // the points are rounded as they are inserted into the curve line li = new RobustLineIntersector(); filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments(); /** * Non-round joins cause issues with short closing segments, so don't use * them. In any case, non-round joins only really make sense for relatively * small buffer distances. */ if (bufParams.getQuadrantSegments() >= 8 && bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND) closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR; init(distance); } /** * Tests whether the input has a narrow concave angle * (relative to the offset distance). * In this case the generated offset curve will contain self-intersections * and heuristic closing segments. * This is expected behaviour in the case of Buffer curves. * For pure Offset Curves, * the output needs to be further treated * before it can be used. * * @return true if the input has a narrow concave angle */ public boolean hasNarrowConcaveAngle() { return hasNarrowConcaveAngle; } private void init(double distance) { this.distance = distance; maxCurveSegmentError = distance * (1 - Math.cos(filletAngleQuantum / 2.0)); segList = new OffsetSegmentString(); segList.setPrecisionModel(precisionModel); /** * Choose the min vertex separation as a small fraction of the offset distance. */ segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR); } public void initSideSegments(Coordinate s1, Coordinate s2, int side) { this.s1 = s1; this.s2 = s2; this.side = side; seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); } public Coordinate[] getCoordinates() { Coordinate[] pts = segList.getCoordinates(); return pts; } public void closeRing() { segList.closeRing(); } public void addSegments(Coordinate[] pt, boolean isForward) { segList.addPts(pt, isForward); } public void addFirstSegment() { segList.addPt(offset1.p0); } /** * Add last offset point */ public void addLastSegment() { segList.addPt(offset1.p1); } //private static double MAX_CLOSING_SEG_LEN = 3.0; public void addNextSegment(Coordinate p, boolean addStartPoint) { // s0-s1-s2 are the coordinates of the previous segment and the current one s0 = s1; s1 = s2; s2 = p; seg0.setCoordinates(s0, s1); computeOffsetSegment(seg0, side, distance, offset0); seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); // do nothing if points are equal if (s1.equals(s2)) return; int orientation = Orientation.index(s0, s1, s2); boolean outsideTurn = (orientation == Orientation.CLOCKWISE && side == Position.LEFT) || (orientation == Orientation.COUNTERCLOCKWISE && side == Position.RIGHT); if (orientation == 0) { // lines are collinear addCollinear(addStartPoint); } else if (outsideTurn) { addOutsideTurn(orientation, addStartPoint); } else { // inside turn addInsideTurn(orientation, addStartPoint); } } private void addCollinear(boolean addStartPoint) { /** * This test could probably be done more efficiently, * but the situation of exact collinearity should be fairly rare. */ li.computeIntersection(s0, s1, s1, s2); int numInt = li.getIntersectionNum(); /** * if numInt is < 2, the lines are parallel and in the same direction. In * this case the point can be ignored, since the offset lines will also be * parallel. */ if (numInt >= 2) { /** * segments are collinear but reversing. * Add an "end-cap" fillet * all the way around to other direction This case should ONLY happen * for LineStrings, so the orientation is always CW. (Polygons can never * have two consecutive segments which are parallel but reversed, * because that would be a self intersection. * */ if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL || bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { if (addStartPoint) segList.addPt(offset0.p1); segList.addPt(offset1.p0); } else { addCornerFillet(s1, offset0.p1, offset1.p0, Orientation.CLOCKWISE, distance); } } } /** * Adds the offset points for an outside (convex) turn * * @param orientation * @param addStartPoint */ private void addOutsideTurn(int orientation, boolean addStartPoint) { /** * Heuristic: If offset endpoints are very close together, * just use one of them as the corner vertex. * This avoids problems with computing mitre corners in the case * where the two segments are almost parallel * (which is hard to compute a robust intersection for). */ if (offset0.p1.distance(offset1.p0) < distance * OFFSET_SEGMENT_SEPARATION_FACTOR) { segList.addPt(offset0.p1); return; } if (bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { addMitreJoin(s1, offset0, offset1, distance); } else if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL){ addBevelJoin(offset0, offset1); } else { // add a circular fillet connecting the endpoints of the offset segments if (addStartPoint) segList.addPt(offset0.p1); // TESTING - comment out to produce beveled joins addCornerFillet(s1, offset0.p1, offset1.p0, orientation, distance); segList.addPt(offset1.p0); } } /** * Adds the offset points for an inside (concave) turn. * * @param orientation * @param addStartPoint */ private void addInsideTurn(int orientation, boolean addStartPoint) { /** * add intersection point of offset segments (if any) */ li.computeIntersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (li.hasIntersection()) { segList.addPt(li.getIntersection(0)); } else { /** * If no intersection is detected, * it means the angle is so small and/or the offset so * large that the offsets segments don't intersect. * In this case we must * add a "closing segment" to make sure the buffer curve is continuous, * fairly smooth (e.g. no sharp reversals in direction) * and tracks the buffer correctly around the corner. The curve connects * the endpoints of the segment offsets to points * which lie toward the centre point of the corner. * The joining curve will not appear in the final buffer outline, since it * is completely internal to the buffer polygon. * * In complex buffer cases the closing segment may cut across many other * segments in the generated offset curve. In order to improve the * performance of the noding, the closing segment should be kept as short as possible. * (But not too short, since that would defeat its purpose). * This is the purpose of the closingSegFactor heuristic value. */ /** * The intersection test above is vulnerable to robustness errors; i.e. it * may be that the offsets should intersect very close to their endpoints, * but aren't reported as such due to rounding. To handle this situation * appropriately, we use the following test: If the offset points are very * close, don't add closing segments but simply use one of the offset * points */ hasNarrowConcaveAngle = true; //System.out.println("NARROW ANGLE - distance = " + distance); if (offset0.p1.distance(offset1.p0) < distance * INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) { segList.addPt(offset0.p1); } else { // add endpoint of this segment offset segList.addPt(offset0.p1); /** * Add "closing segment" of required length. */ if (closingSegLengthFactor > 0) { Coordinate mid0 = new Coordinate((closingSegLengthFactor * offset0.p1.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset0.p1.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid0); Coordinate mid1 = new Coordinate((closingSegLengthFactor*offset1.p0.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset1.p0.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid1); } else { /** * This branch is not expected to be used except for testing purposes. * It is equivalent to the JTS 1.9 logic for closing segments * (which results in very poor performance for large buffer distances) */ segList.addPt(s1); } //*/ // add start point of next segment offset segList.addPt(offset1.p0); } } } /** * Compute an offset segment for an input segment on a given side and at a given distance. * The offset points are computed in full double precision, for accuracy. * * @param seg the segment to offset * @param side the side of the segment ({@link Position}) the offset lies on * @param distance the offset distance * @param offset the points computed for the offset segment */ private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset) { int sideSign = side == Position.LEFT ? 1 : -1; double dx = seg.p1.x - seg.p0.x; double dy = seg.p1.y - seg.p0.y; double len = Math.sqrt(dx * dx + dy * dy); // u is the vector that is the length of the offset, in the direction of the segment double ux = sideSign * distance * dx / len; double uy = sideSign * distance * dy / len; offset.p0.x = seg.p0.x - uy; offset.p0.y = seg.p0.y + ux; offset.p1.x = seg.p1.x - uy; offset.p1.y = seg.p1.y + ux; } /** * Add an end cap around point p1, terminating a line segment coming from p0 */ public void addLineEndCap(Coordinate p0, Coordinate p1) { LineSegment seg = new LineSegment(p0, p1); LineSegment offsetL = new LineSegment(); computeOffsetSegment(seg, Position.LEFT, distance, offsetL); LineSegment offsetR = new LineSegment(); computeOffsetSegment(seg, Position.RIGHT, distance, offsetR); double dx = p1.x - p0.x; double dy = p1.y - p0.y; double angle = Math.atan2(dy, dx); switch (bufParams.getEndCapStyle()) { case BufferParameters.CAP_ROUND: // add offset seg points with a fillet between them segList.addPt(offsetL.p1); addDirectedFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, Orientation.CLOCKWISE, distance); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_FLAT: // only offset segment points are added segList.addPt(offsetL.p1); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_SQUARE: // add a square defined by extensions of the offset segment endpoints Coordinate squareCapSideOffset = new Coordinate(); squareCapSideOffset.x = Math.abs(distance) * Math.cos(angle); squareCapSideOffset.y = Math.abs(distance) * Math.sin(angle); Coordinate squareCapLOffset = new Coordinate( offsetL.p1.x + squareCapSideOffset.x, offsetL.p1.y + squareCapSideOffset.y); Coordinate squareCapROffset = new Coordinate( offsetR.p1.x + squareCapSideOffset.x, offsetR.p1.y + squareCapSideOffset.y); segList.addPt(squareCapLOffset); segList.addPt(squareCapROffset); break; } } /** * Adds a mitre join connecting the two reflex offset segments. * The mitre will be beveled if it exceeds the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance */ private void addMitreJoin(Coordinate p, LineSegment offset0, LineSegment offset1, double distance) { /** * This computation is unstable if the offset segments are nearly collinear. * However, this situation should have been eliminated earlier by the check * for whether the offset segment endpoints are almost coincident */ Coordinate intPt = Intersection.intersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (intPt != null) { double mitreRatio = distance <= 0.0 ? 1.0 : intPt.distance(p) / Math.abs(distance); if (mitreRatio <= bufParams.getMitreLimit()) { segList.addPt(intPt); return; } } // at this point either intersection failed or mitre limit was exceeded addLimitedMitreJoin(offset0, offset1, distance, bufParams.getMitreLimit()); // addBevelJoin(offset0, offset1); } /** * Adds a limited mitre join connecting the two reflex offset segments. * A limited mitre is a mitre which is beveled at the distance * determined by the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance * @param mitreLimit the mitre limit ratio */ private void addLimitedMitreJoin( LineSegment offset0, LineSegment offset1, double distance, double mitreLimit) { Coordinate basePt = seg0.p1; double ang0 = Angle.angle(basePt, seg0.p0); // oriented angle between segments double angDiff = Angle.angleBetweenOriented(seg0.p0, basePt, seg1.p1); // half of the interior angle double angDiffHalf = angDiff / 2; // angle for bisector of the interior angle between the segments double midAng = Angle.normalize(ang0 + angDiffHalf); // rotating this by PI gives the bisector of the reflex angle double mitreMidAng = Angle.normalize(midAng + Math.PI); // the miterLimit determines the distance to the mitre bevel double mitreDist = mitreLimit * distance; // the bevel delta is the difference between the buffer distance // and half of the length of the bevel segment double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf)); double bevelHalfLen = distance - bevelDelta; // compute the midpoint of the bevel segment double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng); double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng); Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY); // compute the mitre midline segment from the corner point to the bevel segment midpoint LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt); // finally the bevel segment endpoints are computed as offsets from // the mitre midline Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen); Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen); if (side == Position.LEFT) { segList.addPt(bevelEndLeft); segList.addPt(bevelEndRight); } else { segList.addPt(bevelEndRight); segList.addPt(bevelEndLeft); } } /** * Adds a bevel join connecting the two offset segments * around a reflex corner. * * @param offset0 the first offset segment * @param offset1 the second offset segment */ private void addBevelJoin( LineSegment offset0, LineSegment offset1) { segList.addPt(offset0.p1); segList.addPt(offset1.p0); } /** * Add points for a circular fillet around a reflex corner. * Adds the start and end points * * @param p base point of curve * @param p0 start point of fillet curve * @param p1 endpoint of fillet curve * @param direction the orientation of the fillet * @param radius the radius of the fillet */ private void addCornerFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius) { double dx0 = p0.x - p.x; double dy0 = p0.y - p.y; double startAngle = Math.atan2(dy0, dx0); double dx1 = p1.x - p.x; double dy1 = p1.y - p.y; double endAngle = Math.atan2(dy1, dx1); if (direction == Orientation.CLOCKWISE) { if (startAngle <= endAngle) startAngle += 2.0 * Math.PI; } else { // direction == COUNTERCLOCKWISE if (startAngle >= endAngle) startAngle -= 2.0 * Math.PI; } segList.addPt(p0); addDirectedFillet(p, startAngle, endAngle, direction, radius); segList.addPt(p1); } /** * Adds points for a circular fillet arc * between two specified angles. * The start and end point for the fillet are not added - * the caller must add them if required. * * @param direction is -1 for a CW angle, 1 for a CCW angle * @param radius the radius of the fillet */ private void addDirectedFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius) { int directionFactor = direction == Orientation.CLOCKWISE ? -1 : 1; double totalAngle = Math.abs(startAngle - endAngle); int nSegs = (int) (totalAngle / filletAngleQuantum + 0.5); if (nSegs < 1) return; // no segments because angle is less than increment - nothing to do! // choose angle increment so that each segment has equal length double angleInc = totalAngle / nSegs; Coordinate pt = new Coordinate(); for (int i = 0; i < nSegs; i++) { double angle = startAngle + directionFactor * i * angleInc; pt.x = p.x + radius * Math.cos(angle); pt.y = p.y + radius * Math.sin(angle); segList.addPt(pt); } } /** * Creates a CW circle around a point */ public void createCircle(Coordinate p) { // add start point Coordinate pt = new Coordinate(p.x + distance, p.y); segList.addPt(pt); addDirectedFillet(p, 0.0, 2.0 * Math.PI, -1, distance); segList.closeRing(); } /** * Creates a CW square around a point */ public void createSquare(Coordinate p) { segList.addPt(new Coordinate(p.x + distance, p.y + distance)); segList.addPt(new Coordinate(p.x + distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y + distance)); segList.closeRing(); } }
zhounice/jts
modules/core/src/main/java/org/locationtech/jts/operation/buffer/OffsetSegmentGenerator.java
7,113
// oriented angle between segments
line_comment
nl
/* * Copyright (c) 2016 Martin Davis. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * and Eclipse Distribution License v. 1.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html * and the Eclipse Distribution License is available at * * http://www.eclipse.org/org/documents/edl-v10.php. */ package org.locationtech.jts.operation.buffer; import org.locationtech.jts.algorithm.Angle; import org.locationtech.jts.algorithm.HCoordinate; import org.locationtech.jts.algorithm.Intersection; import org.locationtech.jts.algorithm.LineIntersector; import org.locationtech.jts.algorithm.NotRepresentableException; import org.locationtech.jts.algorithm.Orientation; import org.locationtech.jts.algorithm.RobustLineIntersector; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.LineSegment; import org.locationtech.jts.geom.PrecisionModel; import org.locationtech.jts.geomgraph.Position; /** * Generates segments which form an offset curve. * Supports all end cap and join options * provided for buffering. * This algorithm implements various heuristics to * produce smoother, simpler curves which are * still within a reasonable tolerance of the * true curve. * * @author Martin Davis * */ class OffsetSegmentGenerator { /** * Factor which controls how close offset segments can be to * skip adding a filler or mitre. */ private static final double OFFSET_SEGMENT_SEPARATION_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices on inside turns can be to be snapped */ private static final double INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-3; /** * Factor which controls how close curve vertices can be to be snapped */ private static final double CURVE_VERTEX_SNAP_DISTANCE_FACTOR = 1.0E-6; /** * Factor which determines how short closing segs can be for round buffers */ private static final int MAX_CLOSING_SEG_LEN_FACTOR = 80; /** * the max error of approximation (distance) between a quad segment and the true fillet curve */ private double maxCurveSegmentError = 0.0; /** * The angle quantum with which to approximate a fillet curve * (based on the input # of quadrant segments) */ private double filletAngleQuantum; /** * The Closing Segment Length Factor controls how long * "closing segments" are. Closing segments are added * at the middle of inside corners to ensure a smoother * boundary for the buffer offset curve. * In some cases (particularly for round joins with default-or-better * quantization) the closing segments can be made quite short. * This substantially improves performance (due to fewer intersections being created). * * A closingSegFactor of 0 results in lines to the corner vertex * A closingSegFactor of 1 results in lines halfway to the corner vertex * A closingSegFactor of 80 results in lines 1/81 of the way to the corner vertex * (this option is reasonable for the very common default situation of round joins * and quadrantSegs >= 8) */ private int closingSegLengthFactor = 1; private OffsetSegmentString segList; private double distance = 0.0; private PrecisionModel precisionModel; private BufferParameters bufParams; private LineIntersector li; private Coordinate s0, s1, s2; private LineSegment seg0 = new LineSegment(); private LineSegment seg1 = new LineSegment(); private LineSegment offset0 = new LineSegment(); private LineSegment offset1 = new LineSegment(); private int side = 0; private boolean hasNarrowConcaveAngle = false; public OffsetSegmentGenerator(PrecisionModel precisionModel, BufferParameters bufParams, double distance) { this.precisionModel = precisionModel; this.bufParams = bufParams; // compute intersections in full precision, to provide accuracy // the points are rounded as they are inserted into the curve line li = new RobustLineIntersector(); filletAngleQuantum = Math.PI / 2.0 / bufParams.getQuadrantSegments(); /** * Non-round joins cause issues with short closing segments, so don't use * them. In any case, non-round joins only really make sense for relatively * small buffer distances. */ if (bufParams.getQuadrantSegments() >= 8 && bufParams.getJoinStyle() == BufferParameters.JOIN_ROUND) closingSegLengthFactor = MAX_CLOSING_SEG_LEN_FACTOR; init(distance); } /** * Tests whether the input has a narrow concave angle * (relative to the offset distance). * In this case the generated offset curve will contain self-intersections * and heuristic closing segments. * This is expected behaviour in the case of Buffer curves. * For pure Offset Curves, * the output needs to be further treated * before it can be used. * * @return true if the input has a narrow concave angle */ public boolean hasNarrowConcaveAngle() { return hasNarrowConcaveAngle; } private void init(double distance) { this.distance = distance; maxCurveSegmentError = distance * (1 - Math.cos(filletAngleQuantum / 2.0)); segList = new OffsetSegmentString(); segList.setPrecisionModel(precisionModel); /** * Choose the min vertex separation as a small fraction of the offset distance. */ segList.setMinimumVertexDistance(distance * CURVE_VERTEX_SNAP_DISTANCE_FACTOR); } public void initSideSegments(Coordinate s1, Coordinate s2, int side) { this.s1 = s1; this.s2 = s2; this.side = side; seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); } public Coordinate[] getCoordinates() { Coordinate[] pts = segList.getCoordinates(); return pts; } public void closeRing() { segList.closeRing(); } public void addSegments(Coordinate[] pt, boolean isForward) { segList.addPts(pt, isForward); } public void addFirstSegment() { segList.addPt(offset1.p0); } /** * Add last offset point */ public void addLastSegment() { segList.addPt(offset1.p1); } //private static double MAX_CLOSING_SEG_LEN = 3.0; public void addNextSegment(Coordinate p, boolean addStartPoint) { // s0-s1-s2 are the coordinates of the previous segment and the current one s0 = s1; s1 = s2; s2 = p; seg0.setCoordinates(s0, s1); computeOffsetSegment(seg0, side, distance, offset0); seg1.setCoordinates(s1, s2); computeOffsetSegment(seg1, side, distance, offset1); // do nothing if points are equal if (s1.equals(s2)) return; int orientation = Orientation.index(s0, s1, s2); boolean outsideTurn = (orientation == Orientation.CLOCKWISE && side == Position.LEFT) || (orientation == Orientation.COUNTERCLOCKWISE && side == Position.RIGHT); if (orientation == 0) { // lines are collinear addCollinear(addStartPoint); } else if (outsideTurn) { addOutsideTurn(orientation, addStartPoint); } else { // inside turn addInsideTurn(orientation, addStartPoint); } } private void addCollinear(boolean addStartPoint) { /** * This test could probably be done more efficiently, * but the situation of exact collinearity should be fairly rare. */ li.computeIntersection(s0, s1, s1, s2); int numInt = li.getIntersectionNum(); /** * if numInt is < 2, the lines are parallel and in the same direction. In * this case the point can be ignored, since the offset lines will also be * parallel. */ if (numInt >= 2) { /** * segments are collinear but reversing. * Add an "end-cap" fillet * all the way around to other direction This case should ONLY happen * for LineStrings, so the orientation is always CW. (Polygons can never * have two consecutive segments which are parallel but reversed, * because that would be a self intersection. * */ if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL || bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { if (addStartPoint) segList.addPt(offset0.p1); segList.addPt(offset1.p0); } else { addCornerFillet(s1, offset0.p1, offset1.p0, Orientation.CLOCKWISE, distance); } } } /** * Adds the offset points for an outside (convex) turn * * @param orientation * @param addStartPoint */ private void addOutsideTurn(int orientation, boolean addStartPoint) { /** * Heuristic: If offset endpoints are very close together, * just use one of them as the corner vertex. * This avoids problems with computing mitre corners in the case * where the two segments are almost parallel * (which is hard to compute a robust intersection for). */ if (offset0.p1.distance(offset1.p0) < distance * OFFSET_SEGMENT_SEPARATION_FACTOR) { segList.addPt(offset0.p1); return; } if (bufParams.getJoinStyle() == BufferParameters.JOIN_MITRE) { addMitreJoin(s1, offset0, offset1, distance); } else if (bufParams.getJoinStyle() == BufferParameters.JOIN_BEVEL){ addBevelJoin(offset0, offset1); } else { // add a circular fillet connecting the endpoints of the offset segments if (addStartPoint) segList.addPt(offset0.p1); // TESTING - comment out to produce beveled joins addCornerFillet(s1, offset0.p1, offset1.p0, orientation, distance); segList.addPt(offset1.p0); } } /** * Adds the offset points for an inside (concave) turn. * * @param orientation * @param addStartPoint */ private void addInsideTurn(int orientation, boolean addStartPoint) { /** * add intersection point of offset segments (if any) */ li.computeIntersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (li.hasIntersection()) { segList.addPt(li.getIntersection(0)); } else { /** * If no intersection is detected, * it means the angle is so small and/or the offset so * large that the offsets segments don't intersect. * In this case we must * add a "closing segment" to make sure the buffer curve is continuous, * fairly smooth (e.g. no sharp reversals in direction) * and tracks the buffer correctly around the corner. The curve connects * the endpoints of the segment offsets to points * which lie toward the centre point of the corner. * The joining curve will not appear in the final buffer outline, since it * is completely internal to the buffer polygon. * * In complex buffer cases the closing segment may cut across many other * segments in the generated offset curve. In order to improve the * performance of the noding, the closing segment should be kept as short as possible. * (But not too short, since that would defeat its purpose). * This is the purpose of the closingSegFactor heuristic value. */ /** * The intersection test above is vulnerable to robustness errors; i.e. it * may be that the offsets should intersect very close to their endpoints, * but aren't reported as such due to rounding. To handle this situation * appropriately, we use the following test: If the offset points are very * close, don't add closing segments but simply use one of the offset * points */ hasNarrowConcaveAngle = true; //System.out.println("NARROW ANGLE - distance = " + distance); if (offset0.p1.distance(offset1.p0) < distance * INSIDE_TURN_VERTEX_SNAP_DISTANCE_FACTOR) { segList.addPt(offset0.p1); } else { // add endpoint of this segment offset segList.addPt(offset0.p1); /** * Add "closing segment" of required length. */ if (closingSegLengthFactor > 0) { Coordinate mid0 = new Coordinate((closingSegLengthFactor * offset0.p1.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset0.p1.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid0); Coordinate mid1 = new Coordinate((closingSegLengthFactor*offset1.p0.x + s1.x)/(closingSegLengthFactor + 1), (closingSegLengthFactor*offset1.p0.y + s1.y)/(closingSegLengthFactor + 1)); segList.addPt(mid1); } else { /** * This branch is not expected to be used except for testing purposes. * It is equivalent to the JTS 1.9 logic for closing segments * (which results in very poor performance for large buffer distances) */ segList.addPt(s1); } //*/ // add start point of next segment offset segList.addPt(offset1.p0); } } } /** * Compute an offset segment for an input segment on a given side and at a given distance. * The offset points are computed in full double precision, for accuracy. * * @param seg the segment to offset * @param side the side of the segment ({@link Position}) the offset lies on * @param distance the offset distance * @param offset the points computed for the offset segment */ private void computeOffsetSegment(LineSegment seg, int side, double distance, LineSegment offset) { int sideSign = side == Position.LEFT ? 1 : -1; double dx = seg.p1.x - seg.p0.x; double dy = seg.p1.y - seg.p0.y; double len = Math.sqrt(dx * dx + dy * dy); // u is the vector that is the length of the offset, in the direction of the segment double ux = sideSign * distance * dx / len; double uy = sideSign * distance * dy / len; offset.p0.x = seg.p0.x - uy; offset.p0.y = seg.p0.y + ux; offset.p1.x = seg.p1.x - uy; offset.p1.y = seg.p1.y + ux; } /** * Add an end cap around point p1, terminating a line segment coming from p0 */ public void addLineEndCap(Coordinate p0, Coordinate p1) { LineSegment seg = new LineSegment(p0, p1); LineSegment offsetL = new LineSegment(); computeOffsetSegment(seg, Position.LEFT, distance, offsetL); LineSegment offsetR = new LineSegment(); computeOffsetSegment(seg, Position.RIGHT, distance, offsetR); double dx = p1.x - p0.x; double dy = p1.y - p0.y; double angle = Math.atan2(dy, dx); switch (bufParams.getEndCapStyle()) { case BufferParameters.CAP_ROUND: // add offset seg points with a fillet between them segList.addPt(offsetL.p1); addDirectedFillet(p1, angle + Math.PI / 2, angle - Math.PI / 2, Orientation.CLOCKWISE, distance); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_FLAT: // only offset segment points are added segList.addPt(offsetL.p1); segList.addPt(offsetR.p1); break; case BufferParameters.CAP_SQUARE: // add a square defined by extensions of the offset segment endpoints Coordinate squareCapSideOffset = new Coordinate(); squareCapSideOffset.x = Math.abs(distance) * Math.cos(angle); squareCapSideOffset.y = Math.abs(distance) * Math.sin(angle); Coordinate squareCapLOffset = new Coordinate( offsetL.p1.x + squareCapSideOffset.x, offsetL.p1.y + squareCapSideOffset.y); Coordinate squareCapROffset = new Coordinate( offsetR.p1.x + squareCapSideOffset.x, offsetR.p1.y + squareCapSideOffset.y); segList.addPt(squareCapLOffset); segList.addPt(squareCapROffset); break; } } /** * Adds a mitre join connecting the two reflex offset segments. * The mitre will be beveled if it exceeds the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance */ private void addMitreJoin(Coordinate p, LineSegment offset0, LineSegment offset1, double distance) { /** * This computation is unstable if the offset segments are nearly collinear. * However, this situation should have been eliminated earlier by the check * for whether the offset segment endpoints are almost coincident */ Coordinate intPt = Intersection.intersection(offset0.p0, offset0.p1, offset1.p0, offset1.p1); if (intPt != null) { double mitreRatio = distance <= 0.0 ? 1.0 : intPt.distance(p) / Math.abs(distance); if (mitreRatio <= bufParams.getMitreLimit()) { segList.addPt(intPt); return; } } // at this point either intersection failed or mitre limit was exceeded addLimitedMitreJoin(offset0, offset1, distance, bufParams.getMitreLimit()); // addBevelJoin(offset0, offset1); } /** * Adds a limited mitre join connecting the two reflex offset segments. * A limited mitre is a mitre which is beveled at the distance * determined by the mitre ratio limit. * * @param offset0 the first offset segment * @param offset1 the second offset segment * @param distance the offset distance * @param mitreLimit the mitre limit ratio */ private void addLimitedMitreJoin( LineSegment offset0, LineSegment offset1, double distance, double mitreLimit) { Coordinate basePt = seg0.p1; double ang0 = Angle.angle(basePt, seg0.p0); // oriented angle<SUF> double angDiff = Angle.angleBetweenOriented(seg0.p0, basePt, seg1.p1); // half of the interior angle double angDiffHalf = angDiff / 2; // angle for bisector of the interior angle between the segments double midAng = Angle.normalize(ang0 + angDiffHalf); // rotating this by PI gives the bisector of the reflex angle double mitreMidAng = Angle.normalize(midAng + Math.PI); // the miterLimit determines the distance to the mitre bevel double mitreDist = mitreLimit * distance; // the bevel delta is the difference between the buffer distance // and half of the length of the bevel segment double bevelDelta = mitreDist * Math.abs(Math.sin(angDiffHalf)); double bevelHalfLen = distance - bevelDelta; // compute the midpoint of the bevel segment double bevelMidX = basePt.x + mitreDist * Math.cos(mitreMidAng); double bevelMidY = basePt.y + mitreDist * Math.sin(mitreMidAng); Coordinate bevelMidPt = new Coordinate(bevelMidX, bevelMidY); // compute the mitre midline segment from the corner point to the bevel segment midpoint LineSegment mitreMidLine = new LineSegment(basePt, bevelMidPt); // finally the bevel segment endpoints are computed as offsets from // the mitre midline Coordinate bevelEndLeft = mitreMidLine.pointAlongOffset(1.0, bevelHalfLen); Coordinate bevelEndRight = mitreMidLine.pointAlongOffset(1.0, -bevelHalfLen); if (side == Position.LEFT) { segList.addPt(bevelEndLeft); segList.addPt(bevelEndRight); } else { segList.addPt(bevelEndRight); segList.addPt(bevelEndLeft); } } /** * Adds a bevel join connecting the two offset segments * around a reflex corner. * * @param offset0 the first offset segment * @param offset1 the second offset segment */ private void addBevelJoin( LineSegment offset0, LineSegment offset1) { segList.addPt(offset0.p1); segList.addPt(offset1.p0); } /** * Add points for a circular fillet around a reflex corner. * Adds the start and end points * * @param p base point of curve * @param p0 start point of fillet curve * @param p1 endpoint of fillet curve * @param direction the orientation of the fillet * @param radius the radius of the fillet */ private void addCornerFillet(Coordinate p, Coordinate p0, Coordinate p1, int direction, double radius) { double dx0 = p0.x - p.x; double dy0 = p0.y - p.y; double startAngle = Math.atan2(dy0, dx0); double dx1 = p1.x - p.x; double dy1 = p1.y - p.y; double endAngle = Math.atan2(dy1, dx1); if (direction == Orientation.CLOCKWISE) { if (startAngle <= endAngle) startAngle += 2.0 * Math.PI; } else { // direction == COUNTERCLOCKWISE if (startAngle >= endAngle) startAngle -= 2.0 * Math.PI; } segList.addPt(p0); addDirectedFillet(p, startAngle, endAngle, direction, radius); segList.addPt(p1); } /** * Adds points for a circular fillet arc * between two specified angles. * The start and end point for the fillet are not added - * the caller must add them if required. * * @param direction is -1 for a CW angle, 1 for a CCW angle * @param radius the radius of the fillet */ private void addDirectedFillet(Coordinate p, double startAngle, double endAngle, int direction, double radius) { int directionFactor = direction == Orientation.CLOCKWISE ? -1 : 1; double totalAngle = Math.abs(startAngle - endAngle); int nSegs = (int) (totalAngle / filletAngleQuantum + 0.5); if (nSegs < 1) return; // no segments because angle is less than increment - nothing to do! // choose angle increment so that each segment has equal length double angleInc = totalAngle / nSegs; Coordinate pt = new Coordinate(); for (int i = 0; i < nSegs; i++) { double angle = startAngle + directionFactor * i * angleInc; pt.x = p.x + radius * Math.cos(angle); pt.y = p.y + radius * Math.sin(angle); segList.addPt(pt); } } /** * Creates a CW circle around a point */ public void createCircle(Coordinate p) { // add start point Coordinate pt = new Coordinate(p.x + distance, p.y); segList.addPt(pt); addDirectedFillet(p, 0.0, 2.0 * Math.PI, -1, distance); segList.closeRing(); } /** * Creates a CW square around a point */ public void createSquare(Coordinate p) { segList.addPt(new Coordinate(p.x + distance, p.y + distance)); segList.addPt(new Coordinate(p.x + distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y - distance)); segList.addPt(new Coordinate(p.x - distance, p.y + distance)); segList.closeRing(); } }
200847_2
// TODO: 03-05-2024, re-write entire whispercpp.java with standard Android JNI specification // TODO: 03-26-2024, rename this file to ggmljni to unify the JNI of whisper.cpp and llama.cpp, as these projects are all based on ggml package org.ggml; public class ggmljava { private static final String TAG = ggmljava.class.getName(); //keep sync between here and ggml.h // available GGML tensor operations: public enum ggml_op { GGML_OP_NONE, GGML_OP_DUP, GGML_OP_ADD, GGML_OP_ADD1, GGML_OP_ACC, GGML_OP_SUB, GGML_OP_MUL, GGML_OP_DIV, GGML_OP_SQR, GGML_OP_SQRT, GGML_OP_LOG, GGML_OP_SUM, GGML_OP_SUM_ROWS, GGML_OP_MEAN, GGML_OP_ARGMAX, GGML_OP_REPEAT, GGML_OP_REPEAT_BACK, GGML_OP_CONCAT, GGML_OP_SILU_BACK, GGML_OP_NORM, // normalize GGML_OP_RMS_NORM, GGML_OP_RMS_NORM_BACK, GGML_OP_GROUP_NORM, GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID, GGML_OP_OUT_PROD, GGML_OP_SCALE, GGML_OP_SET, GGML_OP_CPY, GGML_OP_CONT, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_PERMUTE, GGML_OP_TRANSPOSE, GGML_OP_GET_ROWS, GGML_OP_GET_ROWS_BACK, GGML_OP_DIAG, GGML_OP_DIAG_MASK_INF, GGML_OP_DIAG_MASK_ZERO, GGML_OP_SOFT_MAX, GGML_OP_SOFT_MAX_BACK, GGML_OP_ROPE, GGML_OP_ROPE_BACK, GGML_OP_ALIBI, GGML_OP_CLAMP, GGML_OP_CONV_TRANSPOSE_1D, GGML_OP_IM2COL, GGML_OP_CONV_TRANSPOSE_2D, GGML_OP_POOL_1D, GGML_OP_POOL_2D, GGML_OP_UPSCALE, // nearest interpolate GGML_OP_PAD, GGML_OP_ARANGE, GGML_OP_TIMESTEP_EMBEDDING, GGML_OP_ARGSORT, GGML_OP_LEAKY_RELU, GGML_OP_FLASH_ATTN, GGML_OP_FLASH_FF, GGML_OP_FLASH_ATTN_BACK, GGML_OP_SSM_CONV, GGML_OP_SSM_SCAN, GGML_OP_WIN_PART, GGML_OP_WIN_UNPART, GGML_OP_GET_REL_POS, GGML_OP_ADD_REL_POS, GGML_OP_UNARY, GGML_OP_MAP_UNARY, GGML_OP_MAP_BINARY, GGML_OP_MAP_CUSTOM1_F32, GGML_OP_MAP_CUSTOM2_F32, GGML_OP_MAP_CUSTOM3_F32, GGML_OP_MAP_CUSTOM1, GGML_OP_MAP_CUSTOM2, GGML_OP_MAP_CUSTOM3, GGML_OP_CROSS_ENTROPY_LOSS, GGML_OP_CROSS_ENTROPY_LOSS_BACK, GGML_OP_COUNT, }; public static native int asr_init(String strModelPath, int nThreadCounts, int nASRMode, int nBackendType); public static native void asr_finalize(); public static native void asr_start(); public static native void asr_stop(); public static native int asr_reset(String strModelPath, int nThreadCounts, int nASRMode, int nBackendType); public static native String asr_get_systeminfo(); public static native int get_cpu_core_counts(); //TODO: not work as expected public static native void asr_set_benchmark_status(int bExitBenchmark); /** * @param modelPath /sdcard/kantv/ggml-xxxxxx.bin or /sdcard/kantv/xxxxxx.gguf or qualcomm's prebuilt dedicated model.so or "" * @param audioPath /sdcard/kantv/jfk.wav * @param nBenchType 0: whisper asr 1: memcpy 2: mulmat 3: whisper full 4: LLAMA 5: stable diffusion 6: QNN sample 7: QNN saver 8: QNN matrix 9: QNN GGML 10: QNN complex 11: QNN GGML OP(QNN UT) 12: QNN UT automation * @param nThreadCounts 1 - 8 * @param nBackendType 0: CPU 1: GPU 2: DSP 3: ggml("fake" QNN backend, just for compare performance) * @param nOpType type of matrix manipulate / GGML OP / type of various complex/complicated computation graph * @return */ public static native String ggml_bench(String modelPath, String audioPath, int nBenchType, int nThreadCounts, int nBackendType, int nOpType); public static native String llm_get_systeminfo(); public static native String llm_inference(String modelPath, String prompt, int nBenchType, int nThreadCounts, int nBackendType); }
zhouwg/kantv
cdeosplayer/cdeosplayer-lib/src/main/java/org/ggml/ggmljava.java
1,643
//keep sync between here and ggml.h
line_comment
nl
// TODO: 03-05-2024, re-write entire whispercpp.java with standard Android JNI specification // TODO: 03-26-2024, rename this file to ggmljni to unify the JNI of whisper.cpp and llama.cpp, as these projects are all based on ggml package org.ggml; public class ggmljava { private static final String TAG = ggmljava.class.getName(); //keep sync<SUF> // available GGML tensor operations: public enum ggml_op { GGML_OP_NONE, GGML_OP_DUP, GGML_OP_ADD, GGML_OP_ADD1, GGML_OP_ACC, GGML_OP_SUB, GGML_OP_MUL, GGML_OP_DIV, GGML_OP_SQR, GGML_OP_SQRT, GGML_OP_LOG, GGML_OP_SUM, GGML_OP_SUM_ROWS, GGML_OP_MEAN, GGML_OP_ARGMAX, GGML_OP_REPEAT, GGML_OP_REPEAT_BACK, GGML_OP_CONCAT, GGML_OP_SILU_BACK, GGML_OP_NORM, // normalize GGML_OP_RMS_NORM, GGML_OP_RMS_NORM_BACK, GGML_OP_GROUP_NORM, GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID, GGML_OP_OUT_PROD, GGML_OP_SCALE, GGML_OP_SET, GGML_OP_CPY, GGML_OP_CONT, GGML_OP_RESHAPE, GGML_OP_VIEW, GGML_OP_PERMUTE, GGML_OP_TRANSPOSE, GGML_OP_GET_ROWS, GGML_OP_GET_ROWS_BACK, GGML_OP_DIAG, GGML_OP_DIAG_MASK_INF, GGML_OP_DIAG_MASK_ZERO, GGML_OP_SOFT_MAX, GGML_OP_SOFT_MAX_BACK, GGML_OP_ROPE, GGML_OP_ROPE_BACK, GGML_OP_ALIBI, GGML_OP_CLAMP, GGML_OP_CONV_TRANSPOSE_1D, GGML_OP_IM2COL, GGML_OP_CONV_TRANSPOSE_2D, GGML_OP_POOL_1D, GGML_OP_POOL_2D, GGML_OP_UPSCALE, // nearest interpolate GGML_OP_PAD, GGML_OP_ARANGE, GGML_OP_TIMESTEP_EMBEDDING, GGML_OP_ARGSORT, GGML_OP_LEAKY_RELU, GGML_OP_FLASH_ATTN, GGML_OP_FLASH_FF, GGML_OP_FLASH_ATTN_BACK, GGML_OP_SSM_CONV, GGML_OP_SSM_SCAN, GGML_OP_WIN_PART, GGML_OP_WIN_UNPART, GGML_OP_GET_REL_POS, GGML_OP_ADD_REL_POS, GGML_OP_UNARY, GGML_OP_MAP_UNARY, GGML_OP_MAP_BINARY, GGML_OP_MAP_CUSTOM1_F32, GGML_OP_MAP_CUSTOM2_F32, GGML_OP_MAP_CUSTOM3_F32, GGML_OP_MAP_CUSTOM1, GGML_OP_MAP_CUSTOM2, GGML_OP_MAP_CUSTOM3, GGML_OP_CROSS_ENTROPY_LOSS, GGML_OP_CROSS_ENTROPY_LOSS_BACK, GGML_OP_COUNT, }; public static native int asr_init(String strModelPath, int nThreadCounts, int nASRMode, int nBackendType); public static native void asr_finalize(); public static native void asr_start(); public static native void asr_stop(); public static native int asr_reset(String strModelPath, int nThreadCounts, int nASRMode, int nBackendType); public static native String asr_get_systeminfo(); public static native int get_cpu_core_counts(); //TODO: not work as expected public static native void asr_set_benchmark_status(int bExitBenchmark); /** * @param modelPath /sdcard/kantv/ggml-xxxxxx.bin or /sdcard/kantv/xxxxxx.gguf or qualcomm's prebuilt dedicated model.so or "" * @param audioPath /sdcard/kantv/jfk.wav * @param nBenchType 0: whisper asr 1: memcpy 2: mulmat 3: whisper full 4: LLAMA 5: stable diffusion 6: QNN sample 7: QNN saver 8: QNN matrix 9: QNN GGML 10: QNN complex 11: QNN GGML OP(QNN UT) 12: QNN UT automation * @param nThreadCounts 1 - 8 * @param nBackendType 0: CPU 1: GPU 2: DSP 3: ggml("fake" QNN backend, just for compare performance) * @param nOpType type of matrix manipulate / GGML OP / type of various complex/complicated computation graph * @return */ public static native String ggml_bench(String modelPath, String audioPath, int nBenchType, int nThreadCounts, int nBackendType, int nOpType); public static native String llm_get_systeminfo(); public static native String llm_inference(String modelPath, String prompt, int nBenchType, int nThreadCounts, int nBackendType); }
162192_77
/* * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.MultipleGradientPaint.CycleMethod; import java.awt.MultipleGradientPaint.ColorSpaceType; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Rectangle2D; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferInt; import java.awt.image.DirectColorModel; import java.awt.image.Raster; import java.awt.image.SinglePixelPackedSampleModel; import java.awt.image.WritableRaster; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.Arrays; /** * This is the superclass for all PaintContexts which use a multiple color * gradient to fill in their raster. It provides the actual color * interpolation functionality. Subclasses only have to deal with using * the gradient to fill pixels in a raster. * * @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans */ abstract class MultipleGradientPaintContext implements PaintContext { /** * The PaintContext's ColorModel. This is ARGB if colors are not all * opaque, otherwise it is RGB. */ protected ColorModel model; /** Color model used if gradient colors are all opaque. */ private static ColorModel xrgbmodel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff); /** The cached ColorModel. */ protected static ColorModel cachedModel; /** The cached raster, which is reusable among instances. */ protected static WeakReference<Raster> cached; /** Raster is reused whenever possible. */ protected Raster saved; /** The method to use when painting out of the gradient bounds. */ protected CycleMethod cycleMethod; /** The ColorSpace in which to perform the interpolation */ protected ColorSpaceType colorSpace; /** Elements of the inverse transform matrix. */ protected float a00, a01, a10, a11, a02, a12; /** * This boolean specifies whether we are in simple lookup mode, where an * input value between 0 and 1 may be used to directly index into a single * array of gradient colors. If this boolean value is false, then we have * to use a 2-step process where we have to determine which gradient array * we fall into, then determine the index into that array. */ protected boolean isSimpleLookup; /** * Size of gradients array for scaling the 0-1 index when looking up * colors the fast way. */ protected int fastGradientArraySize; /** * Array which contains the interpolated color values for each interval, * used by calculateSingleArrayGradient(). It is protected for possible * direct access by subclasses. */ protected int[] gradient; /** * Array of gradient arrays, one array for each interval. Used by * calculateMultipleArrayGradient(). */ private int[][] gradients; /** Normalized intervals array. */ private float[] normalizedIntervals; /** Fractions array. */ private float[] fractions; /** Used to determine if gradient colors are all opaque. */ private int transparencyTest; /** Color space conversion lookup tables. */ private static final int SRGBtoLinearRGB[] = new int[256]; private static final int LinearRGBtoSRGB[] = new int[256]; static { // build the tables for (int k = 0; k < 256; k++) { SRGBtoLinearRGB[k] = convertSRGBtoLinearRGB(k); LinearRGBtoSRGB[k] = convertLinearRGBtoSRGB(k); } } /** * Constant number of max colors between any 2 arbitrary colors. * Used for creating and indexing gradients arrays. */ protected static final int GRADIENT_SIZE = 256; protected static final int GRADIENT_SIZE_INDEX = GRADIENT_SIZE -1; /** * Maximum length of the fast single-array. If the estimated array size * is greater than this, switch over to the slow lookup method. * No particular reason for choosing this number, but it seems to provide * satisfactory performance for the common case (fast lookup). */ private static final int MAX_GRADIENT_ARRAY_SIZE = 5000; /** * Constructor for MultipleGradientPaintContext superclass. */ protected MultipleGradientPaintContext(MultipleGradientPaint mgp, ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform t, RenderingHints hints, float[] fractions, Color[] colors, CycleMethod cycleMethod, ColorSpaceType colorSpace) { if (deviceBounds == null) { throw new NullPointerException("Device bounds cannot be null"); } if (userBounds == null) { throw new NullPointerException("User bounds cannot be null"); } if (t == null) { throw new NullPointerException("Transform cannot be null"); } if (hints == null) { throw new NullPointerException("RenderingHints cannot be null"); } // The inverse transform is needed to go from device to user space. // Get all the components of the inverse transform matrix. AffineTransform tInv; try { // the following assumes that the caller has copied the incoming // transform and is not concerned about it being modified t.invert(); tInv = t; } catch (NoninvertibleTransformException e) { // just use identity transform in this case; better to show // (incorrect) results than to throw an exception and/or no-op tInv = new AffineTransform(); } double m[] = new double[6]; tInv.getMatrix(m); a00 = (float)m[0]; a10 = (float)m[1]; a01 = (float)m[2]; a11 = (float)m[3]; a02 = (float)m[4]; a12 = (float)m[5]; // copy some flags this.cycleMethod = cycleMethod; this.colorSpace = colorSpace; // we can avoid copying this array since we do not modify its values this.fractions = fractions; // note that only one of these values can ever be non-null (we either // store the fast gradient array or the slow one, but never both // at the same time) int[] gradient = (mgp.gradient != null) ? mgp.gradient.get() : null; int[][] gradients = (mgp.gradients != null) ? mgp.gradients.get() : null; if (gradient == null && gradients == null) { // we need to (re)create the appropriate values calculateLookupData(colors); // now cache the calculated values in the // MultipleGradientPaint instance for future use mgp.model = this.model; mgp.normalizedIntervals = this.normalizedIntervals; mgp.isSimpleLookup = this.isSimpleLookup; if (isSimpleLookup) { // only cache the fast array mgp.fastGradientArraySize = this.fastGradientArraySize; mgp.gradient = new SoftReference<int[]>(this.gradient); } else { // only cache the slow array mgp.gradients = new SoftReference<int[][]>(this.gradients); } } else { // use the values cached in the MultipleGradientPaint instance this.model = mgp.model; this.normalizedIntervals = mgp.normalizedIntervals; this.isSimpleLookup = mgp.isSimpleLookup; this.gradient = gradient; this.fastGradientArraySize = mgp.fastGradientArraySize; this.gradients = gradients; } } /** * This function is the meat of this class. It calculates an array of * gradient colors based on an array of fractions and color values at * those fractions. */ private void calculateLookupData(Color[] colors) { Color[] normalizedColors; if (colorSpace == ColorSpaceType.LINEAR_RGB) { // create a new colors array normalizedColors = new Color[colors.length]; // convert the colors using the lookup table for (int i = 0; i < colors.length; i++) { int argb = colors[i].getRGB(); int a = argb >>> 24; int r = SRGBtoLinearRGB[(argb >> 16) & 0xff]; int g = SRGBtoLinearRGB[(argb >> 8) & 0xff]; int b = SRGBtoLinearRGB[(argb ) & 0xff]; normalizedColors[i] = new Color(r, g, b, a); } } else { // we can just use this array by reference since we do not // modify its values in the case of SRGB normalizedColors = colors; } // this will store the intervals (distances) between gradient stops normalizedIntervals = new float[fractions.length-1]; // convert from fractions into intervals for (int i = 0; i < normalizedIntervals.length; i++) { // interval distance is equal to the difference in positions normalizedIntervals[i] = this.fractions[i+1] - this.fractions[i]; } // initialize to be fully opaque for ANDing with colors transparencyTest = 0xff000000; // array of interpolation arrays gradients = new int[normalizedIntervals.length][]; // find smallest interval float Imin = 1; for (int i = 0; i < normalizedIntervals.length; i++) { Imin = (Imin > normalizedIntervals[i]) ? normalizedIntervals[i] : Imin; } // Estimate the size of the entire gradients array. // This is to prevent a tiny interval from causing the size of array // to explode. If the estimated size is too large, break to using // separate arrays for each interval, and using an indexing scheme at // look-up time. int estimatedSize = 0; for (int i = 0; i < normalizedIntervals.length; i++) { estimatedSize += (normalizedIntervals[i]/Imin) * GRADIENT_SIZE; } if (estimatedSize > MAX_GRADIENT_ARRAY_SIZE) { // slow method calculateMultipleArrayGradient(normalizedColors); } else { // fast method calculateSingleArrayGradient(normalizedColors, Imin); } // use the most "economical" model if ((transparencyTest >>> 24) == 0xff) { model = xrgbmodel; } else { model = ColorModel.getRGBdefault(); } } /** * FAST LOOKUP METHOD * * This method calculates the gradient color values and places them in a * single int array, gradient[]. It does this by allocating space for * each interval based on its size relative to the smallest interval in * the array. The smallest interval is allocated 255 interpolated values * (the maximum number of unique in-between colors in a 24 bit color * system), and all other intervals are allocated * size = (255 * the ratio of their size to the smallest interval). * * This scheme expedites a speedy retrieval because the colors are * distributed along the array according to their user-specified * distribution. All that is needed is a relative index from 0 to 1. * * The only problem with this method is that the possibility exists for * the array size to balloon in the case where there is a * disproportionately small gradient interval. In this case the other * intervals will be allocated huge space, but much of that data is * redundant. We thus need to use the space conserving scheme below. * * @param Imin the size of the smallest interval */ private void calculateSingleArrayGradient(Color[] colors, float Imin) { // set the flag so we know later it is a simple (fast) lookup isSimpleLookup = true; // 2 colors to interpolate int rgb1, rgb2; //the eventual size of the single array int gradientsTot = 1; // for every interval (transition between 2 colors) for (int i = 0; i < gradients.length; i++) { // create an array whose size is based on the ratio to the // smallest interval int nGradients = (int)((normalizedIntervals[i]/Imin)*255f); gradientsTot += nGradients; gradients[i] = new int[nGradients]; // the 2 colors (keyframes) to interpolate between rgb1 = colors[i].getRGB(); rgb2 = colors[i+1].getRGB(); // fill this array with the colors in between rgb1 and rgb2 interpolate(rgb1, rgb2, gradients[i]); // if the colors are opaque, transparency should still // be 0xff000000 transparencyTest &= rgb1; transparencyTest &= rgb2; } // put all gradients in a single array gradient = new int[gradientsTot]; int curOffset = 0; for (int i = 0; i < gradients.length; i++){ System.arraycopy(gradients[i], 0, gradient, curOffset, gradients[i].length); curOffset += gradients[i].length; } gradient[gradient.length-1] = colors[colors.length-1].getRGB(); // if interpolation occurred in Linear RGB space, convert the // gradients back to sRGB using the lookup table if (colorSpace == ColorSpaceType.LINEAR_RGB) { for (int i = 0; i < gradient.length; i++) { gradient[i] = convertEntireColorLinearRGBtoSRGB(gradient[i]); } } fastGradientArraySize = gradient.length - 1; } /** * SLOW LOOKUP METHOD * * This method calculates the gradient color values for each interval and * places each into its own 255 size array. The arrays are stored in * gradients[][]. (255 is used because this is the maximum number of * unique colors between 2 arbitrary colors in a 24 bit color system.) * * This method uses the minimum amount of space (only 255 * number of * intervals), but it aggravates the lookup procedure, because now we * have to find out which interval to select, then calculate the index * within that interval. This causes a significant performance hit, * because it requires this calculation be done for every point in * the rendering loop. * * For those of you who are interested, this is a classic example of the * time-space tradeoff. */ private void calculateMultipleArrayGradient(Color[] colors) { // set the flag so we know later it is a non-simple lookup isSimpleLookup = false; // 2 colors to interpolate int rgb1, rgb2; // for every interval (transition between 2 colors) for (int i = 0; i < gradients.length; i++){ // create an array of the maximum theoretical size for // each interval gradients[i] = new int[GRADIENT_SIZE]; // get the 2 colors rgb1 = colors[i].getRGB(); rgb2 = colors[i+1].getRGB(); // fill this array with the colors in between rgb1 and rgb2 interpolate(rgb1, rgb2, gradients[i]); // if the colors are opaque, transparency should still // be 0xff000000 transparencyTest &= rgb1; transparencyTest &= rgb2; } // if interpolation occurred in Linear RGB space, convert the // gradients back to SRGB using the lookup table if (colorSpace == ColorSpaceType.LINEAR_RGB) { for (int j = 0; j < gradients.length; j++) { for (int i = 0; i < gradients[j].length; i++) { gradients[j][i] = convertEntireColorLinearRGBtoSRGB(gradients[j][i]); } } } } /** * Yet another helper function. This one linearly interpolates between * 2 colors, filling up the output array. * * @param rgb1 the start color * @param rgb2 the end color * @param output the output array of colors; must not be null */ private void interpolate(int rgb1, int rgb2, int[] output) { // color components int a1, r1, g1, b1, da, dr, dg, db; // step between interpolated values float stepSize = 1.0f / output.length; // extract color components from packed integer a1 = (rgb1 >> 24) & 0xff; r1 = (rgb1 >> 16) & 0xff; g1 = (rgb1 >> 8) & 0xff; b1 = (rgb1 ) & 0xff; // calculate the total change in alpha, red, green, blue da = ((rgb2 >> 24) & 0xff) - a1; dr = ((rgb2 >> 16) & 0xff) - r1; dg = ((rgb2 >> 8) & 0xff) - g1; db = ((rgb2 ) & 0xff) - b1; // for each step in the interval calculate the in-between color by // multiplying the normalized current position by the total color // change (0.5 is added to prevent truncation round-off error) for (int i = 0; i < output.length; i++) { output[i] = (((int) ((a1 + i * da * stepSize) + 0.5) << 24)) | (((int) ((r1 + i * dr * stepSize) + 0.5) << 16)) | (((int) ((g1 + i * dg * stepSize) + 0.5) << 8)) | (((int) ((b1 + i * db * stepSize) + 0.5) )); } } /** * Yet another helper function. This one extracts the color components * of an integer RGB triple, converts them from LinearRGB to SRGB, then * recompacts them into an int. */ private int convertEntireColorLinearRGBtoSRGB(int rgb) { // color components int a1, r1, g1, b1; // extract red, green, blue components a1 = (rgb >> 24) & 0xff; r1 = (rgb >> 16) & 0xff; g1 = (rgb >> 8) & 0xff; b1 = (rgb ) & 0xff; // use the lookup table r1 = LinearRGBtoSRGB[r1]; g1 = LinearRGBtoSRGB[g1]; b1 = LinearRGBtoSRGB[b1]; // re-compact the components return ((a1 << 24) | (r1 << 16) | (g1 << 8) | (b1 )); } /** * Helper function to index into the gradients array. This is necessary * because each interval has an array of colors with uniform size 255. * However, the color intervals are not necessarily of uniform length, so * a conversion is required. * * @param position the unmanipulated position, which will be mapped * into the range 0 to 1 * @return integer color to display */ protected final int indexIntoGradientsArrays(float position) { // first, manipulate position value depending on the cycle method if (cycleMethod == CycleMethod.NO_CYCLE) { if (position > 1) { // upper bound is 1 position = 1; } else if (position < 0) { // lower bound is 0 position = 0; } } else if (cycleMethod == CycleMethod.REPEAT) { // get the fractional part // (modulo behavior discards integer component) position = position - (int)position; //position should now be between -1 and 1 if (position < 0) { // force it to be in the range 0-1 position = position + 1; } } else { // cycleMethod == CycleMethod.REFLECT if (position < 0) { // take absolute value position = -position; } // get the integer part int part = (int)position; // get the fractional part position = position - part; if ((part & 1) == 1) { // integer part is odd, get reflected color instead position = 1 - position; } } // now, get the color based on this 0-1 position... if (isSimpleLookup) { // easy to compute: just scale index by array size return gradient[(int)(position * fastGradientArraySize)]; } else { // more complicated computation, to save space // for all the gradient interval arrays for (int i = 0; i < gradients.length; i++) { if (position < fractions[i+1]) { // this is the array we want float delta = position - fractions[i]; // this is the interval we want int index = (int)((delta / normalizedIntervals[i]) * (GRADIENT_SIZE_INDEX)); return gradients[i][index]; } } } return gradients[gradients.length - 1][GRADIENT_SIZE_INDEX]; } /** * Helper function to convert a color component in sRGB space to linear * RGB space. Used to build a static lookup table. */ private static int convertSRGBtoLinearRGB(int color) { float input, output; input = color / 255.0f; if (input <= 0.04045f) { output = input / 12.92f; } else { output = (float)Math.pow((input + 0.055) / 1.055, 2.4); } return Math.round(output * 255.0f); } /** * Helper function to convert a color component in linear RGB space to * SRGB space. Used to build a static lookup table. */ private static int convertLinearRGBtoSRGB(int color) { float input, output; input = color/255.0f; if (input <= 0.0031308) { output = input * 12.92f; } else { output = (1.055f * ((float) Math.pow(input, (1.0 / 2.4)))) - 0.055f; } return Math.round(output * 255.0f); } /** * {@inheritDoc} */ public final Raster getRaster(int x, int y, int w, int h) { // If working raster is big enough, reuse it. Otherwise, // build a large enough new one. Raster raster = saved; if (raster == null || raster.getWidth() < w || raster.getHeight() < h) { raster = getCachedRaster(model, w, h); saved = raster; } // Access raster internal int array. Because we use a DirectColorModel, // we know the DataBuffer is of type DataBufferInt and the SampleModel // is SinglePixelPackedSampleModel. // Adjust for initial offset in DataBuffer and also for the scanline // stride. // These calls make the DataBuffer non-acceleratable, but the // Raster is never Stable long enough to accelerate anyway... DataBufferInt rasterDB = (DataBufferInt)raster.getDataBuffer(); int[] pixels = rasterDB.getData(0); int off = rasterDB.getOffset(); int scanlineStride = ((SinglePixelPackedSampleModel) raster.getSampleModel()).getScanlineStride(); int adjust = scanlineStride - w; fillRaster(pixels, off, adjust, x, y, w, h); // delegate to subclass return raster; } protected abstract void fillRaster(int pixels[], int off, int adjust, int x, int y, int w, int h); /** * Took this cacheRaster code from GradientPaint. It appears to recycle * rasters for use by any other instance, as long as they are sufficiently * large. */ private static synchronized Raster getCachedRaster(ColorModel cm, int w, int h) { if (cm == cachedModel) { if (cached != null) { Raster ras = cached.get(); if (ras != null && ras.getWidth() >= w && ras.getHeight() >= h) { cached = null; return ras; } } } return cm.createCompatibleWritableRaster(w, h); } /** * Took this cacheRaster code from GradientPaint. It appears to recycle * rasters for use by any other instance, as long as they are sufficiently * large. */ private static synchronized void putCachedRaster(ColorModel cm, Raster ras) { if (cached != null) { Raster cras = cached.get(); if (cras != null) { int cw = cras.getWidth(); int ch = cras.getHeight(); int iw = ras.getWidth(); int ih = ras.getHeight(); if (cw >= iw && ch >= ih) { return; } if (cw * ch >= iw * ih) { return; } } } cachedModel = cm; cached = new WeakReference<Raster>(ras); } /** * {@inheritDoc} */ public final void dispose() { if (saved != null) { putCachedRaster(model, saved); saved = null; } } /** * {@inheritDoc} */ public final ColorModel getColorModel() { return model; } }
zihaojiang/LearningJDK
src/java/awt/MultipleGradientPaintContext.java
7,432
// step between interpolated values
line_comment
nl
/* * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.awt; import java.awt.MultipleGradientPaint.CycleMethod; import java.awt.MultipleGradientPaint.ColorSpaceType; import java.awt.color.ColorSpace; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Rectangle2D; import java.awt.image.ColorModel; import java.awt.image.DataBuffer; import java.awt.image.DataBufferInt; import java.awt.image.DirectColorModel; import java.awt.image.Raster; import java.awt.image.SinglePixelPackedSampleModel; import java.awt.image.WritableRaster; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.Arrays; /** * This is the superclass for all PaintContexts which use a multiple color * gradient to fill in their raster. It provides the actual color * interpolation functionality. Subclasses only have to deal with using * the gradient to fill pixels in a raster. * * @author Nicholas Talian, Vincent Hardy, Jim Graham, Jerry Evans */ abstract class MultipleGradientPaintContext implements PaintContext { /** * The PaintContext's ColorModel. This is ARGB if colors are not all * opaque, otherwise it is RGB. */ protected ColorModel model; /** Color model used if gradient colors are all opaque. */ private static ColorModel xrgbmodel = new DirectColorModel(24, 0x00ff0000, 0x0000ff00, 0x000000ff); /** The cached ColorModel. */ protected static ColorModel cachedModel; /** The cached raster, which is reusable among instances. */ protected static WeakReference<Raster> cached; /** Raster is reused whenever possible. */ protected Raster saved; /** The method to use when painting out of the gradient bounds. */ protected CycleMethod cycleMethod; /** The ColorSpace in which to perform the interpolation */ protected ColorSpaceType colorSpace; /** Elements of the inverse transform matrix. */ protected float a00, a01, a10, a11, a02, a12; /** * This boolean specifies whether we are in simple lookup mode, where an * input value between 0 and 1 may be used to directly index into a single * array of gradient colors. If this boolean value is false, then we have * to use a 2-step process where we have to determine which gradient array * we fall into, then determine the index into that array. */ protected boolean isSimpleLookup; /** * Size of gradients array for scaling the 0-1 index when looking up * colors the fast way. */ protected int fastGradientArraySize; /** * Array which contains the interpolated color values for each interval, * used by calculateSingleArrayGradient(). It is protected for possible * direct access by subclasses. */ protected int[] gradient; /** * Array of gradient arrays, one array for each interval. Used by * calculateMultipleArrayGradient(). */ private int[][] gradients; /** Normalized intervals array. */ private float[] normalizedIntervals; /** Fractions array. */ private float[] fractions; /** Used to determine if gradient colors are all opaque. */ private int transparencyTest; /** Color space conversion lookup tables. */ private static final int SRGBtoLinearRGB[] = new int[256]; private static final int LinearRGBtoSRGB[] = new int[256]; static { // build the tables for (int k = 0; k < 256; k++) { SRGBtoLinearRGB[k] = convertSRGBtoLinearRGB(k); LinearRGBtoSRGB[k] = convertLinearRGBtoSRGB(k); } } /** * Constant number of max colors between any 2 arbitrary colors. * Used for creating and indexing gradients arrays. */ protected static final int GRADIENT_SIZE = 256; protected static final int GRADIENT_SIZE_INDEX = GRADIENT_SIZE -1; /** * Maximum length of the fast single-array. If the estimated array size * is greater than this, switch over to the slow lookup method. * No particular reason for choosing this number, but it seems to provide * satisfactory performance for the common case (fast lookup). */ private static final int MAX_GRADIENT_ARRAY_SIZE = 5000; /** * Constructor for MultipleGradientPaintContext superclass. */ protected MultipleGradientPaintContext(MultipleGradientPaint mgp, ColorModel cm, Rectangle deviceBounds, Rectangle2D userBounds, AffineTransform t, RenderingHints hints, float[] fractions, Color[] colors, CycleMethod cycleMethod, ColorSpaceType colorSpace) { if (deviceBounds == null) { throw new NullPointerException("Device bounds cannot be null"); } if (userBounds == null) { throw new NullPointerException("User bounds cannot be null"); } if (t == null) { throw new NullPointerException("Transform cannot be null"); } if (hints == null) { throw new NullPointerException("RenderingHints cannot be null"); } // The inverse transform is needed to go from device to user space. // Get all the components of the inverse transform matrix. AffineTransform tInv; try { // the following assumes that the caller has copied the incoming // transform and is not concerned about it being modified t.invert(); tInv = t; } catch (NoninvertibleTransformException e) { // just use identity transform in this case; better to show // (incorrect) results than to throw an exception and/or no-op tInv = new AffineTransform(); } double m[] = new double[6]; tInv.getMatrix(m); a00 = (float)m[0]; a10 = (float)m[1]; a01 = (float)m[2]; a11 = (float)m[3]; a02 = (float)m[4]; a12 = (float)m[5]; // copy some flags this.cycleMethod = cycleMethod; this.colorSpace = colorSpace; // we can avoid copying this array since we do not modify its values this.fractions = fractions; // note that only one of these values can ever be non-null (we either // store the fast gradient array or the slow one, but never both // at the same time) int[] gradient = (mgp.gradient != null) ? mgp.gradient.get() : null; int[][] gradients = (mgp.gradients != null) ? mgp.gradients.get() : null; if (gradient == null && gradients == null) { // we need to (re)create the appropriate values calculateLookupData(colors); // now cache the calculated values in the // MultipleGradientPaint instance for future use mgp.model = this.model; mgp.normalizedIntervals = this.normalizedIntervals; mgp.isSimpleLookup = this.isSimpleLookup; if (isSimpleLookup) { // only cache the fast array mgp.fastGradientArraySize = this.fastGradientArraySize; mgp.gradient = new SoftReference<int[]>(this.gradient); } else { // only cache the slow array mgp.gradients = new SoftReference<int[][]>(this.gradients); } } else { // use the values cached in the MultipleGradientPaint instance this.model = mgp.model; this.normalizedIntervals = mgp.normalizedIntervals; this.isSimpleLookup = mgp.isSimpleLookup; this.gradient = gradient; this.fastGradientArraySize = mgp.fastGradientArraySize; this.gradients = gradients; } } /** * This function is the meat of this class. It calculates an array of * gradient colors based on an array of fractions and color values at * those fractions. */ private void calculateLookupData(Color[] colors) { Color[] normalizedColors; if (colorSpace == ColorSpaceType.LINEAR_RGB) { // create a new colors array normalizedColors = new Color[colors.length]; // convert the colors using the lookup table for (int i = 0; i < colors.length; i++) { int argb = colors[i].getRGB(); int a = argb >>> 24; int r = SRGBtoLinearRGB[(argb >> 16) & 0xff]; int g = SRGBtoLinearRGB[(argb >> 8) & 0xff]; int b = SRGBtoLinearRGB[(argb ) & 0xff]; normalizedColors[i] = new Color(r, g, b, a); } } else { // we can just use this array by reference since we do not // modify its values in the case of SRGB normalizedColors = colors; } // this will store the intervals (distances) between gradient stops normalizedIntervals = new float[fractions.length-1]; // convert from fractions into intervals for (int i = 0; i < normalizedIntervals.length; i++) { // interval distance is equal to the difference in positions normalizedIntervals[i] = this.fractions[i+1] - this.fractions[i]; } // initialize to be fully opaque for ANDing with colors transparencyTest = 0xff000000; // array of interpolation arrays gradients = new int[normalizedIntervals.length][]; // find smallest interval float Imin = 1; for (int i = 0; i < normalizedIntervals.length; i++) { Imin = (Imin > normalizedIntervals[i]) ? normalizedIntervals[i] : Imin; } // Estimate the size of the entire gradients array. // This is to prevent a tiny interval from causing the size of array // to explode. If the estimated size is too large, break to using // separate arrays for each interval, and using an indexing scheme at // look-up time. int estimatedSize = 0; for (int i = 0; i < normalizedIntervals.length; i++) { estimatedSize += (normalizedIntervals[i]/Imin) * GRADIENT_SIZE; } if (estimatedSize > MAX_GRADIENT_ARRAY_SIZE) { // slow method calculateMultipleArrayGradient(normalizedColors); } else { // fast method calculateSingleArrayGradient(normalizedColors, Imin); } // use the most "economical" model if ((transparencyTest >>> 24) == 0xff) { model = xrgbmodel; } else { model = ColorModel.getRGBdefault(); } } /** * FAST LOOKUP METHOD * * This method calculates the gradient color values and places them in a * single int array, gradient[]. It does this by allocating space for * each interval based on its size relative to the smallest interval in * the array. The smallest interval is allocated 255 interpolated values * (the maximum number of unique in-between colors in a 24 bit color * system), and all other intervals are allocated * size = (255 * the ratio of their size to the smallest interval). * * This scheme expedites a speedy retrieval because the colors are * distributed along the array according to their user-specified * distribution. All that is needed is a relative index from 0 to 1. * * The only problem with this method is that the possibility exists for * the array size to balloon in the case where there is a * disproportionately small gradient interval. In this case the other * intervals will be allocated huge space, but much of that data is * redundant. We thus need to use the space conserving scheme below. * * @param Imin the size of the smallest interval */ private void calculateSingleArrayGradient(Color[] colors, float Imin) { // set the flag so we know later it is a simple (fast) lookup isSimpleLookup = true; // 2 colors to interpolate int rgb1, rgb2; //the eventual size of the single array int gradientsTot = 1; // for every interval (transition between 2 colors) for (int i = 0; i < gradients.length; i++) { // create an array whose size is based on the ratio to the // smallest interval int nGradients = (int)((normalizedIntervals[i]/Imin)*255f); gradientsTot += nGradients; gradients[i] = new int[nGradients]; // the 2 colors (keyframes) to interpolate between rgb1 = colors[i].getRGB(); rgb2 = colors[i+1].getRGB(); // fill this array with the colors in between rgb1 and rgb2 interpolate(rgb1, rgb2, gradients[i]); // if the colors are opaque, transparency should still // be 0xff000000 transparencyTest &= rgb1; transparencyTest &= rgb2; } // put all gradients in a single array gradient = new int[gradientsTot]; int curOffset = 0; for (int i = 0; i < gradients.length; i++){ System.arraycopy(gradients[i], 0, gradient, curOffset, gradients[i].length); curOffset += gradients[i].length; } gradient[gradient.length-1] = colors[colors.length-1].getRGB(); // if interpolation occurred in Linear RGB space, convert the // gradients back to sRGB using the lookup table if (colorSpace == ColorSpaceType.LINEAR_RGB) { for (int i = 0; i < gradient.length; i++) { gradient[i] = convertEntireColorLinearRGBtoSRGB(gradient[i]); } } fastGradientArraySize = gradient.length - 1; } /** * SLOW LOOKUP METHOD * * This method calculates the gradient color values for each interval and * places each into its own 255 size array. The arrays are stored in * gradients[][]. (255 is used because this is the maximum number of * unique colors between 2 arbitrary colors in a 24 bit color system.) * * This method uses the minimum amount of space (only 255 * number of * intervals), but it aggravates the lookup procedure, because now we * have to find out which interval to select, then calculate the index * within that interval. This causes a significant performance hit, * because it requires this calculation be done for every point in * the rendering loop. * * For those of you who are interested, this is a classic example of the * time-space tradeoff. */ private void calculateMultipleArrayGradient(Color[] colors) { // set the flag so we know later it is a non-simple lookup isSimpleLookup = false; // 2 colors to interpolate int rgb1, rgb2; // for every interval (transition between 2 colors) for (int i = 0; i < gradients.length; i++){ // create an array of the maximum theoretical size for // each interval gradients[i] = new int[GRADIENT_SIZE]; // get the 2 colors rgb1 = colors[i].getRGB(); rgb2 = colors[i+1].getRGB(); // fill this array with the colors in between rgb1 and rgb2 interpolate(rgb1, rgb2, gradients[i]); // if the colors are opaque, transparency should still // be 0xff000000 transparencyTest &= rgb1; transparencyTest &= rgb2; } // if interpolation occurred in Linear RGB space, convert the // gradients back to SRGB using the lookup table if (colorSpace == ColorSpaceType.LINEAR_RGB) { for (int j = 0; j < gradients.length; j++) { for (int i = 0; i < gradients[j].length; i++) { gradients[j][i] = convertEntireColorLinearRGBtoSRGB(gradients[j][i]); } } } } /** * Yet another helper function. This one linearly interpolates between * 2 colors, filling up the output array. * * @param rgb1 the start color * @param rgb2 the end color * @param output the output array of colors; must not be null */ private void interpolate(int rgb1, int rgb2, int[] output) { // color components int a1, r1, g1, b1, da, dr, dg, db; // step between<SUF> float stepSize = 1.0f / output.length; // extract color components from packed integer a1 = (rgb1 >> 24) & 0xff; r1 = (rgb1 >> 16) & 0xff; g1 = (rgb1 >> 8) & 0xff; b1 = (rgb1 ) & 0xff; // calculate the total change in alpha, red, green, blue da = ((rgb2 >> 24) & 0xff) - a1; dr = ((rgb2 >> 16) & 0xff) - r1; dg = ((rgb2 >> 8) & 0xff) - g1; db = ((rgb2 ) & 0xff) - b1; // for each step in the interval calculate the in-between color by // multiplying the normalized current position by the total color // change (0.5 is added to prevent truncation round-off error) for (int i = 0; i < output.length; i++) { output[i] = (((int) ((a1 + i * da * stepSize) + 0.5) << 24)) | (((int) ((r1 + i * dr * stepSize) + 0.5) << 16)) | (((int) ((g1 + i * dg * stepSize) + 0.5) << 8)) | (((int) ((b1 + i * db * stepSize) + 0.5) )); } } /** * Yet another helper function. This one extracts the color components * of an integer RGB triple, converts them from LinearRGB to SRGB, then * recompacts them into an int. */ private int convertEntireColorLinearRGBtoSRGB(int rgb) { // color components int a1, r1, g1, b1; // extract red, green, blue components a1 = (rgb >> 24) & 0xff; r1 = (rgb >> 16) & 0xff; g1 = (rgb >> 8) & 0xff; b1 = (rgb ) & 0xff; // use the lookup table r1 = LinearRGBtoSRGB[r1]; g1 = LinearRGBtoSRGB[g1]; b1 = LinearRGBtoSRGB[b1]; // re-compact the components return ((a1 << 24) | (r1 << 16) | (g1 << 8) | (b1 )); } /** * Helper function to index into the gradients array. This is necessary * because each interval has an array of colors with uniform size 255. * However, the color intervals are not necessarily of uniform length, so * a conversion is required. * * @param position the unmanipulated position, which will be mapped * into the range 0 to 1 * @return integer color to display */ protected final int indexIntoGradientsArrays(float position) { // first, manipulate position value depending on the cycle method if (cycleMethod == CycleMethod.NO_CYCLE) { if (position > 1) { // upper bound is 1 position = 1; } else if (position < 0) { // lower bound is 0 position = 0; } } else if (cycleMethod == CycleMethod.REPEAT) { // get the fractional part // (modulo behavior discards integer component) position = position - (int)position; //position should now be between -1 and 1 if (position < 0) { // force it to be in the range 0-1 position = position + 1; } } else { // cycleMethod == CycleMethod.REFLECT if (position < 0) { // take absolute value position = -position; } // get the integer part int part = (int)position; // get the fractional part position = position - part; if ((part & 1) == 1) { // integer part is odd, get reflected color instead position = 1 - position; } } // now, get the color based on this 0-1 position... if (isSimpleLookup) { // easy to compute: just scale index by array size return gradient[(int)(position * fastGradientArraySize)]; } else { // more complicated computation, to save space // for all the gradient interval arrays for (int i = 0; i < gradients.length; i++) { if (position < fractions[i+1]) { // this is the array we want float delta = position - fractions[i]; // this is the interval we want int index = (int)((delta / normalizedIntervals[i]) * (GRADIENT_SIZE_INDEX)); return gradients[i][index]; } } } return gradients[gradients.length - 1][GRADIENT_SIZE_INDEX]; } /** * Helper function to convert a color component in sRGB space to linear * RGB space. Used to build a static lookup table. */ private static int convertSRGBtoLinearRGB(int color) { float input, output; input = color / 255.0f; if (input <= 0.04045f) { output = input / 12.92f; } else { output = (float)Math.pow((input + 0.055) / 1.055, 2.4); } return Math.round(output * 255.0f); } /** * Helper function to convert a color component in linear RGB space to * SRGB space. Used to build a static lookup table. */ private static int convertLinearRGBtoSRGB(int color) { float input, output; input = color/255.0f; if (input <= 0.0031308) { output = input * 12.92f; } else { output = (1.055f * ((float) Math.pow(input, (1.0 / 2.4)))) - 0.055f; } return Math.round(output * 255.0f); } /** * {@inheritDoc} */ public final Raster getRaster(int x, int y, int w, int h) { // If working raster is big enough, reuse it. Otherwise, // build a large enough new one. Raster raster = saved; if (raster == null || raster.getWidth() < w || raster.getHeight() < h) { raster = getCachedRaster(model, w, h); saved = raster; } // Access raster internal int array. Because we use a DirectColorModel, // we know the DataBuffer is of type DataBufferInt and the SampleModel // is SinglePixelPackedSampleModel. // Adjust for initial offset in DataBuffer and also for the scanline // stride. // These calls make the DataBuffer non-acceleratable, but the // Raster is never Stable long enough to accelerate anyway... DataBufferInt rasterDB = (DataBufferInt)raster.getDataBuffer(); int[] pixels = rasterDB.getData(0); int off = rasterDB.getOffset(); int scanlineStride = ((SinglePixelPackedSampleModel) raster.getSampleModel()).getScanlineStride(); int adjust = scanlineStride - w; fillRaster(pixels, off, adjust, x, y, w, h); // delegate to subclass return raster; } protected abstract void fillRaster(int pixels[], int off, int adjust, int x, int y, int w, int h); /** * Took this cacheRaster code from GradientPaint. It appears to recycle * rasters for use by any other instance, as long as they are sufficiently * large. */ private static synchronized Raster getCachedRaster(ColorModel cm, int w, int h) { if (cm == cachedModel) { if (cached != null) { Raster ras = cached.get(); if (ras != null && ras.getWidth() >= w && ras.getHeight() >= h) { cached = null; return ras; } } } return cm.createCompatibleWritableRaster(w, h); } /** * Took this cacheRaster code from GradientPaint. It appears to recycle * rasters for use by any other instance, as long as they are sufficiently * large. */ private static synchronized void putCachedRaster(ColorModel cm, Raster ras) { if (cached != null) { Raster cras = cached.get(); if (cras != null) { int cw = cras.getWidth(); int ch = cras.getHeight(); int iw = ras.getWidth(); int ih = ras.getHeight(); if (cw >= iw && ch >= ih) { return; } if (cw * ch >= iw * ih) { return; } } } cachedModel = cm; cached = new WeakReference<Raster>(ras); } /** * {@inheritDoc} */ public final void dispose() { if (saved != null) { putCachedRaster(model, saved); saved = null; } } /** * {@inheritDoc} */ public final ColorModel getColorModel() { return model; } }
14960_3
package nl.kaine; import io.github.cdimascio.dotenv.Dotenv; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.interactions.commands.build.Commands; import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.utils.cache.CacheFlag; import nl.kaine.commands.CommandHandler; import nl.kaine.commands.CommandManager; import nl.kaine.commands.Report; import nl.kaine.listeners.Embed; import nl.kaine.listeners.ReportListener; public class Main extends ListenerAdapter { public static String prefix = "$"; public static void main(String[] args) throws InterruptedException { // Load env file Dotenv config = Dotenv.configure().load(); String token = config.get("TOKEN"); // Bot startup sequence JDA jda = JDABuilder.createDefault(token) .disableCache(CacheFlag.VOICE_STATE, CacheFlag.EMOJI, CacheFlag.STICKER) .enableIntents(GatewayIntent.GUILD_MESSAGES) .build().awaitReady(); jda.getPresence().setActivity(Activity.listening("bot by: Kaine")); jda.getPresence().setStatus(OnlineStatus.ONLINE); jda.addEventListener( new Main(), new Report(), new ReportListener(), new CommandHandler(), new Embed(), new CommandManager()); Guild guild = jda.getGuildById("988150737714442321"); if (guild != null) { jda.updateCommands() .addCommands(Commands.slash("assist", "Command voor jouw hulp")) .addCommands(Commands.slash("report", "Rapporteer een lid")) .addCommands(Commands.slash("help", "Overzicht van commando's")) .queue(); } } } //TODO // Commando toevoegen aan slash-list, verder zie CommandHandler // Zorgen dat embed word gestuurd als .<command> word gedaan // CommandManager maken met prefix [$] (zie line: 21) & gemakkelijk commando's kan aanmaken. // /help commando fix op: "The application did not respond" // Fix reply report embed message // Ephemeral(true) op slashcommandinteractionevent // PREFIX commando's
zkainee/Cluster
src/main/java/nl/kaine/Main.java
761
// Zorgen dat embed word gestuurd als .<command> word gedaan
line_comment
nl
package nl.kaine; import io.github.cdimascio.dotenv.Dotenv; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.OnlineStatus; import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.hooks.ListenerAdapter; import net.dv8tion.jda.api.interactions.commands.build.Commands; import net.dv8tion.jda.api.requests.GatewayIntent; import net.dv8tion.jda.api.utils.cache.CacheFlag; import nl.kaine.commands.CommandHandler; import nl.kaine.commands.CommandManager; import nl.kaine.commands.Report; import nl.kaine.listeners.Embed; import nl.kaine.listeners.ReportListener; public class Main extends ListenerAdapter { public static String prefix = "$"; public static void main(String[] args) throws InterruptedException { // Load env file Dotenv config = Dotenv.configure().load(); String token = config.get("TOKEN"); // Bot startup sequence JDA jda = JDABuilder.createDefault(token) .disableCache(CacheFlag.VOICE_STATE, CacheFlag.EMOJI, CacheFlag.STICKER) .enableIntents(GatewayIntent.GUILD_MESSAGES) .build().awaitReady(); jda.getPresence().setActivity(Activity.listening("bot by: Kaine")); jda.getPresence().setStatus(OnlineStatus.ONLINE); jda.addEventListener( new Main(), new Report(), new ReportListener(), new CommandHandler(), new Embed(), new CommandManager()); Guild guild = jda.getGuildById("988150737714442321"); if (guild != null) { jda.updateCommands() .addCommands(Commands.slash("assist", "Command voor jouw hulp")) .addCommands(Commands.slash("report", "Rapporteer een lid")) .addCommands(Commands.slash("help", "Overzicht van commando's")) .queue(); } } } //TODO // Commando toevoegen aan slash-list, verder zie CommandHandler // Zorgen dat<SUF> // CommandManager maken met prefix [$] (zie line: 21) & gemakkelijk commando's kan aanmaken. // /help commando fix op: "The application did not respond" // Fix reply report embed message // Ephemeral(true) op slashcommandinteractionevent // PREFIX commando's
60475_0
package nl.kaine.network.command; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import nl.kaine.network.Network; public class ReplyCommand extends Command { private Network network; public ReplyCommand(Network network) { super("reply"); this.network = network; } @Override public void execute(CommandSender sender, String[] args) { if (sender instanceof ProxiedPlayer) { ProxiedPlayer player = (ProxiedPlayer) sender; if (args.length >= 1) { if (network.getRecentMessages().containsKey(player.getUniqueId())) { ProxiedPlayer target = ProxyServer.getInstance().getPlayer(network.getRecentMessages().get(player.getUniqueId())); if (target != null) { StringBuilder builder = new StringBuilder(); // Loop door argument die achter elke string een SPATIE plaatst. for (int i = 0; i < args.length; i++) { builder.append(args[1]).append(" "); } player.sendMessage(ChatColor.GRAY + "Jij -> " + ChatColor.WHITE + target.getName() + ChatColor.GRAY + " : " + ChatColor.GRAY + builder); target.sendMessage(player.getName() + ChatColor.GRAY + " -> jou" + " : " + ChatColor.GRAY + builder); } else { player.sendMessage(ChatColor.RED + "Deze speler offline gegaan sinds dat je laatste bericht."); network.getRecentMessages().remove(player.getUniqueId()); } } else { player.sendMessage(ChatColor.RED + "Je hebt niemand om op te reageren."); } } else { player.sendMessage(ChatColor.RED + "Verkeerd gebruik! Gebruik: /message <speler> <bericht>."); } } } }
zkainee/CrossConnect
src/main/java/nl/kaine/network/command/ReplyCommand.java
592
// Loop door argument die achter elke string een SPATIE plaatst.
line_comment
nl
package nl.kaine.network.command; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; import nl.kaine.network.Network; public class ReplyCommand extends Command { private Network network; public ReplyCommand(Network network) { super("reply"); this.network = network; } @Override public void execute(CommandSender sender, String[] args) { if (sender instanceof ProxiedPlayer) { ProxiedPlayer player = (ProxiedPlayer) sender; if (args.length >= 1) { if (network.getRecentMessages().containsKey(player.getUniqueId())) { ProxiedPlayer target = ProxyServer.getInstance().getPlayer(network.getRecentMessages().get(player.getUniqueId())); if (target != null) { StringBuilder builder = new StringBuilder(); // Loop door<SUF> for (int i = 0; i < args.length; i++) { builder.append(args[1]).append(" "); } player.sendMessage(ChatColor.GRAY + "Jij -> " + ChatColor.WHITE + target.getName() + ChatColor.GRAY + " : " + ChatColor.GRAY + builder); target.sendMessage(player.getName() + ChatColor.GRAY + " -> jou" + " : " + ChatColor.GRAY + builder); } else { player.sendMessage(ChatColor.RED + "Deze speler offline gegaan sinds dat je laatste bericht."); network.getRecentMessages().remove(player.getUniqueId()); } } else { player.sendMessage(ChatColor.RED + "Je hebt niemand om op te reageren."); } } else { player.sendMessage(ChatColor.RED + "Verkeerd gebruik! Gebruik: /message <speler> <bericht>."); } } } }
29171_1
package com.zoonref.viewbehavior; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.util.AttributeSet; import android.view.View; /** * Created by zoonooz on 5/1/2018 AD. * Base behavior for percentage driven behaviors. */ public class PercentageViewBehavior<V extends View> extends CoordinatorLayout.Behavior<V> { static final int UNSPECIFIED_INT = Integer.MAX_VALUE; static final float UNSPECIFIED_FLOAT = Float.MAX_VALUE; /** * Depend on the dependency view height */ public static final int DEPEND_TYPE_HEIGHT = 0; /** * Depend on the dependency view width */ public static final int DEPEND_TYPE_WIDTH = 1; /** * Depend on the dependency view x position */ public static final int DEPEND_TYPE_X = 2; /** * Depend on the dependency view y position */ public static final int DEPEND_TYPE_Y = 3; private int mDependType; private int mDependViewId; private int mDependTarget; private int mDependStartX; private int mDependStartY; private int mDependStartWidth; private int mDependStartHeight; /** * Is the values prepared to be use */ private boolean isPrepared; /** * Creates a new behavior whose parameters come from the specified context and * attributes set. * * @param context the application environment * @param attrs the set of attributes holding the target and animation parameters */ PercentageViewBehavior(Context context, AttributeSet attrs) { super(context, attrs); // setting values TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewBehavior); mDependViewId = a.getResourceId(R.styleable.ViewBehavior_behavior_dependsOn, 0); mDependType = a.getInt(R.styleable.ViewBehavior_behavior_dependType, DEPEND_TYPE_WIDTH); mDependTarget = a.getDimensionPixelOffset(R.styleable.ViewBehavior_behavior_dependTarget, UNSPECIFIED_INT); a.recycle(); } PercentageViewBehavior(@NonNull Builder builder) { mDependViewId = builder.dependsOn; mDependType = builder.dependsType; mDependTarget = builder.targetValue; } /** * Call this before making any changes to the view to setup values * * @param parent coordinator layout as parent * @param child view that will move when dependency changed * @param dependency dependency view */ void prepare(CoordinatorLayout parent, V child, View dependency) { mDependStartX = (int) dependency.getX(); mDependStartY = (int) dependency.getY(); mDependStartWidth = dependency.getWidth(); mDependStartHeight = dependency.getHeight(); isPrepared = true; } @Override public boolean layoutDependsOn(CoordinatorLayout parent, V child, View dependency) { // depend on the view that has the same id return dependency.getId() == mDependViewId; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View dependency) { // first time, prepare values before continue if (!isPrepared) { prepare(parent, child, dependency); } updateView(child, dependency); return false; } @Override public boolean onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) { boolean bool = super.onLayoutChild(parent, child, layoutDirection); if (isPrepared) { updateView(child, parent.getDependencies(child).get(0)); } return bool; } /** * Update the child view from the dependency states * * @param child child view * @param dependency dependency view */ void updateView(V child, View dependency) { float percent = 0; float start = 0; float current = 0; float end = UNSPECIFIED_INT; switch (mDependType) { case DEPEND_TYPE_WIDTH: start = mDependStartWidth; current = dependency.getWidth(); end = mDependTarget; break; case DEPEND_TYPE_HEIGHT: start = mDependStartHeight; current = dependency.getHeight(); end = mDependTarget; break; case DEPEND_TYPE_X: start = mDependStartX; current = dependency.getX(); end = mDependTarget; break; case DEPEND_TYPE_Y: start = mDependStartY; current = dependency.getY(); end = mDependTarget; break; } // need to define target value according to the depend type, if not then skip if (end != UNSPECIFIED_INT) { percent = Math.abs(current - start) / Math.abs(end - start); } updateViewWithPercent(child, percent > 1 ? 1 : percent); } /** * Update the child view from the progress of changed dependency view * * @param child child view * @param percent progress of dependency changed 0.0f to 1.0f */ void updateViewWithPercent(V child, float percent) { if (child instanceof PercentageChildView) { ((PercentageChildView) child).onPercentageBehaviorChange(this, percent); } } /** * Builder class */ static abstract class Builder<T extends Builder> { private int dependsOn; private int dependsType = UNSPECIFIED_INT; private int targetValue = UNSPECIFIED_INT; abstract T getThis(); T dependsOn(@IdRes int dependsOn, int dependsType) { this.dependsOn = dependsOn; this.dependsType = dependsType; return getThis(); } T targetValue(int targetValue) { this.targetValue = targetValue; return getThis(); } } }
zoonooz/simple-view-behavior
library/src/main/java/com/zoonref/viewbehavior/PercentageViewBehavior.java
1,679
/** * Depend on the dependency view height */
block_comment
nl
package com.zoonref.viewbehavior; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.design.widget.CoordinatorLayout; import android.util.AttributeSet; import android.view.View; /** * Created by zoonooz on 5/1/2018 AD. * Base behavior for percentage driven behaviors. */ public class PercentageViewBehavior<V extends View> extends CoordinatorLayout.Behavior<V> { static final int UNSPECIFIED_INT = Integer.MAX_VALUE; static final float UNSPECIFIED_FLOAT = Float.MAX_VALUE; /** * Depend on the<SUF>*/ public static final int DEPEND_TYPE_HEIGHT = 0; /** * Depend on the dependency view width */ public static final int DEPEND_TYPE_WIDTH = 1; /** * Depend on the dependency view x position */ public static final int DEPEND_TYPE_X = 2; /** * Depend on the dependency view y position */ public static final int DEPEND_TYPE_Y = 3; private int mDependType; private int mDependViewId; private int mDependTarget; private int mDependStartX; private int mDependStartY; private int mDependStartWidth; private int mDependStartHeight; /** * Is the values prepared to be use */ private boolean isPrepared; /** * Creates a new behavior whose parameters come from the specified context and * attributes set. * * @param context the application environment * @param attrs the set of attributes holding the target and animation parameters */ PercentageViewBehavior(Context context, AttributeSet attrs) { super(context, attrs); // setting values TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewBehavior); mDependViewId = a.getResourceId(R.styleable.ViewBehavior_behavior_dependsOn, 0); mDependType = a.getInt(R.styleable.ViewBehavior_behavior_dependType, DEPEND_TYPE_WIDTH); mDependTarget = a.getDimensionPixelOffset(R.styleable.ViewBehavior_behavior_dependTarget, UNSPECIFIED_INT); a.recycle(); } PercentageViewBehavior(@NonNull Builder builder) { mDependViewId = builder.dependsOn; mDependType = builder.dependsType; mDependTarget = builder.targetValue; } /** * Call this before making any changes to the view to setup values * * @param parent coordinator layout as parent * @param child view that will move when dependency changed * @param dependency dependency view */ void prepare(CoordinatorLayout parent, V child, View dependency) { mDependStartX = (int) dependency.getX(); mDependStartY = (int) dependency.getY(); mDependStartWidth = dependency.getWidth(); mDependStartHeight = dependency.getHeight(); isPrepared = true; } @Override public boolean layoutDependsOn(CoordinatorLayout parent, V child, View dependency) { // depend on the view that has the same id return dependency.getId() == mDependViewId; } @Override public boolean onDependentViewChanged(CoordinatorLayout parent, V child, View dependency) { // first time, prepare values before continue if (!isPrepared) { prepare(parent, child, dependency); } updateView(child, dependency); return false; } @Override public boolean onLayoutChild(CoordinatorLayout parent, V child, int layoutDirection) { boolean bool = super.onLayoutChild(parent, child, layoutDirection); if (isPrepared) { updateView(child, parent.getDependencies(child).get(0)); } return bool; } /** * Update the child view from the dependency states * * @param child child view * @param dependency dependency view */ void updateView(V child, View dependency) { float percent = 0; float start = 0; float current = 0; float end = UNSPECIFIED_INT; switch (mDependType) { case DEPEND_TYPE_WIDTH: start = mDependStartWidth; current = dependency.getWidth(); end = mDependTarget; break; case DEPEND_TYPE_HEIGHT: start = mDependStartHeight; current = dependency.getHeight(); end = mDependTarget; break; case DEPEND_TYPE_X: start = mDependStartX; current = dependency.getX(); end = mDependTarget; break; case DEPEND_TYPE_Y: start = mDependStartY; current = dependency.getY(); end = mDependTarget; break; } // need to define target value according to the depend type, if not then skip if (end != UNSPECIFIED_INT) { percent = Math.abs(current - start) / Math.abs(end - start); } updateViewWithPercent(child, percent > 1 ? 1 : percent); } /** * Update the child view from the progress of changed dependency view * * @param child child view * @param percent progress of dependency changed 0.0f to 1.0f */ void updateViewWithPercent(V child, float percent) { if (child instanceof PercentageChildView) { ((PercentageChildView) child).onPercentageBehaviorChange(this, percent); } } /** * Builder class */ static abstract class Builder<T extends Builder> { private int dependsOn; private int dependsType = UNSPECIFIED_INT; private int targetValue = UNSPECIFIED_INT; abstract T getThis(); T dependsOn(@IdRes int dependsOn, int dependsType) { this.dependsOn = dependsOn; this.dependsType = dependsType; return getThis(); } T targetValue(int targetValue) { this.targetValue = targetValue; return getThis(); } } }
149009_3
/****************************************************************************** * The contents of this file are subject to the Compiere License Version 1.1 * ("License"); You may not use this file except in compliance with the License * You may obtain a copy of the License at http://www.compiere.org/license.html * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * The Original Code is Compiere ERP & CRM Business Solution * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc. * * Copyright (C) 2005 Robert KLEIN. [email protected] * * Contributor(s): ______________________________________. *****************************************************************************/ package org.compiere.FA; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.compiere.model.MAssetAcct; import org.compiere.model.MAssetChange; import org.compiere.model.MRefList; import org.compiere.model.X_A_Asset; import org.compiere.model.X_A_Asset_Addition; import org.compiere.model.X_A_Asset_Group_Acct; import org.compiere.model.X_A_Depreciation_Workfile; import org.compiere.model.X_GL_JournalLine; import org.compiere.process.ProcessInfoParameter; import org.compiere.process.SvrProcess; import org.compiere.util.DB; /** * Create Asset from FA GL Process * * @author Rob Klein * @version $Id: CreateGLAsset.java,v 1.0 $ */ public class CreateGLAsset extends SvrProcess { private int p_client = 0; //private int p_org = 0; /** * Prepare - e.g., get Parameters. */ protected void prepare() { ProcessInfoParameter[] para = getParameter(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("AD_Client_ID")) p_client = para[i].getParameterAsInt(); else log.info("prepare - Unknown Parameter: " + name); } } // prepare /** * Process Invoices * @return info * @throws Exception */ protected String doIt() throws java.lang.Exception { log.info("Starting inbound invoice process"); // int uselifemonths = 0; // int uselifeyears = 0; String sql =" SELECT * FROM GL_JOURNALLINE WHERE A_Processed <> 'Y' and AD_Client_ID = ?" + " and A_CreateAsset = 'Y' and Processed = 'Y'"; log.info(sql); PreparedStatement pstmt = null; pstmt = DB.prepareStatement(sql,get_TrxName()); ResultSet rs = null; try { pstmt.setInt(1, p_client); rs = pstmt.executeQuery(); while (rs.next()){ X_A_Asset asset = new X_A_Asset (getCtx(), rs.getInt("A_Asset_ID"), get_TrxName()); X_GL_JournalLine JVLine = new X_GL_JournalLine (getCtx(), rs.getInt("GL_JournalLine_ID"), get_TrxName()); String sql2 ="SELECT C.AccountType FROM GL_JournalLine A, C_ValidCombination B, C_ElementValue C WHERE A.GL_JournalLine_ID = ?" + " and A.C_ValidCombination_ID = B.C_ValidCombination_ID and B.Account_ID = C.C_ElementValue_ID"; String acctType = DB.getSQLValueString(get_TrxName(),sql2, JVLine.getGL_JournalLine_ID()); if (acctType.equals("A")){ sql ="SELECT * FROM A_Asset_Group_Acct WHERE A_Asset_Group_ID = ? AND IsActive='Y'"; log.info("yes"); pstmt = null; pstmt = DB.prepareStatement(sql,get_TrxName()); if(asset.getA_Asset_ID()==0) { int groupId = JVLine.getA_Asset_Group_ID(); pstmt.setInt(1, groupId); } else pstmt.setInt(1, asset.getA_Asset_Group_ID()); ResultSet rs2 = pstmt.executeQuery(); while (rs2.next()){ X_A_Asset_Group_Acct assetgrpacct = new X_A_Asset_Group_Acct (getCtx(), rs2,get_TrxName()); MAssetAcct assetacct = new MAssetAcct (getCtx(), 0, get_TrxName()); if (assetgrpacct.isProcessing()== true){ sql2 = "SELECT COUNT(*) FROM A_Depreciation_Workfile WHERE A_Asset_ID=? and" + " PostingType = '"+assetgrpacct.getPostingType()+"'"; if (DB.getSQLValue(get_TrxName(),sql2, asset.getA_Asset_ID())== 0) { asset.setIsOwned(true); asset.setIsDepreciated(assetgrpacct.isProcessing()); asset.setA_Asset_CreateDate(JVLine.getDateAcct()); asset.setIsInPosession(true); if(JVLine.getDescription()!= null) asset.setName(JVLine.getDescription()); else asset.setName("Asset created from JV"); asset.setHelp("Created from JV #" + JVLine.getGL_Journal_ID() + " on line #" + JVLine.getLine()); asset.setDescription(JVLine.getDescription()); asset.setUseLifeMonths(assetgrpacct.getUseLifeMonths()); asset.setUseLifeYears(assetgrpacct.getUseLifeYears()); asset.setA_Asset_Group_ID(assetgrpacct.getA_Asset_Group_ID()); asset.setA_QTY_Current(JVLine.getQty()); asset.setA_QTY_Original(JVLine.getQty()); asset.saveEx(); asset.setA_Parent_Asset_ID(asset.getA_Asset_ID()); asset.saveEx(); boolean isdepreciate = assetgrpacct.isProcessing(); if (isdepreciate == true) { assetacct.setPostingType(assetgrpacct.getPostingType()); assetacct.setA_Split_Percent(assetgrpacct.getA_Split_Percent()); assetacct.setA_Depreciation_Conv_ID(assetgrpacct.getConventionType()); assetacct.setA_Asset_ID(asset.getA_Asset_ID()); assetacct.setA_Depreciation_ID(assetgrpacct.getDepreciationType()); assetacct.setA_Asset_Spread_ID(assetgrpacct.getA_Asset_Spread_Type()); assetacct.setA_Period_Start(1); if (asset.getUseLifeMonths() == 0 & asset.getUseLifeYears() == 0){ assetacct.setA_Period_End(assetgrpacct.getUseLifeMonths()); asset.setUseLifeYears(assetgrpacct.getUseLifeYears()); asset.setUseLifeMonths(assetgrpacct.getUseLifeMonths()); asset.setIsDepreciated(true); asset.setIsOwned(true); asset.saveEx(); // uselifemonths = assetgrpacct.getUseLifeMonths(); // uselifeyears = assetgrpacct.getUseLifeYears(); } else if(asset.getUseLifeMonths() == 0){ assetacct.setA_Period_End(asset.getUseLifeYears()*12); asset.setUseLifeMonths(asset.getUseLifeYears()*12); asset.setIsDepreciated(true); asset.setIsOwned(true); asset.saveEx(); // uselifemonths = asset.getUseLifeYears()*12; // uselifeyears = asset.getUseLifeYears(); } else{ assetacct.setA_Period_End(asset.getUseLifeMonths()); // uselifemonths = asset.getUseLifeMonths(); // uselifeyears = asset.getUseLifeYears(); } assetacct.setA_Depreciation_Method_ID(assetgrpacct.getA_Depreciation_Calc_Type()); assetacct.setA_Asset_Acct(assetgrpacct.getA_Asset_Acct()); assetacct.setC_AcctSchema_ID(assetgrpacct.getC_AcctSchema_ID()); assetacct.setA_Salvage_Value(new BigDecimal (0.0)); assetacct.setA_Accumdepreciation_Acct(assetgrpacct.getA_Accumdepreciation_Acct()); assetacct.setA_Depreciation_Acct(assetgrpacct.getA_Depreciation_Acct()); assetacct.setA_Disposal_Revenue(assetgrpacct.getA_Disposal_Revenue()); assetacct.setA_Disposal_Loss(assetgrpacct.getA_Disposal_Loss()); assetacct.setA_Reval_Accumdep_Offset_Cur(assetgrpacct.getA_Reval_Accumdep_Offset_Cur()); assetacct.setA_Reval_Accumdep_Offset_Prior(assetgrpacct.getA_Reval_Accumdep_Offset_Prior()); assetacct.setA_Reval_Cal_Method(assetgrpacct.getA_Reval_Cal_Method()); assetacct.setA_Reval_Cost_Offset(assetgrpacct.getA_Reval_Cost_Offset()); assetacct.setA_Reval_Cost_Offset_Prior(assetgrpacct.getA_Reval_Cost_Offset_Prior()); assetacct.setA_Reval_Depexp_Offset(assetgrpacct.getA_Reval_Depexp_Offset()); assetacct.setA_Depreciation_Manual_Amount(assetgrpacct.getA_Depreciation_Manual_Amount()); assetacct.setA_Depreciation_Manual_Period(assetgrpacct.getA_Depreciation_Manual_Period()); assetacct.setA_Depreciation_Table_Header_ID(assetgrpacct.getA_Depreciation_Table_Header_ID()); assetacct.setA_Depreciation_Variable_Perc(assetgrpacct.getA_Depreciation_Variable_Perc()); assetacct.setProcessing(false); assetacct.saveEx(); MAssetChange change = new MAssetChange (getCtx(), 0, get_TrxName()); change.setPostingType(assetacct.getPostingType()); change.setA_Split_Percent(assetacct.getA_Split_Percent()); change.setConventionType(assetacct.getA_Depreciation_Conv_ID()); change.setA_Asset_ID(asset.getA_Asset_ID()); change.setDepreciationType(assetacct.getA_Depreciation_ID()); change.setA_Asset_Spread_Type(assetacct.getA_Asset_Spread_ID()); change.setA_Period_Start(assetacct.getA_Period_Start()); change.setA_Period_End(assetacct.getA_Period_End()); change.setIsInPosession(asset.isOwned()); change.setIsDisposed(asset.isDisposed()); change.setIsDepreciated(asset.isDepreciated()); change.setIsFullyDepreciated(asset.isFullyDepreciated()); change.setA_Depreciation_Calc_Type(assetacct.getA_Depreciation_Method_ID()); change.setA_Asset_Acct(assetacct.getA_Asset_Acct()); change.setC_AcctSchema_ID(assetacct.getC_AcctSchema_ID()); change.setA_Accumdepreciation_Acct(assetacct.getA_Accumdepreciation_Acct()); change.setA_Depreciation_Acct(assetacct.getA_Depreciation_Acct()); change.setA_Disposal_Revenue(assetacct.getA_Disposal_Revenue()); change.setA_Disposal_Loss(assetacct.getA_Disposal_Loss()); change.setA_Reval_Accumdep_Offset_Cur(assetacct.getA_Reval_Accumdep_Offset_Cur()); change.setA_Reval_Accumdep_Offset_Prior(assetacct.getA_Reval_Accumdep_Offset_Prior()); change.setA_Reval_Cal_Method(assetacct.getA_Reval_Cal_Method()); change.setA_Reval_Cost_Offset(assetacct.getA_Reval_Cost_Offset()); change.setA_Reval_Cost_Offset_Prior(assetacct.getA_Reval_Cost_Offset_Prior()); change.setA_Reval_Depexp_Offset(assetacct.getA_Reval_Depexp_Offset()); change.setA_Depreciation_Manual_Amount(assetacct.getA_Depreciation_Manual_Amount()); change.setA_Depreciation_Manual_Period(assetacct.getA_Depreciation_Manual_Period()); change.setA_Depreciation_Table_Header_ID(assetacct.getA_Depreciation_Table_Header_ID()); change.setA_Depreciation_Variable_Perc(assetacct.getA_Depreciation_Variable_Perc()); change.setA_Parent_Asset_ID(asset.getA_Parent_Asset_ID()); change.setChangeType("CRT"); change.setTextDetails(MRefList.getListDescription (getCtx(),"A_Update_Type" , "CRT")); change.setIsInPosession(asset.isOwned()); change.setIsDisposed(asset.isDisposed()); change.setIsDepreciated(asset.isDepreciated()); change.setIsFullyDepreciated(asset.isFullyDepreciated()); change.setLot(asset.getLot()); change.setSerNo(asset.getSerNo()); change.setVersionNo(asset.getVersionNo()); change.setUseLifeMonths(asset.getUseLifeMonths()); change.setUseLifeYears(asset.getUseLifeYears()); change.setLifeUseUnits(asset.getLifeUseUnits()); change.setAssetDisposalDate(asset.getAssetDisposalDate()); change.setAssetServiceDate(asset.getAssetServiceDate()); change.setC_BPartner_Location_ID(asset.getC_BPartner_Location_ID()); change.setC_BPartner_ID(asset.getC_BPartner_ID()); change.setAssetValueAmt(JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr())); change.setA_Asset_CreateDate(asset.getA_Asset_CreateDate()); change.setAD_User_ID(asset.getAD_User_ID()); change.setC_Location_ID(asset.getC_Location_ID()); change.saveEx(); } X_A_Depreciation_Workfile assetwk = new X_A_Depreciation_Workfile (getCtx(), 0, get_TrxName()); assetwk.setA_Asset_ID(asset.getA_Asset_ID()); assetwk.setA_Life_Period(assetgrpacct.getUseLifeMonths()); assetwk.setA_Asset_Life_Years(assetgrpacct.getUseLifeYears()); assetwk.setA_Asset_Cost(assetwk.getA_Asset_Cost().add(JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr()))); assetwk.setA_Accumulated_Depr(new BigDecimal (0.0)); assetwk.setA_Salvage_Value(new BigDecimal (0.0)); assetwk.setA_Period_Posted(0); assetwk.setA_Asset_Life_Current_Year(new BigDecimal (0.0)); assetwk.setA_Curr_Dep_Exp(new BigDecimal (0.0)); assetwk.setA_QTY_Current(JVLine.getQty()); assetwk.setIsDepreciated(assetgrpacct.isProcessing()); assetwk.setPostingType(assetgrpacct.getPostingType()); assetwk.saveEx(); X_A_Asset_Addition assetadd = new X_A_Asset_Addition (getCtx(), 0, get_TrxName()); assetadd.setA_Asset_ID(asset.getA_Asset_ID()); assetadd.setAssetValueAmt(JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr())); assetadd.setA_SourceType("JRN"); assetadd.setA_CapvsExp("Cap"); assetadd.setA_QTY_Current(JVLine.getQty()); assetadd.setDocumentNo(""+JVLine.getGL_Journal_ID()); assetadd.setGL_JournalBatch_ID(JVLine.getGL_Journal_ID()); assetadd.setLine(JVLine.getLine()); assetadd.setDescription(JVLine.getDescription()); assetadd.setPostingType(assetwk.getPostingType()); assetadd.saveEx(); } else { sql2 ="SELECT * FROM A_Depreciation_Workfile WHERE A_Asset_ID = ? and PostingType = ?"; PreparedStatement pstmt2 = null; pstmt2 = DB.prepareStatement(sql2,get_TrxName()); ResultSet rs3 = null; log.info("no"); try { pstmt2.setInt(1, asset.getA_Asset_ID()); pstmt2.setString(2, assetgrpacct.getPostingType()); rs3 = pstmt2.executeQuery(); while (rs3.next()){ X_A_Depreciation_Workfile assetwk = new X_A_Depreciation_Workfile (getCtx(), rs3, get_TrxName()); assetwk.setA_Asset_ID(asset.getA_Asset_ID()); assetwk.setA_Life_Period(assetgrpacct.getUseLifeMonths()); assetwk.setA_Asset_Life_Years(assetgrpacct.getUseLifeYears()); assetwk.setA_Asset_Cost(assetwk.getA_Asset_Cost().add(JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr()))); assetwk.setA_QTY_Current(assetwk.getA_QTY_Current().add(JVLine.getQty())); assetwk.setIsDepreciated(assetgrpacct.isProcessing()); assetwk.saveEx(); X_A_Asset_Addition assetadd = new X_A_Asset_Addition (getCtx(), 0, get_TrxName()); assetadd.setA_Asset_ID(asset.getA_Asset_ID()); assetadd.setAssetValueAmt((JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr()))); assetadd.setA_SourceType("JRN"); assetadd.setA_CapvsExp("Cap"); assetadd.setA_QTY_Current(JVLine.getQty()); assetadd.setDocumentNo(""+JVLine.getGL_Journal_ID()); assetadd.setGL_JournalBatch_ID(JVLine.getGL_Journal_ID()); assetadd.setLine(JVLine.getLine()); assetadd.setDescription(JVLine.getDescription()); assetadd.setPostingType(assetwk.getPostingType()); assetadd.saveEx(); asset.setA_QTY_Original(assetadd.getA_QTY_Current().add(asset.getA_QTY_Original())); asset.setA_QTY_Current(assetadd.getA_QTY_Current().add(asset.getA_QTY_Current())); asset.saveEx(); MAssetChange change = new MAssetChange (getCtx(), 0, get_TrxName()); change.setA_Asset_ID(asset.getA_Asset_ID()); change.setChangeType("ADD"); change.setTextDetails(MRefList.getListDescription (getCtx(),"A_Update_Type" , "ADD")); change.setPostingType(assetwk.getPostingType()); change.setAssetValueAmt(assetadd.getAssetValueAmt()); change.setA_QTY_Current(assetadd.getA_QTY_Current()); change.saveEx(); } } catch (Exception e) { log.info("getAssets "+ e); } finally { DB.close(rs3, pstmt2); rs3 = null; pstmt2 = null; } } } } } else if (acctType.equals("E")) { X_A_Asset_Addition assetadd = new X_A_Asset_Addition (getCtx(), 0, get_TrxName()); assetadd.setA_Asset_ID(asset.getA_Asset_ID()); assetadd.setAssetValueAmt((JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr()))); assetadd.setA_SourceType("JRN"); assetadd.setA_CapvsExp("Exp"); assetadd.setA_QTY_Current(JVLine.getQty()); assetadd.setDocumentNo(""+JVLine.getGL_Journal_ID()); assetadd.setGL_JournalBatch_ID(JVLine.getGL_Journal_ID()); assetadd.setLine(JVLine.getLine()); assetadd.setDescription(JVLine.getDescription()); assetadd.setPostingType("A"); assetadd.saveEx(); MAssetChange change = new MAssetChange (getCtx(), 0, get_TrxName()); change.setA_Asset_ID(asset.getA_Asset_ID()); change.setA_QTY_Current(assetadd.getA_QTY_Current()); change.setChangeType("EXP"); change.setTextDetails(MRefList.getListDescription (getCtx(),"A_Update_Type" , "EXP")); assetadd.setPostingType("A"); change.setAssetValueAmt(assetadd.getAssetValueAmt()); change.setA_QTY_Current(assetadd.getA_QTY_Current()); change.saveEx(); } JVLine.set_ValueOfColumn(I_CustomColumn.A_Processed, Boolean.TRUE); JVLine.saveEx(); } rs.close(); pstmt.close(); pstmt = null; } catch (Exception e) { log.info("getAssets "+ e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } return ""; } // doIt } // CreateGLAsset
zoosky/adempiere
base/src/org/compiere/FA/CreateGLAsset.java
7,416
/** * Prepare - e.g., get Parameters. */
block_comment
nl
/****************************************************************************** * The contents of this file are subject to the Compiere License Version 1.1 * ("License"); You may not use this file except in compliance with the License * You may obtain a copy of the License at http://www.compiere.org/license.html * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for * the specific language governing rights and limitations under the License. * The Original Code is Compiere ERP & CRM Business Solution * The Initial Developer of the Original Code is Jorg Janke and ComPiere, Inc. * * Copyright (C) 2005 Robert KLEIN. [email protected] * * Contributor(s): ______________________________________. *****************************************************************************/ package org.compiere.FA; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.compiere.model.MAssetAcct; import org.compiere.model.MAssetChange; import org.compiere.model.MRefList; import org.compiere.model.X_A_Asset; import org.compiere.model.X_A_Asset_Addition; import org.compiere.model.X_A_Asset_Group_Acct; import org.compiere.model.X_A_Depreciation_Workfile; import org.compiere.model.X_GL_JournalLine; import org.compiere.process.ProcessInfoParameter; import org.compiere.process.SvrProcess; import org.compiere.util.DB; /** * Create Asset from FA GL Process * * @author Rob Klein * @version $Id: CreateGLAsset.java,v 1.0 $ */ public class CreateGLAsset extends SvrProcess { private int p_client = 0; //private int p_org = 0; /** * Prepare - e.g.,<SUF>*/ protected void prepare() { ProcessInfoParameter[] para = getParameter(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("AD_Client_ID")) p_client = para[i].getParameterAsInt(); else log.info("prepare - Unknown Parameter: " + name); } } // prepare /** * Process Invoices * @return info * @throws Exception */ protected String doIt() throws java.lang.Exception { log.info("Starting inbound invoice process"); // int uselifemonths = 0; // int uselifeyears = 0; String sql =" SELECT * FROM GL_JOURNALLINE WHERE A_Processed <> 'Y' and AD_Client_ID = ?" + " and A_CreateAsset = 'Y' and Processed = 'Y'"; log.info(sql); PreparedStatement pstmt = null; pstmt = DB.prepareStatement(sql,get_TrxName()); ResultSet rs = null; try { pstmt.setInt(1, p_client); rs = pstmt.executeQuery(); while (rs.next()){ X_A_Asset asset = new X_A_Asset (getCtx(), rs.getInt("A_Asset_ID"), get_TrxName()); X_GL_JournalLine JVLine = new X_GL_JournalLine (getCtx(), rs.getInt("GL_JournalLine_ID"), get_TrxName()); String sql2 ="SELECT C.AccountType FROM GL_JournalLine A, C_ValidCombination B, C_ElementValue C WHERE A.GL_JournalLine_ID = ?" + " and A.C_ValidCombination_ID = B.C_ValidCombination_ID and B.Account_ID = C.C_ElementValue_ID"; String acctType = DB.getSQLValueString(get_TrxName(),sql2, JVLine.getGL_JournalLine_ID()); if (acctType.equals("A")){ sql ="SELECT * FROM A_Asset_Group_Acct WHERE A_Asset_Group_ID = ? AND IsActive='Y'"; log.info("yes"); pstmt = null; pstmt = DB.prepareStatement(sql,get_TrxName()); if(asset.getA_Asset_ID()==0) { int groupId = JVLine.getA_Asset_Group_ID(); pstmt.setInt(1, groupId); } else pstmt.setInt(1, asset.getA_Asset_Group_ID()); ResultSet rs2 = pstmt.executeQuery(); while (rs2.next()){ X_A_Asset_Group_Acct assetgrpacct = new X_A_Asset_Group_Acct (getCtx(), rs2,get_TrxName()); MAssetAcct assetacct = new MAssetAcct (getCtx(), 0, get_TrxName()); if (assetgrpacct.isProcessing()== true){ sql2 = "SELECT COUNT(*) FROM A_Depreciation_Workfile WHERE A_Asset_ID=? and" + " PostingType = '"+assetgrpacct.getPostingType()+"'"; if (DB.getSQLValue(get_TrxName(),sql2, asset.getA_Asset_ID())== 0) { asset.setIsOwned(true); asset.setIsDepreciated(assetgrpacct.isProcessing()); asset.setA_Asset_CreateDate(JVLine.getDateAcct()); asset.setIsInPosession(true); if(JVLine.getDescription()!= null) asset.setName(JVLine.getDescription()); else asset.setName("Asset created from JV"); asset.setHelp("Created from JV #" + JVLine.getGL_Journal_ID() + " on line #" + JVLine.getLine()); asset.setDescription(JVLine.getDescription()); asset.setUseLifeMonths(assetgrpacct.getUseLifeMonths()); asset.setUseLifeYears(assetgrpacct.getUseLifeYears()); asset.setA_Asset_Group_ID(assetgrpacct.getA_Asset_Group_ID()); asset.setA_QTY_Current(JVLine.getQty()); asset.setA_QTY_Original(JVLine.getQty()); asset.saveEx(); asset.setA_Parent_Asset_ID(asset.getA_Asset_ID()); asset.saveEx(); boolean isdepreciate = assetgrpacct.isProcessing(); if (isdepreciate == true) { assetacct.setPostingType(assetgrpacct.getPostingType()); assetacct.setA_Split_Percent(assetgrpacct.getA_Split_Percent()); assetacct.setA_Depreciation_Conv_ID(assetgrpacct.getConventionType()); assetacct.setA_Asset_ID(asset.getA_Asset_ID()); assetacct.setA_Depreciation_ID(assetgrpacct.getDepreciationType()); assetacct.setA_Asset_Spread_ID(assetgrpacct.getA_Asset_Spread_Type()); assetacct.setA_Period_Start(1); if (asset.getUseLifeMonths() == 0 & asset.getUseLifeYears() == 0){ assetacct.setA_Period_End(assetgrpacct.getUseLifeMonths()); asset.setUseLifeYears(assetgrpacct.getUseLifeYears()); asset.setUseLifeMonths(assetgrpacct.getUseLifeMonths()); asset.setIsDepreciated(true); asset.setIsOwned(true); asset.saveEx(); // uselifemonths = assetgrpacct.getUseLifeMonths(); // uselifeyears = assetgrpacct.getUseLifeYears(); } else if(asset.getUseLifeMonths() == 0){ assetacct.setA_Period_End(asset.getUseLifeYears()*12); asset.setUseLifeMonths(asset.getUseLifeYears()*12); asset.setIsDepreciated(true); asset.setIsOwned(true); asset.saveEx(); // uselifemonths = asset.getUseLifeYears()*12; // uselifeyears = asset.getUseLifeYears(); } else{ assetacct.setA_Period_End(asset.getUseLifeMonths()); // uselifemonths = asset.getUseLifeMonths(); // uselifeyears = asset.getUseLifeYears(); } assetacct.setA_Depreciation_Method_ID(assetgrpacct.getA_Depreciation_Calc_Type()); assetacct.setA_Asset_Acct(assetgrpacct.getA_Asset_Acct()); assetacct.setC_AcctSchema_ID(assetgrpacct.getC_AcctSchema_ID()); assetacct.setA_Salvage_Value(new BigDecimal (0.0)); assetacct.setA_Accumdepreciation_Acct(assetgrpacct.getA_Accumdepreciation_Acct()); assetacct.setA_Depreciation_Acct(assetgrpacct.getA_Depreciation_Acct()); assetacct.setA_Disposal_Revenue(assetgrpacct.getA_Disposal_Revenue()); assetacct.setA_Disposal_Loss(assetgrpacct.getA_Disposal_Loss()); assetacct.setA_Reval_Accumdep_Offset_Cur(assetgrpacct.getA_Reval_Accumdep_Offset_Cur()); assetacct.setA_Reval_Accumdep_Offset_Prior(assetgrpacct.getA_Reval_Accumdep_Offset_Prior()); assetacct.setA_Reval_Cal_Method(assetgrpacct.getA_Reval_Cal_Method()); assetacct.setA_Reval_Cost_Offset(assetgrpacct.getA_Reval_Cost_Offset()); assetacct.setA_Reval_Cost_Offset_Prior(assetgrpacct.getA_Reval_Cost_Offset_Prior()); assetacct.setA_Reval_Depexp_Offset(assetgrpacct.getA_Reval_Depexp_Offset()); assetacct.setA_Depreciation_Manual_Amount(assetgrpacct.getA_Depreciation_Manual_Amount()); assetacct.setA_Depreciation_Manual_Period(assetgrpacct.getA_Depreciation_Manual_Period()); assetacct.setA_Depreciation_Table_Header_ID(assetgrpacct.getA_Depreciation_Table_Header_ID()); assetacct.setA_Depreciation_Variable_Perc(assetgrpacct.getA_Depreciation_Variable_Perc()); assetacct.setProcessing(false); assetacct.saveEx(); MAssetChange change = new MAssetChange (getCtx(), 0, get_TrxName()); change.setPostingType(assetacct.getPostingType()); change.setA_Split_Percent(assetacct.getA_Split_Percent()); change.setConventionType(assetacct.getA_Depreciation_Conv_ID()); change.setA_Asset_ID(asset.getA_Asset_ID()); change.setDepreciationType(assetacct.getA_Depreciation_ID()); change.setA_Asset_Spread_Type(assetacct.getA_Asset_Spread_ID()); change.setA_Period_Start(assetacct.getA_Period_Start()); change.setA_Period_End(assetacct.getA_Period_End()); change.setIsInPosession(asset.isOwned()); change.setIsDisposed(asset.isDisposed()); change.setIsDepreciated(asset.isDepreciated()); change.setIsFullyDepreciated(asset.isFullyDepreciated()); change.setA_Depreciation_Calc_Type(assetacct.getA_Depreciation_Method_ID()); change.setA_Asset_Acct(assetacct.getA_Asset_Acct()); change.setC_AcctSchema_ID(assetacct.getC_AcctSchema_ID()); change.setA_Accumdepreciation_Acct(assetacct.getA_Accumdepreciation_Acct()); change.setA_Depreciation_Acct(assetacct.getA_Depreciation_Acct()); change.setA_Disposal_Revenue(assetacct.getA_Disposal_Revenue()); change.setA_Disposal_Loss(assetacct.getA_Disposal_Loss()); change.setA_Reval_Accumdep_Offset_Cur(assetacct.getA_Reval_Accumdep_Offset_Cur()); change.setA_Reval_Accumdep_Offset_Prior(assetacct.getA_Reval_Accumdep_Offset_Prior()); change.setA_Reval_Cal_Method(assetacct.getA_Reval_Cal_Method()); change.setA_Reval_Cost_Offset(assetacct.getA_Reval_Cost_Offset()); change.setA_Reval_Cost_Offset_Prior(assetacct.getA_Reval_Cost_Offset_Prior()); change.setA_Reval_Depexp_Offset(assetacct.getA_Reval_Depexp_Offset()); change.setA_Depreciation_Manual_Amount(assetacct.getA_Depreciation_Manual_Amount()); change.setA_Depreciation_Manual_Period(assetacct.getA_Depreciation_Manual_Period()); change.setA_Depreciation_Table_Header_ID(assetacct.getA_Depreciation_Table_Header_ID()); change.setA_Depreciation_Variable_Perc(assetacct.getA_Depreciation_Variable_Perc()); change.setA_Parent_Asset_ID(asset.getA_Parent_Asset_ID()); change.setChangeType("CRT"); change.setTextDetails(MRefList.getListDescription (getCtx(),"A_Update_Type" , "CRT")); change.setIsInPosession(asset.isOwned()); change.setIsDisposed(asset.isDisposed()); change.setIsDepreciated(asset.isDepreciated()); change.setIsFullyDepreciated(asset.isFullyDepreciated()); change.setLot(asset.getLot()); change.setSerNo(asset.getSerNo()); change.setVersionNo(asset.getVersionNo()); change.setUseLifeMonths(asset.getUseLifeMonths()); change.setUseLifeYears(asset.getUseLifeYears()); change.setLifeUseUnits(asset.getLifeUseUnits()); change.setAssetDisposalDate(asset.getAssetDisposalDate()); change.setAssetServiceDate(asset.getAssetServiceDate()); change.setC_BPartner_Location_ID(asset.getC_BPartner_Location_ID()); change.setC_BPartner_ID(asset.getC_BPartner_ID()); change.setAssetValueAmt(JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr())); change.setA_Asset_CreateDate(asset.getA_Asset_CreateDate()); change.setAD_User_ID(asset.getAD_User_ID()); change.setC_Location_ID(asset.getC_Location_ID()); change.saveEx(); } X_A_Depreciation_Workfile assetwk = new X_A_Depreciation_Workfile (getCtx(), 0, get_TrxName()); assetwk.setA_Asset_ID(asset.getA_Asset_ID()); assetwk.setA_Life_Period(assetgrpacct.getUseLifeMonths()); assetwk.setA_Asset_Life_Years(assetgrpacct.getUseLifeYears()); assetwk.setA_Asset_Cost(assetwk.getA_Asset_Cost().add(JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr()))); assetwk.setA_Accumulated_Depr(new BigDecimal (0.0)); assetwk.setA_Salvage_Value(new BigDecimal (0.0)); assetwk.setA_Period_Posted(0); assetwk.setA_Asset_Life_Current_Year(new BigDecimal (0.0)); assetwk.setA_Curr_Dep_Exp(new BigDecimal (0.0)); assetwk.setA_QTY_Current(JVLine.getQty()); assetwk.setIsDepreciated(assetgrpacct.isProcessing()); assetwk.setPostingType(assetgrpacct.getPostingType()); assetwk.saveEx(); X_A_Asset_Addition assetadd = new X_A_Asset_Addition (getCtx(), 0, get_TrxName()); assetadd.setA_Asset_ID(asset.getA_Asset_ID()); assetadd.setAssetValueAmt(JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr())); assetadd.setA_SourceType("JRN"); assetadd.setA_CapvsExp("Cap"); assetadd.setA_QTY_Current(JVLine.getQty()); assetadd.setDocumentNo(""+JVLine.getGL_Journal_ID()); assetadd.setGL_JournalBatch_ID(JVLine.getGL_Journal_ID()); assetadd.setLine(JVLine.getLine()); assetadd.setDescription(JVLine.getDescription()); assetadd.setPostingType(assetwk.getPostingType()); assetadd.saveEx(); } else { sql2 ="SELECT * FROM A_Depreciation_Workfile WHERE A_Asset_ID = ? and PostingType = ?"; PreparedStatement pstmt2 = null; pstmt2 = DB.prepareStatement(sql2,get_TrxName()); ResultSet rs3 = null; log.info("no"); try { pstmt2.setInt(1, asset.getA_Asset_ID()); pstmt2.setString(2, assetgrpacct.getPostingType()); rs3 = pstmt2.executeQuery(); while (rs3.next()){ X_A_Depreciation_Workfile assetwk = new X_A_Depreciation_Workfile (getCtx(), rs3, get_TrxName()); assetwk.setA_Asset_ID(asset.getA_Asset_ID()); assetwk.setA_Life_Period(assetgrpacct.getUseLifeMonths()); assetwk.setA_Asset_Life_Years(assetgrpacct.getUseLifeYears()); assetwk.setA_Asset_Cost(assetwk.getA_Asset_Cost().add(JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr()))); assetwk.setA_QTY_Current(assetwk.getA_QTY_Current().add(JVLine.getQty())); assetwk.setIsDepreciated(assetgrpacct.isProcessing()); assetwk.saveEx(); X_A_Asset_Addition assetadd = new X_A_Asset_Addition (getCtx(), 0, get_TrxName()); assetadd.setA_Asset_ID(asset.getA_Asset_ID()); assetadd.setAssetValueAmt((JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr()))); assetadd.setA_SourceType("JRN"); assetadd.setA_CapvsExp("Cap"); assetadd.setA_QTY_Current(JVLine.getQty()); assetadd.setDocumentNo(""+JVLine.getGL_Journal_ID()); assetadd.setGL_JournalBatch_ID(JVLine.getGL_Journal_ID()); assetadd.setLine(JVLine.getLine()); assetadd.setDescription(JVLine.getDescription()); assetadd.setPostingType(assetwk.getPostingType()); assetadd.saveEx(); asset.setA_QTY_Original(assetadd.getA_QTY_Current().add(asset.getA_QTY_Original())); asset.setA_QTY_Current(assetadd.getA_QTY_Current().add(asset.getA_QTY_Current())); asset.saveEx(); MAssetChange change = new MAssetChange (getCtx(), 0, get_TrxName()); change.setA_Asset_ID(asset.getA_Asset_ID()); change.setChangeType("ADD"); change.setTextDetails(MRefList.getListDescription (getCtx(),"A_Update_Type" , "ADD")); change.setPostingType(assetwk.getPostingType()); change.setAssetValueAmt(assetadd.getAssetValueAmt()); change.setA_QTY_Current(assetadd.getA_QTY_Current()); change.saveEx(); } } catch (Exception e) { log.info("getAssets "+ e); } finally { DB.close(rs3, pstmt2); rs3 = null; pstmt2 = null; } } } } } else if (acctType.equals("E")) { X_A_Asset_Addition assetadd = new X_A_Asset_Addition (getCtx(), 0, get_TrxName()); assetadd.setA_Asset_ID(asset.getA_Asset_ID()); assetadd.setAssetValueAmt((JVLine.getAmtAcctDr().subtract(JVLine.getAmtAcctCr()))); assetadd.setA_SourceType("JRN"); assetadd.setA_CapvsExp("Exp"); assetadd.setA_QTY_Current(JVLine.getQty()); assetadd.setDocumentNo(""+JVLine.getGL_Journal_ID()); assetadd.setGL_JournalBatch_ID(JVLine.getGL_Journal_ID()); assetadd.setLine(JVLine.getLine()); assetadd.setDescription(JVLine.getDescription()); assetadd.setPostingType("A"); assetadd.saveEx(); MAssetChange change = new MAssetChange (getCtx(), 0, get_TrxName()); change.setA_Asset_ID(asset.getA_Asset_ID()); change.setA_QTY_Current(assetadd.getA_QTY_Current()); change.setChangeType("EXP"); change.setTextDetails(MRefList.getListDescription (getCtx(),"A_Update_Type" , "EXP")); assetadd.setPostingType("A"); change.setAssetValueAmt(assetadd.getAssetValueAmt()); change.setA_QTY_Current(assetadd.getA_QTY_Current()); change.saveEx(); } JVLine.set_ValueOfColumn(I_CustomColumn.A_Processed, Boolean.TRUE); JVLine.saveEx(); } rs.close(); pstmt.close(); pstmt = null; } catch (Exception e) { log.info("getAssets "+ e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } return ""; } // doIt } // CreateGLAsset
75371_48
/** Generated Model - DO NOT CHANGE */ package de.metas.flatrate.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.Env; /** Generated Model for C_SubscriptionProgress * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_C_SubscriptionProgress extends org.compiere.model.PO implements I_C_SubscriptionProgress, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -626565630L; /** Standard Constructor */ public X_C_SubscriptionProgress (Properties ctx, int C_SubscriptionProgress_ID, String trxName) { super (ctx, C_SubscriptionProgress_ID, trxName); /** if (C_SubscriptionProgress_ID == 0) { setC_Flatrate_Term_ID (0); setC_SubscriptionProgress_ID (0); setDropShip_BPartner_ID (0); setDropShip_Location_ID (0); setEventType (null); setIsSubscriptionConfirmed (false); // N setProcessed (false); // N setStatus (null); // P } */ } /** Load Constructor */ public X_C_SubscriptionProgress (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public de.metas.flatrate.model.I_C_Flatrate_Term getC_Flatrate_Term() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.flatrate.model.I_C_Flatrate_Term.class); } @Override public void setC_Flatrate_Term(de.metas.flatrate.model.I_C_Flatrate_Term C_Flatrate_Term) { set_ValueFromPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.flatrate.model.I_C_Flatrate_Term.class, C_Flatrate_Term); } /** Set Pauschale - Vertragsperiode. @param C_Flatrate_Term_ID Pauschale - Vertragsperiode */ @Override public void setC_Flatrate_Term_ID (int C_Flatrate_Term_ID) { if (C_Flatrate_Term_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, Integer.valueOf(C_Flatrate_Term_ID)); } /** Get Pauschale - Vertragsperiode. @return Pauschale - Vertragsperiode */ @Override public int getC_Flatrate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_Term_ID); if (ii == null) return 0; return ii.intValue(); } /** * ContractStatus AD_Reference_ID=540000 * Reference name: SubscriptionStatus */ public static final int CONTRACTSTATUS_AD_Reference_ID=540000; /** Laufend = Ru */ public static final String CONTRACTSTATUS_Laufend = "Ru"; /** Lieferpause = Pa */ public static final String CONTRACTSTATUS_Lieferpause = "Pa"; /** Beendet = En */ public static final String CONTRACTSTATUS_Beendet = "En"; /** Gekündigt = Qu */ public static final String CONTRACTSTATUS_Gekuendigt = "Qu"; /** Wartet auf Bestätigung = St */ public static final String CONTRACTSTATUS_WartetAufBestaetigung = "St"; /** Info = In */ public static final String CONTRACTSTATUS_Info = "In"; /** Noch nicht begonnen = Wa */ public static final String CONTRACTSTATUS_NochNichtBegonnen = "Wa"; /** Set Vertrags-Status. @param ContractStatus Vertrags-Status */ @Override public void setContractStatus (java.lang.String ContractStatus) { set_Value (COLUMNNAME_ContractStatus, ContractStatus); } /** Get Vertrags-Status. @return Vertrags-Status */ @Override public java.lang.String getContractStatus () { return (java.lang.String)get_Value(COLUMNNAME_ContractStatus); } /** Set Abo-Verlauf. @param C_SubscriptionProgress_ID Abo-Verlauf */ @Override public void setC_SubscriptionProgress_ID (int C_SubscriptionProgress_ID) { if (C_SubscriptionProgress_ID < 1) set_ValueNoCheck (COLUMNNAME_C_SubscriptionProgress_ID, null); else set_ValueNoCheck (COLUMNNAME_C_SubscriptionProgress_ID, Integer.valueOf(C_SubscriptionProgress_ID)); } /** Get Abo-Verlauf. @return Abo-Verlauf */ @Override public int getC_SubscriptionProgress_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_SubscriptionProgress_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_BPartner getDropShip_BPartner() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DropShip_BPartner_ID, org.compiere.model.I_C_BPartner.class); } @Override public void setDropShip_BPartner(org.compiere.model.I_C_BPartner DropShip_BPartner) { set_ValueFromPO(COLUMNNAME_DropShip_BPartner_ID, org.compiere.model.I_C_BPartner.class, DropShip_BPartner); } /** Set Lieferempfänger. @param DropShip_BPartner_ID Business Partner to ship to */ @Override public void setDropShip_BPartner_ID (int DropShip_BPartner_ID) { if (DropShip_BPartner_ID < 1) set_Value (COLUMNNAME_DropShip_BPartner_ID, null); else set_Value (COLUMNNAME_DropShip_BPartner_ID, Integer.valueOf(DropShip_BPartner_ID)); } /** Get Lieferempfänger. @return Business Partner to ship to */ @Override public int getDropShip_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_BPartner_Location getDropShip_Location() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DropShip_Location_ID, org.compiere.model.I_C_BPartner_Location.class); } @Override public void setDropShip_Location(org.compiere.model.I_C_BPartner_Location DropShip_Location) { set_ValueFromPO(COLUMNNAME_DropShip_Location_ID, org.compiere.model.I_C_BPartner_Location.class, DropShip_Location); } /** Set Lieferadresse. @param DropShip_Location_ID Business Partner Location for shipping to */ @Override public void setDropShip_Location_ID (int DropShip_Location_ID) { if (DropShip_Location_ID < 1) set_Value (COLUMNNAME_DropShip_Location_ID, null); else set_Value (COLUMNNAME_DropShip_Location_ID, Integer.valueOf(DropShip_Location_ID)); } /** Get Lieferadresse. @return Business Partner Location for shipping to */ @Override public int getDropShip_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_Location_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_User getDropShip_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DropShip_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setDropShip_User(org.compiere.model.I_AD_User DropShip_User) { set_ValueFromPO(COLUMNNAME_DropShip_User_ID, org.compiere.model.I_AD_User.class, DropShip_User); } /** Set Lieferkontakt. @param DropShip_User_ID Business Partner Contact for drop shipment */ @Override public void setDropShip_User_ID (int DropShip_User_ID) { if (DropShip_User_ID < 1) set_Value (COLUMNNAME_DropShip_User_ID, null); else set_Value (COLUMNNAME_DropShip_User_ID, Integer.valueOf(DropShip_User_ID)); } /** Get Lieferkontakt. @return Business Partner Contact for drop shipment */ @Override public int getDropShip_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datum. @param EventDate Datum */ @Override public void setEventDate (java.sql.Timestamp EventDate) { set_Value (COLUMNNAME_EventDate, EventDate); } /** Get Datum. @return Datum */ @Override public java.sql.Timestamp getEventDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_EventDate); } /** * EventType AD_Reference_ID=540013 * Reference name: C_SubscriptionProgress EventType */ public static final int EVENTTYPE_AD_Reference_ID=540013; /** Lieferung = DE */ public static final String EVENTTYPE_Lieferung = "DE"; /** Abowechsel = SU */ public static final String EVENTTYPE_Abowechsel = "SU"; /** Statuswechsel = ST */ public static final String EVENTTYPE_Statuswechsel = "ST"; /** Abo-Ende = SE */ public static final String EVENTTYPE_Abo_Ende = "SE"; /** Abo-Beginn = SB */ public static final String EVENTTYPE_Abo_Beginn = "SB"; /** Abo-Autoverlängerung = SR */ public static final String EVENTTYPE_Abo_Autoverlaengerung = "SR"; /** Abopause-Beginn = PB */ public static final String EVENTTYPE_Abopause_Beginn = "PB"; /** Abopause-Ende = PE */ public static final String EVENTTYPE_Abopause_Ende = "PE"; /** Set Ereignisart. @param EventType Ereignisart */ @Override public void setEventType (java.lang.String EventType) { set_ValueNoCheck (COLUMNNAME_EventType, EventType); } /** Get Ereignisart. @return Ereignisart */ @Override public java.lang.String getEventType () { return (java.lang.String)get_Value(COLUMNNAME_EventType); } /** Set Bestätigung eingegangen. @param IsSubscriptionConfirmed Bestätigung eingegangen */ @Override public void setIsSubscriptionConfirmed (boolean IsSubscriptionConfirmed) { set_Value (COLUMNNAME_IsSubscriptionConfirmed, Boolean.valueOf(IsSubscriptionConfirmed)); } /** Get Bestätigung eingegangen. @return Bestätigung eingegangen */ @Override public boolean isSubscriptionConfirmed () { Object oo = get_Value(COLUMNNAME_IsSubscriptionConfirmed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } /** Set Lieferdisposition. @param M_ShipmentSchedule_ID Lieferdisposition */ @Override public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID)); } /** Get Lieferdisposition. @return Lieferdisposition */ @Override public int getM_ShipmentSchedule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipmentSchedule_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** * Status AD_Reference_ID=540002 * Reference name: C_SubscriptionProgress Status */ public static final int STATUS_AD_Reference_ID=540002; /** Geplant = P */ public static final String STATUS_Geplant = "P"; /** Lieferung Offen = O */ public static final String STATUS_LieferungOffen = "O"; /** Ausgeliefert = D */ public static final String STATUS_Ausgeliefert = "D"; /** Wird kommissioniert = C */ public static final String STATUS_WirdKommissioniert = "C"; /** Ausgeführt = E */ public static final String STATUS_Ausgefuehrt = "E"; /** Verzögert = H */ public static final String STATUS_Verzoegert = "H"; /** Set Status. @param Status Status of the currently running check */ @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status of the currently running check */ @Override public java.lang.String getStatus () { return (java.lang.String)get_Value(COLUMNNAME_Status); } }
zoosky/metasfresh
de.metas.contracts/src/main/java-gen/de/metas/flatrate/model/X_C_SubscriptionProgress.java
4,903
/** Geplant = P */
block_comment
nl
/** Generated Model - DO NOT CHANGE */ package de.metas.flatrate.model; import java.math.BigDecimal; import java.sql.ResultSet; import java.util.Properties; import org.compiere.util.Env; /** Generated Model for C_SubscriptionProgress * @author Adempiere (generated) */ @SuppressWarnings("javadoc") public class X_C_SubscriptionProgress extends org.compiere.model.PO implements I_C_SubscriptionProgress, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -626565630L; /** Standard Constructor */ public X_C_SubscriptionProgress (Properties ctx, int C_SubscriptionProgress_ID, String trxName) { super (ctx, C_SubscriptionProgress_ID, trxName); /** if (C_SubscriptionProgress_ID == 0) { setC_Flatrate_Term_ID (0); setC_SubscriptionProgress_ID (0); setDropShip_BPartner_ID (0); setDropShip_Location_ID (0); setEventType (null); setIsSubscriptionConfirmed (false); // N setProcessed (false); // N setStatus (null); // P } */ } /** Load Constructor */ public X_C_SubscriptionProgress (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } @Override public de.metas.flatrate.model.I_C_Flatrate_Term getC_Flatrate_Term() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.flatrate.model.I_C_Flatrate_Term.class); } @Override public void setC_Flatrate_Term(de.metas.flatrate.model.I_C_Flatrate_Term C_Flatrate_Term) { set_ValueFromPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.flatrate.model.I_C_Flatrate_Term.class, C_Flatrate_Term); } /** Set Pauschale - Vertragsperiode. @param C_Flatrate_Term_ID Pauschale - Vertragsperiode */ @Override public void setC_Flatrate_Term_ID (int C_Flatrate_Term_ID) { if (C_Flatrate_Term_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, Integer.valueOf(C_Flatrate_Term_ID)); } /** Get Pauschale - Vertragsperiode. @return Pauschale - Vertragsperiode */ @Override public int getC_Flatrate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_Term_ID); if (ii == null) return 0; return ii.intValue(); } /** * ContractStatus AD_Reference_ID=540000 * Reference name: SubscriptionStatus */ public static final int CONTRACTSTATUS_AD_Reference_ID=540000; /** Laufend = Ru */ public static final String CONTRACTSTATUS_Laufend = "Ru"; /** Lieferpause = Pa */ public static final String CONTRACTSTATUS_Lieferpause = "Pa"; /** Beendet = En */ public static final String CONTRACTSTATUS_Beendet = "En"; /** Gekündigt = Qu */ public static final String CONTRACTSTATUS_Gekuendigt = "Qu"; /** Wartet auf Bestätigung = St */ public static final String CONTRACTSTATUS_WartetAufBestaetigung = "St"; /** Info = In */ public static final String CONTRACTSTATUS_Info = "In"; /** Noch nicht begonnen = Wa */ public static final String CONTRACTSTATUS_NochNichtBegonnen = "Wa"; /** Set Vertrags-Status. @param ContractStatus Vertrags-Status */ @Override public void setContractStatus (java.lang.String ContractStatus) { set_Value (COLUMNNAME_ContractStatus, ContractStatus); } /** Get Vertrags-Status. @return Vertrags-Status */ @Override public java.lang.String getContractStatus () { return (java.lang.String)get_Value(COLUMNNAME_ContractStatus); } /** Set Abo-Verlauf. @param C_SubscriptionProgress_ID Abo-Verlauf */ @Override public void setC_SubscriptionProgress_ID (int C_SubscriptionProgress_ID) { if (C_SubscriptionProgress_ID < 1) set_ValueNoCheck (COLUMNNAME_C_SubscriptionProgress_ID, null); else set_ValueNoCheck (COLUMNNAME_C_SubscriptionProgress_ID, Integer.valueOf(C_SubscriptionProgress_ID)); } /** Get Abo-Verlauf. @return Abo-Verlauf */ @Override public int getC_SubscriptionProgress_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_SubscriptionProgress_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_BPartner getDropShip_BPartner() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DropShip_BPartner_ID, org.compiere.model.I_C_BPartner.class); } @Override public void setDropShip_BPartner(org.compiere.model.I_C_BPartner DropShip_BPartner) { set_ValueFromPO(COLUMNNAME_DropShip_BPartner_ID, org.compiere.model.I_C_BPartner.class, DropShip_BPartner); } /** Set Lieferempfänger. @param DropShip_BPartner_ID Business Partner to ship to */ @Override public void setDropShip_BPartner_ID (int DropShip_BPartner_ID) { if (DropShip_BPartner_ID < 1) set_Value (COLUMNNAME_DropShip_BPartner_ID, null); else set_Value (COLUMNNAME_DropShip_BPartner_ID, Integer.valueOf(DropShip_BPartner_ID)); } /** Get Lieferempfänger. @return Business Partner to ship to */ @Override public int getDropShip_BPartner_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_BPartner_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_C_BPartner_Location getDropShip_Location() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DropShip_Location_ID, org.compiere.model.I_C_BPartner_Location.class); } @Override public void setDropShip_Location(org.compiere.model.I_C_BPartner_Location DropShip_Location) { set_ValueFromPO(COLUMNNAME_DropShip_Location_ID, org.compiere.model.I_C_BPartner_Location.class, DropShip_Location); } /** Set Lieferadresse. @param DropShip_Location_ID Business Partner Location for shipping to */ @Override public void setDropShip_Location_ID (int DropShip_Location_ID) { if (DropShip_Location_ID < 1) set_Value (COLUMNNAME_DropShip_Location_ID, null); else set_Value (COLUMNNAME_DropShip_Location_ID, Integer.valueOf(DropShip_Location_ID)); } /** Get Lieferadresse. @return Business Partner Location for shipping to */ @Override public int getDropShip_Location_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_Location_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_User getDropShip_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DropShip_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setDropShip_User(org.compiere.model.I_AD_User DropShip_User) { set_ValueFromPO(COLUMNNAME_DropShip_User_ID, org.compiere.model.I_AD_User.class, DropShip_User); } /** Set Lieferkontakt. @param DropShip_User_ID Business Partner Contact for drop shipment */ @Override public void setDropShip_User_ID (int DropShip_User_ID) { if (DropShip_User_ID < 1) set_Value (COLUMNNAME_DropShip_User_ID, null); else set_Value (COLUMNNAME_DropShip_User_ID, Integer.valueOf(DropShip_User_ID)); } /** Get Lieferkontakt. @return Business Partner Contact for drop shipment */ @Override public int getDropShip_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datum. @param EventDate Datum */ @Override public void setEventDate (java.sql.Timestamp EventDate) { set_Value (COLUMNNAME_EventDate, EventDate); } /** Get Datum. @return Datum */ @Override public java.sql.Timestamp getEventDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_EventDate); } /** * EventType AD_Reference_ID=540013 * Reference name: C_SubscriptionProgress EventType */ public static final int EVENTTYPE_AD_Reference_ID=540013; /** Lieferung = DE */ public static final String EVENTTYPE_Lieferung = "DE"; /** Abowechsel = SU */ public static final String EVENTTYPE_Abowechsel = "SU"; /** Statuswechsel = ST */ public static final String EVENTTYPE_Statuswechsel = "ST"; /** Abo-Ende = SE */ public static final String EVENTTYPE_Abo_Ende = "SE"; /** Abo-Beginn = SB */ public static final String EVENTTYPE_Abo_Beginn = "SB"; /** Abo-Autoverlängerung = SR */ public static final String EVENTTYPE_Abo_Autoverlaengerung = "SR"; /** Abopause-Beginn = PB */ public static final String EVENTTYPE_Abopause_Beginn = "PB"; /** Abopause-Ende = PE */ public static final String EVENTTYPE_Abopause_Ende = "PE"; /** Set Ereignisart. @param EventType Ereignisart */ @Override public void setEventType (java.lang.String EventType) { set_ValueNoCheck (COLUMNNAME_EventType, EventType); } /** Get Ereignisart. @return Ereignisart */ @Override public java.lang.String getEventType () { return (java.lang.String)get_Value(COLUMNNAME_EventType); } /** Set Bestätigung eingegangen. @param IsSubscriptionConfirmed Bestätigung eingegangen */ @Override public void setIsSubscriptionConfirmed (boolean IsSubscriptionConfirmed) { set_Value (COLUMNNAME_IsSubscriptionConfirmed, Boolean.valueOf(IsSubscriptionConfirmed)); } /** Get Bestätigung eingegangen. @return Bestätigung eingegangen */ @Override public boolean isSubscriptionConfirmed () { Object oo = get_Value(COLUMNNAME_IsSubscriptionConfirmed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } @Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } /** Set Lieferdisposition. @param M_ShipmentSchedule_ID Lieferdisposition */ @Override public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID)); } /** Get Lieferdisposition. @return Lieferdisposition */ @Override public int getM_ShipmentSchedule_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipmentSchedule_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Menge. @param Qty Menge */ @Override public void setQty (java.math.BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } /** Get Menge. @return Menge */ @Override public java.math.BigDecimal getQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); if (bd == null) return Env.ZERO; return bd; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** * Status AD_Reference_ID=540002 * Reference name: C_SubscriptionProgress Status */ public static final int STATUS_AD_Reference_ID=540002; /** Geplant = P<SUF>*/ public static final String STATUS_Geplant = "P"; /** Lieferung Offen = O */ public static final String STATUS_LieferungOffen = "O"; /** Ausgeliefert = D */ public static final String STATUS_Ausgeliefert = "D"; /** Wird kommissioniert = C */ public static final String STATUS_WirdKommissioniert = "C"; /** Ausgeführt = E */ public static final String STATUS_Ausgefuehrt = "E"; /** Verzögert = H */ public static final String STATUS_Verzoegert = "H"; /** Set Status. @param Status Status of the currently running check */ @Override public void setStatus (java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status of the currently running check */ @Override public java.lang.String getStatus () { return (java.lang.String)get_Value(COLUMNNAME_Status); } }
10249_4
package be.kdg.tic_tac_toe.model; import java.util.Objects; public class Piece { // vars aanmaken private final Sort SORT; private final int X; private final int Y; //constructor van de var Piece(Sort sort, int y, int x) { this.X = x; this.Y = y; this.SORT = sort; } public boolean equalsSort(Sort sort) { //zorgt ervoor om te checken of dat teken het teken is dat ze zeggen wat het is // als het null is is het zowiezo false if (sort == null) { //het kan nooit null zijn anders was der niks om mee te vergelijken daarom altijd false return false; } else { //dikke sort is wat je bent en dat vergelijk je met de kleine sort wat er gevraagd word of je dat bent //ben je die sort geef je true en dan kan het doorgaan //ben je het niet dan stopt ie en gaat het spel verder --> false return this.getSORT().equals(sort); } } Sort getSORT() { //de sort returnen die je bent return SORT; } @Override public int hashCode() { //returned de uitgerekende hashcode return Objects.hash(SORT, X, Y); } @Override public boolean equals(Object o) { //het is hetzelfde dus gelijk --> true if (this == o) return true; //als o null is is het zwz false en of als de klasse van o niet gelijk is aan de klasse van het opgegeven var if (o == null || getClass() != o.getClass()) return false; //nieuwe var en we weten dat het o is omdat we dat ervoor hebben gecheckt Piece piece = (Piece) o; // als de hashcode gelijk is dan zijn alle var ook gelijk aan elkaar if (this.hashCode() == o.hashCode()) { return X == piece.X && Y == piece.Y && SORT == piece.SORT; } return false; } @Override public String toString() { //een string van da gecheckte var teruggeven return String.format("%s", this.getSORT()); } }
zouffke/TicTacToeFX
src/main/java/be/kdg/tic_tac_toe/model/Piece.java
603
//dikke sort is wat je bent en dat vergelijk je met de kleine sort wat er gevraagd word of je dat bent
line_comment
nl
package be.kdg.tic_tac_toe.model; import java.util.Objects; public class Piece { // vars aanmaken private final Sort SORT; private final int X; private final int Y; //constructor van de var Piece(Sort sort, int y, int x) { this.X = x; this.Y = y; this.SORT = sort; } public boolean equalsSort(Sort sort) { //zorgt ervoor om te checken of dat teken het teken is dat ze zeggen wat het is // als het null is is het zowiezo false if (sort == null) { //het kan nooit null zijn anders was der niks om mee te vergelijken daarom altijd false return false; } else { //dikke sort<SUF> //ben je die sort geef je true en dan kan het doorgaan //ben je het niet dan stopt ie en gaat het spel verder --> false return this.getSORT().equals(sort); } } Sort getSORT() { //de sort returnen die je bent return SORT; } @Override public int hashCode() { //returned de uitgerekende hashcode return Objects.hash(SORT, X, Y); } @Override public boolean equals(Object o) { //het is hetzelfde dus gelijk --> true if (this == o) return true; //als o null is is het zwz false en of als de klasse van o niet gelijk is aan de klasse van het opgegeven var if (o == null || getClass() != o.getClass()) return false; //nieuwe var en we weten dat het o is omdat we dat ervoor hebben gecheckt Piece piece = (Piece) o; // als de hashcode gelijk is dan zijn alle var ook gelijk aan elkaar if (this.hashCode() == o.hashCode()) { return X == piece.X && Y == piece.Y && SORT == piece.SORT; } return false; } @Override public String toString() { //een string van da gecheckte var teruggeven return String.format("%s", this.getSORT()); } }
209386_0
package imtpmd.imtpmd_stoplicht.API; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import imtpmd.imtpmd_stoplicht.Models.Date; import imtpmd.imtpmd_stoplicht.Models.Emotion; import imtpmd.imtpmd_stoplicht.Models.Feedback; import imtpmd.imtpmd_stoplicht.Models.FeedbackStats; import imtpmd.imtpmd_stoplicht.Models.Meeting; import imtpmd.imtpmd_stoplicht.Models.User; public class API { public static void login (String login_number_new) { try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://188.226.134.236/api/user/login"); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(new BasicNameValuePair("number", login_number_new)); httpPost.setEntity(new UrlEncodedFormEntity(pairs)); defaultHttpClient.execute(httpPost); } catch (Exception e) {} } public static ArrayList<Meeting> getAllMeetings() { ArrayList<Meeting> meetings = new ArrayList<>(); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting"); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); JSONArray jsonArray = new JSONArray(json); for (int i = 0; i < jsonArray.length(); i++) { JSONObject meeting = jsonArray.getJSONObject(i); JSONObject user = meeting.getJSONObject("user"); meetings.add(new Meeting( meeting.getInt("id"), new User( user.getInt("id"), user.getString("number") ), meeting.getString("name"), meeting.getString("description"), new Date(meeting.getString("starting_at")), new Date(meeting.getString("ending_at")) )); } } catch (Exception e) {} return meetings; } public static Meeting getMeetingById(int meeting_id) { Meeting meeting = new Meeting(); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); JSONObject jsonObject = new JSONObject(reader.readLine()); meeting.setName(jsonObject.getString("name")); } catch (Exception e) { e.printStackTrace(); } return meeting; } public static ArrayList<Feedback> getFeedbackByMeetingId(int meeting_id) { ArrayList<Feedback> feedback = new ArrayList<>(); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); JSONObject jsonObject = new JSONObject(reader.readLine()); JSONArray jsonArray = jsonObject.getJSONArray("feedback"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject the_feedback = jsonArray.getJSONObject(i); JSONObject emotion = the_feedback.getJSONObject("emotion"); JSONObject user = the_feedback.getJSONObject("user"); // Fill what we need. feedback.add( new Feedback( the_feedback.getInt("id"), new Emotion(emotion.getString("name"), emotion.getString("slug")), new User(user.getString("number")), the_feedback.getString("description"), new Date(the_feedback.getString("created_at")) ) ); } } catch (Exception e) { e.printStackTrace(); } return feedback; } public static FeedbackStats getFeedbackStatsByMeetingId(int meeting_id) { FeedbackStats feedbackStats = new FeedbackStats(); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); JSONObject jsonObject = new JSONObject(reader.readLine()); JSONObject stats = jsonObject.getJSONObject("feedback_stats"); feedbackStats.setBlij(stats.getInt("blij")); feedbackStats.setNeutraal(stats.getInt("neutraal")); feedbackStats.setVerdrietig(stats.getInt("verdrietig")); } catch (Exception e) { e.printStackTrace(); } return feedbackStats; } public static void giveFeedback(int meeting_id, int emotion_id, String username, String description) { try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://188.226.134.236/api/feedback"); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(new BasicNameValuePair("meeting_id", Integer.toString(meeting_id))); pairs.add(new BasicNameValuePair("emotion_id", Integer.toString(emotion_id))); pairs.add(new BasicNameValuePair("number", username)); pairs.add(new BasicNameValuePair("description", description)); httpPost.setEntity(new UrlEncodedFormEntity(pairs)); defaultHttpClient.execute(httpPost); } catch (Exception e) {} } public static void createNewMeeting(String number, String name, String description, String starting_at, String ending_at) { Log.d("starting", starting_at); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://188.226.134.236/api/meeting"); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(new BasicNameValuePair("number", number)); pairs.add(new BasicNameValuePair("name", name)); pairs.add(new BasicNameValuePair("description", description)); pairs.add(new BasicNameValuePair("starting_at", starting_at)); pairs.add(new BasicNameValuePair("ending_at", ending_at)); httpPost.setEntity(new UrlEncodedFormEntity(pairs)); defaultHttpClient.execute(httpPost); } catch (Exception e) { e.printStackTrace(); } } }
zowievangeest/IMTPMD
app/src/main/java/imtpmd/imtpmd_stoplicht/API/API.java
2,073
//188.226.134.236/api/meeting/" + meeting_id);
line_comment
nl
package imtpmd.imtpmd_stoplicht.API; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import imtpmd.imtpmd_stoplicht.Models.Date; import imtpmd.imtpmd_stoplicht.Models.Emotion; import imtpmd.imtpmd_stoplicht.Models.Feedback; import imtpmd.imtpmd_stoplicht.Models.FeedbackStats; import imtpmd.imtpmd_stoplicht.Models.Meeting; import imtpmd.imtpmd_stoplicht.Models.User; public class API { public static void login (String login_number_new) { try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://188.226.134.236/api/user/login"); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(new BasicNameValuePair("number", login_number_new)); httpPost.setEntity(new UrlEncodedFormEntity(pairs)); defaultHttpClient.execute(httpPost); } catch (Exception e) {} } public static ArrayList<Meeting> getAllMeetings() { ArrayList<Meeting> meetings = new ArrayList<>(); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting"); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); String json = reader.readLine(); JSONArray jsonArray = new JSONArray(json); for (int i = 0; i < jsonArray.length(); i++) { JSONObject meeting = jsonArray.getJSONObject(i); JSONObject user = meeting.getJSONObject("user"); meetings.add(new Meeting( meeting.getInt("id"), new User( user.getInt("id"), user.getString("number") ), meeting.getString("name"), meeting.getString("description"), new Date(meeting.getString("starting_at")), new Date(meeting.getString("ending_at")) )); } } catch (Exception e) {} return meetings; } public static Meeting getMeetingById(int meeting_id) { Meeting meeting = new Meeting(); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" +<SUF> HttpResponse httpResponse = defaultHttpClient.execute(httpGet); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); JSONObject jsonObject = new JSONObject(reader.readLine()); meeting.setName(jsonObject.getString("name")); } catch (Exception e) { e.printStackTrace(); } return meeting; } public static ArrayList<Feedback> getFeedbackByMeetingId(int meeting_id) { ArrayList<Feedback> feedback = new ArrayList<>(); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); JSONObject jsonObject = new JSONObject(reader.readLine()); JSONArray jsonArray = jsonObject.getJSONArray("feedback"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject the_feedback = jsonArray.getJSONObject(i); JSONObject emotion = the_feedback.getJSONObject("emotion"); JSONObject user = the_feedback.getJSONObject("user"); // Fill what we need. feedback.add( new Feedback( the_feedback.getInt("id"), new Emotion(emotion.getString("name"), emotion.getString("slug")), new User(user.getString("number")), the_feedback.getString("description"), new Date(the_feedback.getString("created_at")) ) ); } } catch (Exception e) { e.printStackTrace(); } return feedback; } public static FeedbackStats getFeedbackStatsByMeetingId(int meeting_id) { FeedbackStats feedbackStats = new FeedbackStats(); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("http://188.226.134.236/api/meeting/" + meeting_id); HttpResponse httpResponse = defaultHttpClient.execute(httpGet); BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8")); JSONObject jsonObject = new JSONObject(reader.readLine()); JSONObject stats = jsonObject.getJSONObject("feedback_stats"); feedbackStats.setBlij(stats.getInt("blij")); feedbackStats.setNeutraal(stats.getInt("neutraal")); feedbackStats.setVerdrietig(stats.getInt("verdrietig")); } catch (Exception e) { e.printStackTrace(); } return feedbackStats; } public static void giveFeedback(int meeting_id, int emotion_id, String username, String description) { try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://188.226.134.236/api/feedback"); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(new BasicNameValuePair("meeting_id", Integer.toString(meeting_id))); pairs.add(new BasicNameValuePair("emotion_id", Integer.toString(emotion_id))); pairs.add(new BasicNameValuePair("number", username)); pairs.add(new BasicNameValuePair("description", description)); httpPost.setEntity(new UrlEncodedFormEntity(pairs)); defaultHttpClient.execute(httpPost); } catch (Exception e) {} } public static void createNewMeeting(String number, String name, String description, String starting_at, String ending_at) { Log.d("starting", starting_at); try { DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://188.226.134.236/api/meeting"); List<NameValuePair> pairs = new ArrayList<>(); pairs.add(new BasicNameValuePair("number", number)); pairs.add(new BasicNameValuePair("name", name)); pairs.add(new BasicNameValuePair("description", description)); pairs.add(new BasicNameValuePair("starting_at", starting_at)); pairs.add(new BasicNameValuePair("ending_at", ending_at)); httpPost.setEntity(new UrlEncodedFormEntity(pairs)); defaultHttpClient.execute(httpPost); } catch (Exception e) { e.printStackTrace(); } } }
147455_9
/** * Copyright (c) 2016-2024 by the respective copyright holders. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.zsmartsystems.zigbee.dongle.xbee.internal.protocol; import com.zsmartsystems.zigbee.dongle.xbee.internal.protocol.CommandStatus; /** * Class to implement the XBee command <b>ZigBee Stack Profile</b>. * <p> * AT Command <b>ZS</b></p>Set or read the Zigbee stack profile value. This must be the same on * all devices that will join the same network. Effective with release 4x5E, changing ZS to a * different value causes all current parameters to be written to persistent storage. * <p> * This class provides methods for processing XBee API commands. * <p> * Note that this code is autogenerated. Manual changes may be overwritten. * * @author Chris Jackson - Initial contribution of Java code generator */ public class XBeeZigbeeStackProfileResponse extends XBeeFrame implements XBeeResponse { /** * Response field */ private Integer frameId; /** * Response field */ private CommandStatus commandStatus; /** * Response field */ private Integer stackProfile; /** * * @return the frameId as {@link Integer} */ public Integer getFrameId() { return frameId; } /** * * @return the commandStatus as {@link CommandStatus} */ public CommandStatus getCommandStatus() { return commandStatus; } /** * * @return the stackProfile as {@link Integer} */ public Integer getStackProfile() { return stackProfile; } @Override public void deserialize(int[] incomingData) { initialiseDeserializer(incomingData); // Deserialize the fields for the response // Deserialize field "Frame ID" frameId = deserializeInt8(); deserializeAtCommand(); // Deserialize field "Command Status" commandStatus = deserializeCommandStatus(); if (commandStatus != CommandStatus.OK || isComplete()) { return; } // Deserialize field "Stack Profile" stackProfile = deserializeInt8(); } @Override public String toString() { final StringBuilder builder = new StringBuilder(480); builder.append("XBeeZigbeeStackProfileResponse [frameId="); builder.append(frameId); builder.append(", commandStatus="); builder.append(commandStatus); if (commandStatus == CommandStatus.OK) { builder.append(", stackProfile="); builder.append(stackProfile); } builder.append(']'); return builder.toString(); } }
zsmartsystems/com.zsmartsystems.zigbee
com.zsmartsystems.zigbee.dongle.xbee/src/main/java/com/zsmartsystems/zigbee/dongle/xbee/internal/protocol/XBeeZigbeeStackProfileResponse.java
764
// Deserialize field "Frame ID"
line_comment
nl
/** * Copyright (c) 2016-2024 by the respective copyright holders. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.zsmartsystems.zigbee.dongle.xbee.internal.protocol; import com.zsmartsystems.zigbee.dongle.xbee.internal.protocol.CommandStatus; /** * Class to implement the XBee command <b>ZigBee Stack Profile</b>. * <p> * AT Command <b>ZS</b></p>Set or read the Zigbee stack profile value. This must be the same on * all devices that will join the same network. Effective with release 4x5E, changing ZS to a * different value causes all current parameters to be written to persistent storage. * <p> * This class provides methods for processing XBee API commands. * <p> * Note that this code is autogenerated. Manual changes may be overwritten. * * @author Chris Jackson - Initial contribution of Java code generator */ public class XBeeZigbeeStackProfileResponse extends XBeeFrame implements XBeeResponse { /** * Response field */ private Integer frameId; /** * Response field */ private CommandStatus commandStatus; /** * Response field */ private Integer stackProfile; /** * * @return the frameId as {@link Integer} */ public Integer getFrameId() { return frameId; } /** * * @return the commandStatus as {@link CommandStatus} */ public CommandStatus getCommandStatus() { return commandStatus; } /** * * @return the stackProfile as {@link Integer} */ public Integer getStackProfile() { return stackProfile; } @Override public void deserialize(int[] incomingData) { initialiseDeserializer(incomingData); // Deserialize the fields for the response // Deserialize field<SUF> frameId = deserializeInt8(); deserializeAtCommand(); // Deserialize field "Command Status" commandStatus = deserializeCommandStatus(); if (commandStatus != CommandStatus.OK || isComplete()) { return; } // Deserialize field "Stack Profile" stackProfile = deserializeInt8(); } @Override public String toString() { final StringBuilder builder = new StringBuilder(480); builder.append("XBeeZigbeeStackProfileResponse [frameId="); builder.append(frameId); builder.append(", commandStatus="); builder.append(commandStatus); if (commandStatus == CommandStatus.OK) { builder.append(", stackProfile="); builder.append(stackProfile); } builder.append(']'); return builder.toString(); } }
121879_47
package mpi.eudico.client.annotator.viewer; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.Map; import javax.swing.ButtonGroup; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import mpi.eudico.client.annotator.Constants; import mpi.eudico.client.annotator.ElanLocale; import mpi.eudico.client.annotator.InlineEditBoxListener; import mpi.eudico.client.annotator.Preferences; import mpi.eudico.client.annotator.gui.InlineEditBox; import mpi.eudico.client.annotator.util.ClientLogger; import mpi.eudico.client.mediacontrol.ControllerEvent; import mpi.eudico.server.corpora.clom.Annotation; import mpi.eudico.server.corpora.clom.Tier; import mpi.eudico.server.corpora.clomimpl.abstr.TierImpl; import mpi.eudico.server.corpora.event.ACMEditEvent; import mpi.eudico.server.corpora.event.ACMEditListener; /** * Viewer for a subtitle * @version Aug 2005 Identity removed */ @SuppressWarnings("serial") public class SubtitleViewer extends AbstractViewer implements SingleTierViewer, ACMEditListener, ActionListener, InlineEditBoxListener { private JMenu fontMenu; private ButtonGroup fontSizeBG; private int fontSize; private JPopupMenu popup; private Dimension minDimension = new Dimension(400, 50); private JTextArea taSubtitle; private JScrollPane jspSubtitle; private TierImpl tier; private List<? extends Annotation> annotations = new ArrayList<Annotation>(); private long begintime = 0; private long endtime = 0; private long[] arrTags; private Highlighter highlighter; private Highlighter.HighlightPainter selectionPainter; private InlineEditBox inlineEditBox; private int viewerIndex = 0; /** * Constructor * */ public SubtitleViewer() { try { setLayout(new BorderLayout()); taSubtitle = new JTextArea() { //don't eat up any key events @Override protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { return false; } /** * Override to set rendering hints. */ /* only for J 1.4, new solutions for 1.5 and 1.6 public void paintComponent(Graphics g) { if (g instanceof Graphics2D) { ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } super.paintComponent(g); } */ }; taSubtitle.setFont(Constants.DEFAULTFONT); taSubtitle.setLineWrap(true); taSubtitle.setBackground(Constants.DEFAULTBACKGROUNDCOLOR); taSubtitle.setForeground(Constants.DEFAULTFOREGROUNDCOLOR); taSubtitle.setEditable(false); taSubtitle.addMouseListener(new SubtitleViewerMouseListener(this)); highlighter = taSubtitle.getHighlighter(); selectionPainter = new DefaultHighlighter.DefaultHighlightPainter(Constants.SELECTIONCOLOR); jspSubtitle = new JScrollPane(taSubtitle); add(jspSubtitle, BorderLayout.CENTER); fontSize = 12; setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } /** * Sets minimum for the subtitle viewer See also getPreferredSize * * @return DOCUMENT ME! */ @Override public Dimension getMinimumSize() { return minDimension; } /** * Sets minimum for the subtitle viewer See also getMinimumSize * * @return DOCUMENT ME! */ @Override public Dimension getPreferredSize() { return minDimension; } /** * AR notification that the selection has changed method from SelectionUser * not implemented in AbstractViewer */ @Override public void updateSelection() { doUpdate(); } /** * AR heeft dit hier neergezet, zie abstract viewer voor get en set * methodes van ActiveAnnotation. Update method from ActiveAnnotationUser */ @Override public void updateActiveAnnotation() { } /** * AR heeft dit hier neergezet Er moet nog gepraat worden over wat hier te * doen valt * * @param e DOCUMENT ME! */ @Override public void ACMEdited(ACMEditEvent e) { switch (e.getOperation()) { case ACMEditEvent.ADD_ANNOTATION_HERE: case ACMEditEvent.ADD_ANNOTATION_BEFORE: case ACMEditEvent.ADD_ANNOTATION_AFTER: case ACMEditEvent.CHANGE_ANNOTATIONS: case ACMEditEvent.REMOVE_ANNOTATION: case ACMEditEvent.CHANGE_ANNOTATION_TIME: case ACMEditEvent.CHANGE_ANNOTATION_VALUE: { setTier(getTier()); doUpdate(); } } } /** * Applies (stored) preferences. */ @Override public void preferencesChanged() { Integer fontSi = Preferences.getInt("SubTitleViewer.FontSize-" + viewerIndex, getViewerManager().getTranscription()); if (fontSi != null) { setFontSize(fontSi.intValue()); } if (tier != null) { Map<String, Font> fonts = Preferences.getMapOfFont("TierFonts", getViewerManager().getTranscription()); if (fonts != null) { Font tf = fonts.get(tier.getName()); if (tf != null) { taSubtitle.setFont(new Font(tf.getName(), Font.PLAIN, fontSize)); } else { taSubtitle.setFont(Constants.DEFAULTFONT.deriveFont((float) fontSize)); } } } else { taSubtitle.setFont(Constants.DEFAULTFONT.deriveFont((float) fontSize)); } } /** * method from ElanLocaleListener not implemented in AbstractViewer */ @Override public void updateLocale() { createPopup(); } private void createPopup() { popup = new JPopupMenu(""); fontSizeBG = new ButtonGroup(); fontMenu = new JMenu(ElanLocale.getString("Menu.View.FontSize")); JRadioButtonMenuItem fontRB; for (int element : Constants.FONT_SIZES) { fontRB = new JRadioButtonMenuItem(String.valueOf(element)); fontRB.setActionCommand("font" + element); if (fontSize == element) { fontRB.setSelected(true); } fontRB.addActionListener(this); fontSizeBG.add(fontRB); fontMenu.add(fontRB); } popup.add(fontMenu); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void actionPerformed(ActionEvent e) { String strAction = e.getActionCommand(); if (strAction.indexOf("font") != -1) { int index = strAction.indexOf("font") + 4; try { fontSize = Integer.parseInt(strAction.substring(index)); repaint(); } catch (Exception ex) { ex.printStackTrace(); } taSubtitle.setFont(taSubtitle.getFont().deriveFont((float) fontSize)); setPreference("SubTitleViewer.FontSize-" + viewerIndex, Integer.valueOf(fontSize), getViewerManager().getTranscription()); } } /** * AR notification that some media related event happened method from * ControllerListener not implemented in AbstractViewer * * @param event DOCUMENT ME! */ @Override public void controllerUpdate(ControllerEvent event) { doUpdate(); } /** * Update the complete subtitle viewer Determines whether current time is * in a selection Sets the correct value in the subtitle viewer */ public void doUpdate() { String strTagValue = ""; boolean bFound = false; long mediatime = getMediaTime(); int annotations_size = annotations.size(); if (arrTags == null) { return; } //use fast search to determine approximate index from array int index = Math.abs(Arrays.binarySearch(arrTags, mediatime)); //make it an index which can be used with the vector index = index / 2; //determine first and last index in vector to use in loop int beginindex = index - 2; int endindex = index + 2; if (beginindex < 0) { beginindex = 0; } if (endindex > (annotations_size - 1)) { endindex = annotations_size - 1; } long selectionBeginTime = getSelectionBeginTime(); long selectionEndTime = getSelectionEndTime(); //now there is a maximum of only 5 indexes to loop through for (int i = beginindex; i <= endindex; i++) { Annotation ann = annotations.get(i); begintime = ann.getBeginTimeBoundary(); endtime = ann.getEndTimeBoundary(); // special case: if a selection (active annotation) is played, // at the end mediatime == end time of active annotation. Include endtime // in comparison in such case if ( (ann == getActiveAnnotation() && endtime == mediatime) || (begintime == selectionBeginTime && endtime == selectionEndTime && endtime == mediatime) ) { bFound = true; strTagValue = ann.getValue(); strTagValue = strTagValue.replace('\n', ' '); break; } if ((mediatime >= begintime) && (mediatime < endtime)) { bFound = true; strTagValue = ann.getValue(); /* if (ann == getActiveAnnotation()) { taSubtitle.setBorder(BorderFactory.createLineBorder( Constants.ACTIVEANNOTATIONCOLOR)); } else { taSubtitle.setBorder(null); } */ //next line for JDK1.4 only //strTagValue = strTagValue.replaceAll("\n", ""); strTagValue = strTagValue.replace('\n', ' '); break; } } //set the appropriate text if (bFound) { try { taSubtitle.setText(" " + strTagValue); //+ '\u0332') } catch (Exception ex) { taSubtitle.setText(""); } } else { taSubtitle.setText(""); //taSubtitle.setBorder(null); } //handle colors if ((tier != null) && (selectionBeginTime != selectionEndTime) && (mediatime >= begintime) && ((mediatime < endtime) || (mediatime == endtime && selectionBeginTime == begintime)) && (((selectionBeginTime >= begintime) && (selectionBeginTime < endtime)) || ((selectionEndTime >= begintime) && (selectionEndTime < endtime)))) { try { highlighter.addHighlight(1, taSubtitle.getText().length(), selectionPainter); } catch (Exception ex) { //ex.printStackTrace(); ClientLogger.LOG.warning("Cannot add a highlight: " + ex.getMessage()); } } else { taSubtitle.getHighlighter().removeAllHighlights(); } repaint(); } /** * Sets the tier which is shown in the subtitle viewer * * @param tier The tier which should become visible */ @Override public void setTier(Tier tier) { // added by AR putOriginalComponentBack(); if (tier == null) { this.tier = null; annotations = new ArrayList<Annotation>(); doUpdate(); setPreference("SubTitleViewer.TierName-" + viewerIndex, tier, getViewerManager().getTranscription()); taSubtitle.setFont(Constants.DEFAULTFONT.deriveFont((float) fontSize)); } else { this.tier = (TierImpl) tier; try { annotations = this.tier.getAnnotations(); } catch (Exception ex) { ex.printStackTrace(); } setPreference("SubTitleViewer.TierName-" + viewerIndex, tier.getName(), getViewerManager().getTranscription()); // Object fonts = Preferences.get("TierFonts", getViewerManager().getTranscription()); // if (fonts instanceof HashMap) { // Font tf = (Font) ((HashMap) fonts).get(tier.getName()); // if (tf != null) { // taSubtitle.setFont(new Font(tf.getName(), Font.PLAIN, fontSize)); // } else { // taSubtitle.setFont(Constants.DEFAULTFONT.deriveFont((float) fontSize)); // } // } preferencesChanged(); } buildArray(); doUpdate(); } /** * Gets the tier which is shown in the subtitle viewer * * @return DOCUMENT ME! */ @Override public Tier getTier() { return tier; } /** * Returns the current font size. * * @return the current font size */ public int getFontSize() { return fontSize; } /** * Sets the font size. * * @param size the new font size */ public void setFontSize(int size) { fontSize = size; if (fontSizeBG != null) { Enumeration en = fontSizeBG.getElements(); JMenuItem item; String value; while (en.hasMoreElements()) { item = (JMenuItem) en.nextElement(); value = item.getText(); try { int v = Integer.parseInt(value); if (v == fontSize) { item.setSelected(true); taSubtitle.setFont(taSubtitle.getFont().deriveFont((float) fontSize)); break; } } catch (NumberFormatException nfe) { //// do nothing } } } else { createPopup(); taSubtitle.setFont(taSubtitle.getFont().deriveFont((float) fontSize)); } } /** * The index of this subtitle viewer in the list of subtitle viewers, * first index is 1. * * @return the viewerIndex */ public int getViewerIndex() { return viewerIndex; } /** * Sets the index of this subtitle viewer in the list of subtitle viewers. * * @param viewerIndex the viewerIndex to set */ public void setViewerIndex(int viewerIndex) { this.viewerIndex = viewerIndex; } /** * Builds an array with all begintimes and endtimes from a tag Used for * searching (quickly) a particular tag */ private void buildArray() { int annotations_size = annotations.size(); arrTags = new long[2 * annotations_size]; int arrIndex = 0; for (int i = 0; i < annotations_size; i++) { Annotation ann = annotations.get(i); begintime = ann.getBeginTimeBoundary(); endtime = ann.getEndTimeBoundary(); arrTags[arrIndex++] = begintime; arrTags[arrIndex++] = endtime; } } //when inline edit box disappears, it calls this method public void putOriginalComponentBack() { inlineEditBox = null; removeAll(); add(jspSubtitle, BorderLayout.CENTER); validate(); repaint(); } @Override public void isClosing(){ if(inlineEditBox != null && inlineEditBox.isVisible()){ Boolean boolPref = Preferences.getBool("InlineEdit.DeselectCommits", null); if (boolPref != null && !boolPref) { inlineEditBox.cancelEdit(); } else { inlineEditBox.commitEdit(); } } validate(); repaint(); } /** * Hhandles mouse actions on the subtitle viewer */ private class SubtitleViewerMouseListener extends MouseAdapter { private SubtitleViewer subtitleViewer; /** * Creates a new SubtitleViewerMouseListener instance * * @param sv DOCUMENT ME! */ SubtitleViewerMouseListener(SubtitleViewer sv) { subtitleViewer = sv; } /** * The mouse pressed event handler. * @param e the mouse event */ @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e) || e.isPopupTrigger()) { Point p = e.getPoint(); SwingUtilities.convertPointToScreen(p, subtitleViewer); int x = e.getPoint().x; int y = e.getPoint().y; popup.show(subtitleViewer, x, y); return; } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void mouseClicked(MouseEvent e) { //bring up edit dialog if (e.getClickCount() == 2) { inlineEditBox = new InlineEditBox(true); Annotation annotation = getAnnotation(); if (annotation != null) { if (e.isShiftDown()) { // open CV inlineEditBox.setAnnotation(annotation, true); } else { inlineEditBox.setAnnotation(annotation); } inlineEditBox.setFont(taSubtitle.getFont()); inlineEditBox.configureEditor(JPanel.class, null, getSize()); inlineEditBox.addInlineEditBoxListener(subtitleViewer); removeAll(); add(inlineEditBox, BorderLayout.CENTER); validate(); //repaint(); inlineEditBox.startEdit(); } return; } if (!taSubtitle.getText().equals("")) { stopPlayer(); setActiveAnnotation(getAnnotation()); } } private Annotation getAnnotation() { int annotations_size = annotations.size(); for (int i = 0; i < annotations_size; i++) { Annotation annotation = annotations.get(i); //exact time always exists in this case //if (getSelectionBeginTime() == tag.getBeginTime()) // HS 4 dec 03: the subtitle viewer always seems to show the tag // at the media time, if any if ((getMediaTime() >= annotation.getBeginTimeBoundary()) && (getMediaTime() < annotation.getEndTimeBoundary())) { return annotation; } } return null; } } //end of SubtitleViewerMouseListener @Override public void editingCommitted() { putOriginalComponentBack(); } @Override public void editingCancelled() { putOriginalComponentBack(); } public void setKeyStrokesNotToBeConsumed(List<KeyStroke> ksList) { if(inlineEditBox != null){ inlineEditBox.setKeyStrokesNotToBeConsumed(ksList); } } // public void editingInterrupted() { // isClosing(); // } }
ztl8702/ELAN
src/main/java/mpi/eudico/client/annotator/viewer/SubtitleViewer.java
5,682
//if (getSelectionBeginTime() == tag.getBeginTime())
line_comment
nl
package mpi.eudico.client.annotator.viewer; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.List; import java.util.Map; import javax.swing.ButtonGroup; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.text.DefaultHighlighter; import javax.swing.text.Highlighter; import mpi.eudico.client.annotator.Constants; import mpi.eudico.client.annotator.ElanLocale; import mpi.eudico.client.annotator.InlineEditBoxListener; import mpi.eudico.client.annotator.Preferences; import mpi.eudico.client.annotator.gui.InlineEditBox; import mpi.eudico.client.annotator.util.ClientLogger; import mpi.eudico.client.mediacontrol.ControllerEvent; import mpi.eudico.server.corpora.clom.Annotation; import mpi.eudico.server.corpora.clom.Tier; import mpi.eudico.server.corpora.clomimpl.abstr.TierImpl; import mpi.eudico.server.corpora.event.ACMEditEvent; import mpi.eudico.server.corpora.event.ACMEditListener; /** * Viewer for a subtitle * @version Aug 2005 Identity removed */ @SuppressWarnings("serial") public class SubtitleViewer extends AbstractViewer implements SingleTierViewer, ACMEditListener, ActionListener, InlineEditBoxListener { private JMenu fontMenu; private ButtonGroup fontSizeBG; private int fontSize; private JPopupMenu popup; private Dimension minDimension = new Dimension(400, 50); private JTextArea taSubtitle; private JScrollPane jspSubtitle; private TierImpl tier; private List<? extends Annotation> annotations = new ArrayList<Annotation>(); private long begintime = 0; private long endtime = 0; private long[] arrTags; private Highlighter highlighter; private Highlighter.HighlightPainter selectionPainter; private InlineEditBox inlineEditBox; private int viewerIndex = 0; /** * Constructor * */ public SubtitleViewer() { try { setLayout(new BorderLayout()); taSubtitle = new JTextArea() { //don't eat up any key events @Override protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { return false; } /** * Override to set rendering hints. */ /* only for J 1.4, new solutions for 1.5 and 1.6 public void paintComponent(Graphics g) { if (g instanceof Graphics2D) { ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } super.paintComponent(g); } */ }; taSubtitle.setFont(Constants.DEFAULTFONT); taSubtitle.setLineWrap(true); taSubtitle.setBackground(Constants.DEFAULTBACKGROUNDCOLOR); taSubtitle.setForeground(Constants.DEFAULTFOREGROUNDCOLOR); taSubtitle.setEditable(false); taSubtitle.addMouseListener(new SubtitleViewerMouseListener(this)); highlighter = taSubtitle.getHighlighter(); selectionPainter = new DefaultHighlighter.DefaultHighlightPainter(Constants.SELECTIONCOLOR); jspSubtitle = new JScrollPane(taSubtitle); add(jspSubtitle, BorderLayout.CENTER); fontSize = 12; setVisible(true); } catch (Exception ex) { ex.printStackTrace(); } } /** * Sets minimum for the subtitle viewer See also getPreferredSize * * @return DOCUMENT ME! */ @Override public Dimension getMinimumSize() { return minDimension; } /** * Sets minimum for the subtitle viewer See also getMinimumSize * * @return DOCUMENT ME! */ @Override public Dimension getPreferredSize() { return minDimension; } /** * AR notification that the selection has changed method from SelectionUser * not implemented in AbstractViewer */ @Override public void updateSelection() { doUpdate(); } /** * AR heeft dit hier neergezet, zie abstract viewer voor get en set * methodes van ActiveAnnotation. Update method from ActiveAnnotationUser */ @Override public void updateActiveAnnotation() { } /** * AR heeft dit hier neergezet Er moet nog gepraat worden over wat hier te * doen valt * * @param e DOCUMENT ME! */ @Override public void ACMEdited(ACMEditEvent e) { switch (e.getOperation()) { case ACMEditEvent.ADD_ANNOTATION_HERE: case ACMEditEvent.ADD_ANNOTATION_BEFORE: case ACMEditEvent.ADD_ANNOTATION_AFTER: case ACMEditEvent.CHANGE_ANNOTATIONS: case ACMEditEvent.REMOVE_ANNOTATION: case ACMEditEvent.CHANGE_ANNOTATION_TIME: case ACMEditEvent.CHANGE_ANNOTATION_VALUE: { setTier(getTier()); doUpdate(); } } } /** * Applies (stored) preferences. */ @Override public void preferencesChanged() { Integer fontSi = Preferences.getInt("SubTitleViewer.FontSize-" + viewerIndex, getViewerManager().getTranscription()); if (fontSi != null) { setFontSize(fontSi.intValue()); } if (tier != null) { Map<String, Font> fonts = Preferences.getMapOfFont("TierFonts", getViewerManager().getTranscription()); if (fonts != null) { Font tf = fonts.get(tier.getName()); if (tf != null) { taSubtitle.setFont(new Font(tf.getName(), Font.PLAIN, fontSize)); } else { taSubtitle.setFont(Constants.DEFAULTFONT.deriveFont((float) fontSize)); } } } else { taSubtitle.setFont(Constants.DEFAULTFONT.deriveFont((float) fontSize)); } } /** * method from ElanLocaleListener not implemented in AbstractViewer */ @Override public void updateLocale() { createPopup(); } private void createPopup() { popup = new JPopupMenu(""); fontSizeBG = new ButtonGroup(); fontMenu = new JMenu(ElanLocale.getString("Menu.View.FontSize")); JRadioButtonMenuItem fontRB; for (int element : Constants.FONT_SIZES) { fontRB = new JRadioButtonMenuItem(String.valueOf(element)); fontRB.setActionCommand("font" + element); if (fontSize == element) { fontRB.setSelected(true); } fontRB.addActionListener(this); fontSizeBG.add(fontRB); fontMenu.add(fontRB); } popup.add(fontMenu); } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void actionPerformed(ActionEvent e) { String strAction = e.getActionCommand(); if (strAction.indexOf("font") != -1) { int index = strAction.indexOf("font") + 4; try { fontSize = Integer.parseInt(strAction.substring(index)); repaint(); } catch (Exception ex) { ex.printStackTrace(); } taSubtitle.setFont(taSubtitle.getFont().deriveFont((float) fontSize)); setPreference("SubTitleViewer.FontSize-" + viewerIndex, Integer.valueOf(fontSize), getViewerManager().getTranscription()); } } /** * AR notification that some media related event happened method from * ControllerListener not implemented in AbstractViewer * * @param event DOCUMENT ME! */ @Override public void controllerUpdate(ControllerEvent event) { doUpdate(); } /** * Update the complete subtitle viewer Determines whether current time is * in a selection Sets the correct value in the subtitle viewer */ public void doUpdate() { String strTagValue = ""; boolean bFound = false; long mediatime = getMediaTime(); int annotations_size = annotations.size(); if (arrTags == null) { return; } //use fast search to determine approximate index from array int index = Math.abs(Arrays.binarySearch(arrTags, mediatime)); //make it an index which can be used with the vector index = index / 2; //determine first and last index in vector to use in loop int beginindex = index - 2; int endindex = index + 2; if (beginindex < 0) { beginindex = 0; } if (endindex > (annotations_size - 1)) { endindex = annotations_size - 1; } long selectionBeginTime = getSelectionBeginTime(); long selectionEndTime = getSelectionEndTime(); //now there is a maximum of only 5 indexes to loop through for (int i = beginindex; i <= endindex; i++) { Annotation ann = annotations.get(i); begintime = ann.getBeginTimeBoundary(); endtime = ann.getEndTimeBoundary(); // special case: if a selection (active annotation) is played, // at the end mediatime == end time of active annotation. Include endtime // in comparison in such case if ( (ann == getActiveAnnotation() && endtime == mediatime) || (begintime == selectionBeginTime && endtime == selectionEndTime && endtime == mediatime) ) { bFound = true; strTagValue = ann.getValue(); strTagValue = strTagValue.replace('\n', ' '); break; } if ((mediatime >= begintime) && (mediatime < endtime)) { bFound = true; strTagValue = ann.getValue(); /* if (ann == getActiveAnnotation()) { taSubtitle.setBorder(BorderFactory.createLineBorder( Constants.ACTIVEANNOTATIONCOLOR)); } else { taSubtitle.setBorder(null); } */ //next line for JDK1.4 only //strTagValue = strTagValue.replaceAll("\n", ""); strTagValue = strTagValue.replace('\n', ' '); break; } } //set the appropriate text if (bFound) { try { taSubtitle.setText(" " + strTagValue); //+ '\u0332') } catch (Exception ex) { taSubtitle.setText(""); } } else { taSubtitle.setText(""); //taSubtitle.setBorder(null); } //handle colors if ((tier != null) && (selectionBeginTime != selectionEndTime) && (mediatime >= begintime) && ((mediatime < endtime) || (mediatime == endtime && selectionBeginTime == begintime)) && (((selectionBeginTime >= begintime) && (selectionBeginTime < endtime)) || ((selectionEndTime >= begintime) && (selectionEndTime < endtime)))) { try { highlighter.addHighlight(1, taSubtitle.getText().length(), selectionPainter); } catch (Exception ex) { //ex.printStackTrace(); ClientLogger.LOG.warning("Cannot add a highlight: " + ex.getMessage()); } } else { taSubtitle.getHighlighter().removeAllHighlights(); } repaint(); } /** * Sets the tier which is shown in the subtitle viewer * * @param tier The tier which should become visible */ @Override public void setTier(Tier tier) { // added by AR putOriginalComponentBack(); if (tier == null) { this.tier = null; annotations = new ArrayList<Annotation>(); doUpdate(); setPreference("SubTitleViewer.TierName-" + viewerIndex, tier, getViewerManager().getTranscription()); taSubtitle.setFont(Constants.DEFAULTFONT.deriveFont((float) fontSize)); } else { this.tier = (TierImpl) tier; try { annotations = this.tier.getAnnotations(); } catch (Exception ex) { ex.printStackTrace(); } setPreference("SubTitleViewer.TierName-" + viewerIndex, tier.getName(), getViewerManager().getTranscription()); // Object fonts = Preferences.get("TierFonts", getViewerManager().getTranscription()); // if (fonts instanceof HashMap) { // Font tf = (Font) ((HashMap) fonts).get(tier.getName()); // if (tf != null) { // taSubtitle.setFont(new Font(tf.getName(), Font.PLAIN, fontSize)); // } else { // taSubtitle.setFont(Constants.DEFAULTFONT.deriveFont((float) fontSize)); // } // } preferencesChanged(); } buildArray(); doUpdate(); } /** * Gets the tier which is shown in the subtitle viewer * * @return DOCUMENT ME! */ @Override public Tier getTier() { return tier; } /** * Returns the current font size. * * @return the current font size */ public int getFontSize() { return fontSize; } /** * Sets the font size. * * @param size the new font size */ public void setFontSize(int size) { fontSize = size; if (fontSizeBG != null) { Enumeration en = fontSizeBG.getElements(); JMenuItem item; String value; while (en.hasMoreElements()) { item = (JMenuItem) en.nextElement(); value = item.getText(); try { int v = Integer.parseInt(value); if (v == fontSize) { item.setSelected(true); taSubtitle.setFont(taSubtitle.getFont().deriveFont((float) fontSize)); break; } } catch (NumberFormatException nfe) { //// do nothing } } } else { createPopup(); taSubtitle.setFont(taSubtitle.getFont().deriveFont((float) fontSize)); } } /** * The index of this subtitle viewer in the list of subtitle viewers, * first index is 1. * * @return the viewerIndex */ public int getViewerIndex() { return viewerIndex; } /** * Sets the index of this subtitle viewer in the list of subtitle viewers. * * @param viewerIndex the viewerIndex to set */ public void setViewerIndex(int viewerIndex) { this.viewerIndex = viewerIndex; } /** * Builds an array with all begintimes and endtimes from a tag Used for * searching (quickly) a particular tag */ private void buildArray() { int annotations_size = annotations.size(); arrTags = new long[2 * annotations_size]; int arrIndex = 0; for (int i = 0; i < annotations_size; i++) { Annotation ann = annotations.get(i); begintime = ann.getBeginTimeBoundary(); endtime = ann.getEndTimeBoundary(); arrTags[arrIndex++] = begintime; arrTags[arrIndex++] = endtime; } } //when inline edit box disappears, it calls this method public void putOriginalComponentBack() { inlineEditBox = null; removeAll(); add(jspSubtitle, BorderLayout.CENTER); validate(); repaint(); } @Override public void isClosing(){ if(inlineEditBox != null && inlineEditBox.isVisible()){ Boolean boolPref = Preferences.getBool("InlineEdit.DeselectCommits", null); if (boolPref != null && !boolPref) { inlineEditBox.cancelEdit(); } else { inlineEditBox.commitEdit(); } } validate(); repaint(); } /** * Hhandles mouse actions on the subtitle viewer */ private class SubtitleViewerMouseListener extends MouseAdapter { private SubtitleViewer subtitleViewer; /** * Creates a new SubtitleViewerMouseListener instance * * @param sv DOCUMENT ME! */ SubtitleViewerMouseListener(SubtitleViewer sv) { subtitleViewer = sv; } /** * The mouse pressed event handler. * @param e the mouse event */ @Override public void mousePressed(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e) || e.isPopupTrigger()) { Point p = e.getPoint(); SwingUtilities.convertPointToScreen(p, subtitleViewer); int x = e.getPoint().x; int y = e.getPoint().y; popup.show(subtitleViewer, x, y); return; } } /** * DOCUMENT ME! * * @param e DOCUMENT ME! */ @Override public void mouseClicked(MouseEvent e) { //bring up edit dialog if (e.getClickCount() == 2) { inlineEditBox = new InlineEditBox(true); Annotation annotation = getAnnotation(); if (annotation != null) { if (e.isShiftDown()) { // open CV inlineEditBox.setAnnotation(annotation, true); } else { inlineEditBox.setAnnotation(annotation); } inlineEditBox.setFont(taSubtitle.getFont()); inlineEditBox.configureEditor(JPanel.class, null, getSize()); inlineEditBox.addInlineEditBoxListener(subtitleViewer); removeAll(); add(inlineEditBox, BorderLayout.CENTER); validate(); //repaint(); inlineEditBox.startEdit(); } return; } if (!taSubtitle.getText().equals("")) { stopPlayer(); setActiveAnnotation(getAnnotation()); } } private Annotation getAnnotation() { int annotations_size = annotations.size(); for (int i = 0; i < annotations_size; i++) { Annotation annotation = annotations.get(i); //exact time always exists in this case //if (getSelectionBeginTime()<SUF> // HS 4 dec 03: the subtitle viewer always seems to show the tag // at the media time, if any if ((getMediaTime() >= annotation.getBeginTimeBoundary()) && (getMediaTime() < annotation.getEndTimeBoundary())) { return annotation; } } return null; } } //end of SubtitleViewerMouseListener @Override public void editingCommitted() { putOriginalComponentBack(); } @Override public void editingCancelled() { putOriginalComponentBack(); } public void setKeyStrokesNotToBeConsumed(List<KeyStroke> ksList) { if(inlineEditBox != null){ inlineEditBox.setKeyStrokesNotToBeConsumed(ksList); } } // public void editingInterrupted() { // isClosing(); // } }
93771_7
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package sun.security.provider; import java.io.IOException; import java.security.AccessController; import java.security.DrbgParameters; import java.security.PrivilegedAction; import java.security.SecureRandomParameters; import java.security.SecureRandomSpi; import java.security.Security; import java.util.Locale; import static java.security.DrbgParameters.Capability.*; /** * Implement the "SecureRandom.DRBG" algorithm. * * About the default "securerandom.drbg.config" value: * * The default value in java.security is set to "". This is because * the default values of different aspects are dependent (For example, * strength depends on algorithm) and if we write a full string there * it will be difficult to modify one and keep all others legal. * * When changing default values, touch all places including: * * 1. comments of the security property in java.security * 2. Default mech, cap, usedf set in this class * 3. Default algorithm set in final implementation of each mech * 4. Default strength set in AbstractDrbg, but the effective * value can be smaller if an algorithm does not support it. * * The default value is also mentioned in the @implNote part of * {@link DrbgParameters} class. */ public final class DRBG extends SecureRandomSpi { private static final String PROP_NAME = "securerandom.drbg.config"; private static final long serialVersionUID = 9L; private transient AbstractDrbg impl; /** * @serial */ private final MoreDrbgParameters mdp; public DRBG(SecureRandomParameters params) { // All parameters at unset status (null or -1). // Configurable with the "securerandom.drbg.config" security property String mech = null; Boolean usedf = null; String algorithm = null; // Default instantiate parameters also configurable with // "securerandom.drbg.config", and can be changed with params // in getInstance("drbg", params) int strength = -1; DrbgParameters.Capability cap = null; byte[] ps = null; // Not configurable with public interfaces, but is a part of // MoreDrbgParameters EntropySource es = null; byte[] nonce = null; // Can be configured with a security property String config = AccessController.doPrivileged((PrivilegedAction<String>) () -> Security.getProperty(PROP_NAME)); if (config != null && !config.isEmpty()) { for (String part : config.split(",")) { part = part.trim(); switch (part.toLowerCase(Locale.ROOT)) { case "": throw new IllegalArgumentException( "aspect in " + PROP_NAME + " cannot be empty"); case "pr_and_reseed": checkTwice(cap != null, "capability"); cap = PR_AND_RESEED; break; case "reseed_only": checkTwice(cap != null, "capability"); cap = RESEED_ONLY; break; case "none": checkTwice(cap != null, "capability"); cap = NONE; break; case "hash_drbg": case "hmac_drbg": case "ctr_drbg": checkTwice(mech != null, "mechanism name"); mech = part; break; case "no_df": checkTwice(usedf != null, "usedf flag"); usedf = false; break; case "use_df": checkTwice(usedf != null, "usedf flag"); usedf = true; break; default: // For all other parts of the property, it is // either an algorithm name or a strength try { int tmp = Integer.parseInt(part); if (tmp < 0) { throw new IllegalArgumentException( "strength in " + PROP_NAME + " cannot be negative: " + part); } checkTwice(strength >= 0, "strength"); strength = tmp; } catch (NumberFormatException e) { checkTwice(algorithm != null, "algorithm name"); algorithm = part; } } } } // Can be updated by params if (params != null) { // MoreDrbgParameters is used for testing. if (params instanceof MoreDrbgParameters) { MoreDrbgParameters m = (MoreDrbgParameters) params; params = DrbgParameters.instantiation(m.strength, m.capability, m.personalizationString); // No need to check null for es and nonce, they are still null es = m.es; nonce = m.nonce; if (m.mech != null) { mech = m.mech; } if (m.algorithm != null) { algorithm = m.algorithm; } usedf = m.usedf; } if (params instanceof DrbgParameters.Instantiation) { DrbgParameters.Instantiation dp = (DrbgParameters.Instantiation) params; // ps is still null by now ps = dp.getPersonalizationString(); int tmp = dp.getStrength(); if (tmp != -1) { strength = tmp; } cap = dp.getCapability(); } else { throw new IllegalArgumentException("Unsupported params: " + params.getClass()); } } // Hardcoded defaults. // Remember to sync with "securerandom.drbg.config" in java.security. if (cap == null) { cap = NONE; } if (mech == null) { mech = "Hash_DRBG"; } if (usedf == null) { usedf = true; } mdp = new MoreDrbgParameters( es, mech, algorithm, nonce, usedf, DrbgParameters.instantiation(strength, cap, ps)); createImpl(); } private void createImpl() { switch (mdp.mech.toLowerCase(Locale.ROOT)) { case "hash_drbg": impl = new HashDrbg(mdp); break; case "hmac_drbg": impl = new HmacDrbg(mdp); break; case "ctr_drbg": impl = new CtrDrbg(mdp); break; default: throw new IllegalArgumentException("Unsupported mech: " + mdp.mech); } } @Override protected void engineSetSeed(byte[] seed) { impl.engineSetSeed(seed); } @Override protected void engineNextBytes(byte[] bytes) { impl.engineNextBytes(bytes); } @Override protected byte[] engineGenerateSeed(int numBytes) { return impl.engineGenerateSeed(numBytes); } @Override protected void engineNextBytes( byte[] bytes, SecureRandomParameters params) { impl.engineNextBytes(bytes, params); } @Override protected void engineReseed(SecureRandomParameters params) { impl.engineReseed(params); } @Override protected SecureRandomParameters engineGetParameters() { return impl.engineGetParameters(); } @Override public String toString() { return impl.toString(); } /** * Ensures an aspect is not set more than once. * * @param flag true if set more than once * @param name the name of aspect shown in IAE * @throws IllegalArgumentException if it happens */ private static void checkTwice(boolean flag, String name) { if (flag) { throw new IllegalArgumentException(name + " cannot be provided more than once in " + PROP_NAME); } } private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); if (mdp.mech == null) { throw new IllegalArgumentException("Input data is corrupted"); } createImpl(); } }
zxiaofan/JDK
jdk-11.0.2/src/java.base/sun/security/provider/DRBG.java
2,314
// in getInstance("drbg", params)
line_comment
nl
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package sun.security.provider; import java.io.IOException; import java.security.AccessController; import java.security.DrbgParameters; import java.security.PrivilegedAction; import java.security.SecureRandomParameters; import java.security.SecureRandomSpi; import java.security.Security; import java.util.Locale; import static java.security.DrbgParameters.Capability.*; /** * Implement the "SecureRandom.DRBG" algorithm. * * About the default "securerandom.drbg.config" value: * * The default value in java.security is set to "". This is because * the default values of different aspects are dependent (For example, * strength depends on algorithm) and if we write a full string there * it will be difficult to modify one and keep all others legal. * * When changing default values, touch all places including: * * 1. comments of the security property in java.security * 2. Default mech, cap, usedf set in this class * 3. Default algorithm set in final implementation of each mech * 4. Default strength set in AbstractDrbg, but the effective * value can be smaller if an algorithm does not support it. * * The default value is also mentioned in the @implNote part of * {@link DrbgParameters} class. */ public final class DRBG extends SecureRandomSpi { private static final String PROP_NAME = "securerandom.drbg.config"; private static final long serialVersionUID = 9L; private transient AbstractDrbg impl; /** * @serial */ private final MoreDrbgParameters mdp; public DRBG(SecureRandomParameters params) { // All parameters at unset status (null or -1). // Configurable with the "securerandom.drbg.config" security property String mech = null; Boolean usedf = null; String algorithm = null; // Default instantiate parameters also configurable with // "securerandom.drbg.config", and can be changed with params // in getInstance("drbg",<SUF> int strength = -1; DrbgParameters.Capability cap = null; byte[] ps = null; // Not configurable with public interfaces, but is a part of // MoreDrbgParameters EntropySource es = null; byte[] nonce = null; // Can be configured with a security property String config = AccessController.doPrivileged((PrivilegedAction<String>) () -> Security.getProperty(PROP_NAME)); if (config != null && !config.isEmpty()) { for (String part : config.split(",")) { part = part.trim(); switch (part.toLowerCase(Locale.ROOT)) { case "": throw new IllegalArgumentException( "aspect in " + PROP_NAME + " cannot be empty"); case "pr_and_reseed": checkTwice(cap != null, "capability"); cap = PR_AND_RESEED; break; case "reseed_only": checkTwice(cap != null, "capability"); cap = RESEED_ONLY; break; case "none": checkTwice(cap != null, "capability"); cap = NONE; break; case "hash_drbg": case "hmac_drbg": case "ctr_drbg": checkTwice(mech != null, "mechanism name"); mech = part; break; case "no_df": checkTwice(usedf != null, "usedf flag"); usedf = false; break; case "use_df": checkTwice(usedf != null, "usedf flag"); usedf = true; break; default: // For all other parts of the property, it is // either an algorithm name or a strength try { int tmp = Integer.parseInt(part); if (tmp < 0) { throw new IllegalArgumentException( "strength in " + PROP_NAME + " cannot be negative: " + part); } checkTwice(strength >= 0, "strength"); strength = tmp; } catch (NumberFormatException e) { checkTwice(algorithm != null, "algorithm name"); algorithm = part; } } } } // Can be updated by params if (params != null) { // MoreDrbgParameters is used for testing. if (params instanceof MoreDrbgParameters) { MoreDrbgParameters m = (MoreDrbgParameters) params; params = DrbgParameters.instantiation(m.strength, m.capability, m.personalizationString); // No need to check null for es and nonce, they are still null es = m.es; nonce = m.nonce; if (m.mech != null) { mech = m.mech; } if (m.algorithm != null) { algorithm = m.algorithm; } usedf = m.usedf; } if (params instanceof DrbgParameters.Instantiation) { DrbgParameters.Instantiation dp = (DrbgParameters.Instantiation) params; // ps is still null by now ps = dp.getPersonalizationString(); int tmp = dp.getStrength(); if (tmp != -1) { strength = tmp; } cap = dp.getCapability(); } else { throw new IllegalArgumentException("Unsupported params: " + params.getClass()); } } // Hardcoded defaults. // Remember to sync with "securerandom.drbg.config" in java.security. if (cap == null) { cap = NONE; } if (mech == null) { mech = "Hash_DRBG"; } if (usedf == null) { usedf = true; } mdp = new MoreDrbgParameters( es, mech, algorithm, nonce, usedf, DrbgParameters.instantiation(strength, cap, ps)); createImpl(); } private void createImpl() { switch (mdp.mech.toLowerCase(Locale.ROOT)) { case "hash_drbg": impl = new HashDrbg(mdp); break; case "hmac_drbg": impl = new HmacDrbg(mdp); break; case "ctr_drbg": impl = new CtrDrbg(mdp); break; default: throw new IllegalArgumentException("Unsupported mech: " + mdp.mech); } } @Override protected void engineSetSeed(byte[] seed) { impl.engineSetSeed(seed); } @Override protected void engineNextBytes(byte[] bytes) { impl.engineNextBytes(bytes); } @Override protected byte[] engineGenerateSeed(int numBytes) { return impl.engineGenerateSeed(numBytes); } @Override protected void engineNextBytes( byte[] bytes, SecureRandomParameters params) { impl.engineNextBytes(bytes, params); } @Override protected void engineReseed(SecureRandomParameters params) { impl.engineReseed(params); } @Override protected SecureRandomParameters engineGetParameters() { return impl.engineGetParameters(); } @Override public String toString() { return impl.toString(); } /** * Ensures an aspect is not set more than once. * * @param flag true if set more than once * @param name the name of aspect shown in IAE * @throws IllegalArgumentException if it happens */ private static void checkTwice(boolean flag, String name) { if (flag) { throw new IllegalArgumentException(name + " cannot be provided more than once in " + PROP_NAME); } } private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); if (mdp.mech == null) { throw new IllegalArgumentException("Input data is corrupted"); } createImpl(); } }
17524_1
/* * Copyright 2018 ZXing authors * * 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.zxing.client.j2se; import com.beust.jcommander.JCommander; import org.junit.Assert; import org.junit.Test; import java.net.URI; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; /** * Tests {@link DecodeWorker}. */ public final class DecodeWorkerTestCase extends Assert { static final String IMAGE_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAhAQAAAAB/n//CAAAAkklEQVR42mP4DwQNDJjkB4" + "E77A0M369N/d7A8CV6rjiQjPMFkWG1QPL7RVGg%2BAfREKCa/5/vA9V/nFSQ3sDwb7/KdiDJqX4dSH4pXN/A8DfyDVD2" + "988HQPUfPVaqA0XKz%2BgD9bIk1AP1fgwvB7KlS9VBdqXbA82PT9AH2fiaH2SXGdDM71fDgeIfhIvKsbkTTAIAKYVr0N" + "z5IloAAAAASUVORK5CYII="; static final String IMAGE_NOBARCODE_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAACE1BMVEUAAAAYsPIXsPL//+" + "2J6/CI6vB74/Alt/IXr/LL/++M7PD//+UZsPIXr/ISrfIRrPIXsPIYsPIYsPIKqfIQrPITrvIZsfImt/IouPImt/IZsf" + "IXr/IXsPIbsfIWr/IcsvInuPImuPIvvPJt3PB54vBt3PAasfIXsPIXr/IUrvIYsPIwvfJx3vB54vCE6PCS7/B64/Bt3P" + "AktvIXr/IYsPIYsPIasfIlt/IwvPKJ6/CM7PCW8fCQ7vCB5vAmt/IXr/IYsPIYsPIXsPKI6vCI6vCI6vAYsfMYsPIYsP" + "KI6vCI6vCI6vAYrO0YsPGI6vCI6vCI6vCJ6/CH6vBw3vB64/CE6PAwvPJr2/FLy/ESrfIYsPIjtvIasfIYsPIYsPIYsP" + "IYsPIYsPIYsPIYsPIYsPIYre4vvPIktvJ64/Bx3vCI6vAitfJj1/F74/CH6vAbsfI7wvF/5fCJ6vAXsPJw3fAWmNEYre" + "0mt/J85PCJ6/Bw3vAXqukYr/EYsPIZsPIwvPJ95PAjtvIVksgWmtQYre4VlMsXpuUVkccWl9AXquouu/Jy3/AWl88Wm9" + "QXpuQYrO0ZsfIVkcgVlMwWmNAXqekVisIVkMcVkscWm9UTXaQVgr0VisMVlcwTT5oTVZ4TXKMVhL4TTpoTTZoTW6MVg7" + "4Vj8YVicIVkMYVi8MUfbkTVZ8UfLkUY6gTVJ4Vg70TT5sTVp/hyCW0AAAAZnRSTlMAAAAAAAAAAAAAAAACGx8fHxsCAh" + "k2yeTi4uLJMgEZNsnm++fi5s80GTbJ5v3NNhzJ4uCvFwHJ5v3mNgIbHx8cBDHN/ckZOcz+5jYC5f3k4Bzk/f3NMv7NNh" + "0f/eTg4jYd/eQZ5v3GzkXBAAAByUlEQVQ4y73TvW4TQRSG4e/dtbHx2hv/FBEIEBWIEgmLhoaGittJRYeEfAUUFBS+Ai" + "qIoIBQgGQRFKWwoAxgKYog3vXf2uvx7lAkBDvyio7TnkffnDOaQf8o/h/4C+06gOQB1oHgnEASosZZ9VYFQvLqp837vO" + "NnsAqQdwXg3oeTI+DzOXDn8DLcZo8OdwF4vwqaZW4BXdiRrAPxuRkewE3gC7wxa+/hITfGlXkXdrQebJHkoLvICBBbJO" + "PG+BsvlQEeAbAfZydccCI//jrMnOExxMDrWtYWT4iI/LiTtQYtGIsybwd7GLMOKB84UqUDrxbzNe+hJeNNY+F2AbYJlp" + "r2BKQX6UvR1U/AbpP5aXebQLKipRIQxlJUknr8GYPdZu5FINGSpNSPRsVZcVhYyu+5H5vMxVMIJZHW+5VJ2UxiqTArep" + "NZcXaUGIlnYAaS0sR1lG5O+X4tjiuWUT2yhXBW5DlwWA3PktPNo8RN8sZN3MT1RwFtrMO0FNaCoXzVDyTper8WVF17IO" + "OWaUsLTDWsTfIyc+eXr6EuWS+oM/shX9CWhKmGeVPRtHxcMtqIbIqpOmNKAxnaS1/E+migDR3nJGnR0GDR+A23fMFDA8" + "6WRQAAAABJRU5ErkJggg=="; @Test public void testWorker() throws Exception { DecoderConfig config = new DecoderConfig(); JCommander jCommander = new JCommander(config); jCommander.parse("--pure_barcode", IMAGE_DATA_URI); Queue<URI> inputs = new LinkedList<>(Collections.singletonList(new URI(IMAGE_DATA_URI))); DecodeWorker worker = new DecodeWorker(config, inputs); assertEquals(1, worker.call().intValue()); } }
zxing/zxing
javase/src/test/java/com/google/zxing/client/j2se/DecodeWorkerTestCase.java
1,982
/** * Tests {@link DecodeWorker}. */
block_comment
nl
/* * Copyright 2018 ZXing authors * * 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.zxing.client.j2se; import com.beust.jcommander.JCommander; import org.junit.Assert; import org.junit.Test; import java.net.URI; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; /** * Tests {@link DecodeWorker}.<SUF>*/ public final class DecodeWorkerTestCase extends Assert { static final String IMAGE_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACEAAAAhAQAAAAB/n//CAAAAkklEQVR42mP4DwQNDJjkB4" + "E77A0M369N/d7A8CV6rjiQjPMFkWG1QPL7RVGg%2BAfREKCa/5/vA9V/nFSQ3sDwb7/KdiDJqX4dSH4pXN/A8DfyDVD2" + "988HQPUfPVaqA0XKz%2BgD9bIk1AP1fgwvB7KlS9VBdqXbA82PT9AH2fiaH2SXGdDM71fDgeIfhIvKsbkTTAIAKYVr0N" + "z5IloAAAAASUVORK5CYII="; static final String IMAGE_NOBARCODE_DATA_URI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAACE1BMVEUAAAAYsPIXsPL//+" + "2J6/CI6vB74/Alt/IXr/LL/++M7PD//+UZsPIXr/ISrfIRrPIXsPIYsPIYsPIKqfIQrPITrvIZsfImt/IouPImt/IZsf" + "IXr/IXsPIbsfIWr/IcsvInuPImuPIvvPJt3PB54vBt3PAasfIXsPIXr/IUrvIYsPIwvfJx3vB54vCE6PCS7/B64/Bt3P" + "AktvIXr/IYsPIYsPIasfIlt/IwvPKJ6/CM7PCW8fCQ7vCB5vAmt/IXr/IYsPIYsPIXsPKI6vCI6vCI6vAYsfMYsPIYsP" + "KI6vCI6vCI6vAYrO0YsPGI6vCI6vCI6vCJ6/CH6vBw3vB64/CE6PAwvPJr2/FLy/ESrfIYsPIjtvIasfIYsPIYsPIYsP" + "IYsPIYsPIYsPIYsPIYsPIYre4vvPIktvJ64/Bx3vCI6vAitfJj1/F74/CH6vAbsfI7wvF/5fCJ6vAXsPJw3fAWmNEYre" + "0mt/J85PCJ6/Bw3vAXqukYr/EYsPIZsPIwvPJ95PAjtvIVksgWmtQYre4VlMsXpuUVkccWl9AXquouu/Jy3/AWl88Wm9" + "QXpuQYrO0ZsfIVkcgVlMwWmNAXqekVisIVkMcVkscWm9UTXaQVgr0VisMVlcwTT5oTVZ4TXKMVhL4TTpoTTZoTW6MVg7" + "4Vj8YVicIVkMYVi8MUfbkTVZ8UfLkUY6gTVJ4Vg70TT5sTVp/hyCW0AAAAZnRSTlMAAAAAAAAAAAAAAAACGx8fHxsCAh" + "k2yeTi4uLJMgEZNsnm++fi5s80GTbJ5v3NNhzJ4uCvFwHJ5v3mNgIbHx8cBDHN/ckZOcz+5jYC5f3k4Bzk/f3NMv7NNh" + "0f/eTg4jYd/eQZ5v3GzkXBAAAByUlEQVQ4y73TvW4TQRSG4e/dtbHx2hv/FBEIEBWIEgmLhoaGittJRYeEfAUUFBS+Ai" + "qIoIBQgGQRFKWwoAxgKYog3vXf2uvx7lAkBDvyio7TnkffnDOaQf8o/h/4C+06gOQB1oHgnEASosZZ9VYFQvLqp837vO" + "NnsAqQdwXg3oeTI+DzOXDn8DLcZo8OdwF4vwqaZW4BXdiRrAPxuRkewE3gC7wxa+/hITfGlXkXdrQebJHkoLvICBBbJO" + "PG+BsvlQEeAbAfZydccCI//jrMnOExxMDrWtYWT4iI/LiTtQYtGIsybwd7GLMOKB84UqUDrxbzNe+hJeNNY+F2AbYJlp" + "r2BKQX6UvR1U/AbpP5aXebQLKipRIQxlJUknr8GYPdZu5FINGSpNSPRsVZcVhYyu+5H5vMxVMIJZHW+5VJ2UxiqTArep" + "NZcXaUGIlnYAaS0sR1lG5O+X4tjiuWUT2yhXBW5DlwWA3PktPNo8RN8sZN3MT1RwFtrMO0FNaCoXzVDyTper8WVF17IO" + "OWaUsLTDWsTfIyc+eXr6EuWS+oM/shX9CWhKmGeVPRtHxcMtqIbIqpOmNKAxnaS1/E+migDR3nJGnR0GDR+A23fMFDA8" + "6WRQAAAABJRU5ErkJggg=="; @Test public void testWorker() throws Exception { DecoderConfig config = new DecoderConfig(); JCommander jCommander = new JCommander(config); jCommander.parse("--pure_barcode", IMAGE_DATA_URI); Queue<URI> inputs = new LinkedList<>(Collections.singletonList(new URI(IMAGE_DATA_URI))); DecodeWorker worker = new DecodeWorker(config, inputs); assertEquals(1, worker.call().intValue()); } }
172296_1
package competition.practice.round1C2016; import competition.utility.MyIn; import competition.utility.MyOut; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.PriorityQueue; /** * Created by zzt on 5/8/16. * <p> * Usage: */ public class Senators { public static void main(String[] args) { MyIn in; MyOut out = new MyOut("res"); try { in = new MyIn("testCase/senator-large.in"); } catch (FileNotFoundException e) { e.printStackTrace(); return; } int trail = in.nextInt(); in.nextLine(); String res; for (int i = 0; i < trail; i++) { in.nextLine(); res = eva(in.oneLineToInt(" ")); out.println("Case #" + (i + 1) + ": " + res); } } static class Party implements Comparable<Party> { final int num; final char c; public Party(int num, char c) { this.num = num; this.c = c; } @Override public int compareTo(Party o) { return -Integer.compare(num, o.num); } } private static String eva(ArrayList<Integer> list) { char c = 'A'; int sum = 0; PriorityQueue<Party> parties = new PriorityQueue<>(list.size()); for (Integer integer : list) { parties.add(new Party(integer, c++)); sum += integer; } StringBuilder res = new StringBuilder(); while (!parties.isEmpty()) { final Party max = parties.poll(); Party sec; if ((sec = parties.poll()) != null) { res.append(sec.c); if (sec.num > 1) { parties.add(new Party(sec.num - 1, sec.c)); } } res.append(max.c).append(" "); if (max.num > 1) { parties.add(new Party(max.num - 1, max.c)); } } if (sum % 2 != 0) {// swap last two elements? final String substring = res.substring(res.length() - 5); final StringBuilder tmp = res.delete(res.length() - 5, res.length()); tmp.append(substring.substring(3)).append(substring.substring(0, 3)); res = tmp; } return res.toString(); } }
zzt93/Daily-pracitce
java/algo/src/main/java/competition/practice/round1C2016/Senators.java
714
// swap last two elements?
line_comment
nl
package competition.practice.round1C2016; import competition.utility.MyIn; import competition.utility.MyOut; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.PriorityQueue; /** * Created by zzt on 5/8/16. * <p> * Usage: */ public class Senators { public static void main(String[] args) { MyIn in; MyOut out = new MyOut("res"); try { in = new MyIn("testCase/senator-large.in"); } catch (FileNotFoundException e) { e.printStackTrace(); return; } int trail = in.nextInt(); in.nextLine(); String res; for (int i = 0; i < trail; i++) { in.nextLine(); res = eva(in.oneLineToInt(" ")); out.println("Case #" + (i + 1) + ": " + res); } } static class Party implements Comparable<Party> { final int num; final char c; public Party(int num, char c) { this.num = num; this.c = c; } @Override public int compareTo(Party o) { return -Integer.compare(num, o.num); } } private static String eva(ArrayList<Integer> list) { char c = 'A'; int sum = 0; PriorityQueue<Party> parties = new PriorityQueue<>(list.size()); for (Integer integer : list) { parties.add(new Party(integer, c++)); sum += integer; } StringBuilder res = new StringBuilder(); while (!parties.isEmpty()) { final Party max = parties.poll(); Party sec; if ((sec = parties.poll()) != null) { res.append(sec.c); if (sec.num > 1) { parties.add(new Party(sec.num - 1, sec.c)); } } res.append(max.c).append(" "); if (max.num > 1) { parties.add(new Party(max.num - 1, max.c)); } } if (sum % 2 != 0) {// swap last<SUF> final String substring = res.substring(res.length() - 5); final StringBuilder tmp = res.delete(res.length() - 5, res.length()); tmp.append(substring.substring(3)).append(substring.substring(0, 3)); res = tmp; } return res.toString(); } }