repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
gawkermedia/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201602/CustomFieldPage.java
7820
/** * CustomFieldPage.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201602; /** * Captures a page of {@link CustomField} objects. */ public class CustomFieldPage implements java.io.Serializable { /* The size of the total result set to which this page belongs. */ private java.lang.Integer totalResultSetSize; /* The absolute index in the total result set on which this page * begins. */ private java.lang.Integer startIndex; /* The collection of custom fields contained within this page. */ private com.google.api.ads.dfp.axis.v201602.CustomField[] results; public CustomFieldPage() { } public CustomFieldPage( java.lang.Integer totalResultSetSize, java.lang.Integer startIndex, com.google.api.ads.dfp.axis.v201602.CustomField[] results) { this.totalResultSetSize = totalResultSetSize; this.startIndex = startIndex; this.results = results; } /** * Gets the totalResultSetSize value for this CustomFieldPage. * * @return totalResultSetSize * The size of the total result set to which this page belongs. */ public java.lang.Integer getTotalResultSetSize() { return totalResultSetSize; } /** * Sets the totalResultSetSize value for this CustomFieldPage. * * @param totalResultSetSize * The size of the total result set to which this page belongs. */ public void setTotalResultSetSize(java.lang.Integer totalResultSetSize) { this.totalResultSetSize = totalResultSetSize; } /** * Gets the startIndex value for this CustomFieldPage. * * @return startIndex * The absolute index in the total result set on which this page * begins. */ public java.lang.Integer getStartIndex() { return startIndex; } /** * Sets the startIndex value for this CustomFieldPage. * * @param startIndex * The absolute index in the total result set on which this page * begins. */ public void setStartIndex(java.lang.Integer startIndex) { this.startIndex = startIndex; } /** * Gets the results value for this CustomFieldPage. * * @return results * The collection of custom fields contained within this page. */ public com.google.api.ads.dfp.axis.v201602.CustomField[] getResults() { return results; } /** * Sets the results value for this CustomFieldPage. * * @param results * The collection of custom fields contained within this page. */ public void setResults(com.google.api.ads.dfp.axis.v201602.CustomField[] results) { this.results = results; } public com.google.api.ads.dfp.axis.v201602.CustomField getResults(int i) { return this.results[i]; } public void setResults(int i, com.google.api.ads.dfp.axis.v201602.CustomField _value) { this.results[i] = _value; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof CustomFieldPage)) return false; CustomFieldPage other = (CustomFieldPage) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.totalResultSetSize==null && other.getTotalResultSetSize()==null) || (this.totalResultSetSize!=null && this.totalResultSetSize.equals(other.getTotalResultSetSize()))) && ((this.startIndex==null && other.getStartIndex()==null) || (this.startIndex!=null && this.startIndex.equals(other.getStartIndex()))) && ((this.results==null && other.getResults()==null) || (this.results!=null && java.util.Arrays.equals(this.results, other.getResults()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getTotalResultSetSize() != null) { _hashCode += getTotalResultSetSize().hashCode(); } if (getStartIndex() != null) { _hashCode += getStartIndex().hashCode(); } if (getResults() != null) { for (int i=0; i<java.lang.reflect.Array.getLength(getResults()); i++) { java.lang.Object obj = java.lang.reflect.Array.get(getResults(), i); if (obj != null && !obj.getClass().isArray()) { _hashCode += obj.hashCode(); } } } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(CustomFieldPage.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "CustomFieldPage")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("totalResultSetSize"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "totalResultSetSize")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("startIndex"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "startIndex")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("results"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "results")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201602", "CustomField")); elemField.setMinOccurs(0); elemField.setNillable(false); elemField.setMaxOccursUnbounded(true); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
LittleLazyCat/TXEYXXK
2017workspace/wxqyh/src/com/bruce/wechat/oauth2/OAuth2Servlet.java
1430
package com.bruce.wechat.oauth2; /** * OAuth2 servlet类 * * @author ivhhs * @date 2014.10.16 */ import com.bruce.wechat.ParamesAPI.ParamesAPI; import com.bruce.wechat.ParamesAPI.WeixinUtil; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class OAuth2Servlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String code = request.getParameter("code"); if (!"authdeny".equals(code)) { String access_token = WeixinUtil.getAccessToken(ParamesAPI.corpId, ParamesAPI.secret).getToken(); // agentid 跳转链接时所在的企业应用ID // 管理员须拥有agent的使用权限;agentid必须和跳转链接时所在的企业应用ID相同 String UserID = OAuth2Core.getUserID(access_token, code, "您的agentid"); request.setAttribute("UserID", UserID); } else { out.print("授权获取失败,至于为什么,自己找原因。。。"); } // 跳转到index.jsp request.getRequestDispatcher("index.jsp").forward(request, response); } }
apache-2.0
jerkar/jerkar
dev.jeka.core/src/main/java/dev/jeka/core/api/depmanagement/JkFileSystemDependency.java
2003
package dev.jeka.core.api.depmanagement; import dev.jeka.core.api.utils.JkUtilsIterable; import dev.jeka.core.api.utils.JkUtilsPath; import java.nio.file.Path; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * A dependency on files located on file system. */ public final class JkFileSystemDependency implements JkFileDependency { private final Path ideProjectDir; private JkFileSystemDependency(Iterable<Path> files, Path ideProjectDir) { this.files = Collections.unmodifiableList(JkUtilsIterable.listWithoutDuplicateOf(files)); this.ideProjectDir = ideProjectDir; } /** * Creates a {@link JkFileSystemDependency} on the specified files. */ public static JkFileSystemDependency of(Iterable<Path> files) { final Iterable<Path> trueFiles = JkUtilsPath.disambiguate(files); return new JkFileSystemDependency(trueFiles, null); } private final List<Path> files; @Override public final List<Path> getFiles() { return files; } public JkFileSystemDependency minusFile(Path file) { List<Path> result = new LinkedList<>(files); result.remove(file); return new JkFileSystemDependency(result, ideProjectDir); } @Override public String toString() { return "Files=" + files.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final JkFileSystemDependency that = (JkFileSystemDependency) o; return files.equals(that.files); } @Override public int hashCode() { return files.hashCode(); } @Override public Path getIdeProjectDir() { return ideProjectDir; } @Override public JkFileSystemDependency withIdeProjectDir(Path path) { return new JkFileSystemDependency(files, path); } }
apache-2.0
mapr-demos/mapr-music
data-generator/src/main/java/Main.java
167
import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { new OptionParser(args).parseOpts(); } }
apache-2.0
Anteoy/jottings
src/main/java/com/anteoy/coreJava/niotest/TCPEchoClientNonblocking.java
3193
package com.anteoy.coreJava.niotest; import java.net.InetSocketAddress; import java.net.SocketException; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; /** * @auther zhoudazhuang * @date 19-5-8 21:19 * @description */ public class TCPEchoClientNonblocking { public static void main(String args[]) throws Exception{ if ((args.length < 2) || (args.length > 3)) throw new IllegalArgumentException("参数不正确"); //第一个参数作为要连接的服务端的主机名或IP String server = args[0]; //第二个参数为要发送到服务端的字符串 byte[] argument = args[1].getBytes(); //如果有第三个参数,则作为端口号,如果没有,则端口号设为7 int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7; //创建一个信道,并设为非阻塞模式 SocketChannel clntChan = SocketChannel.open(); clntChan.configureBlocking(false); //向服务端发起连接 if (!clntChan.connect(new InetSocketAddress(server, servPort))){ //不断地轮询连接状态,直到完成连接 while (!clntChan.finishConnect()){ //在等待连接的时间里,可以执行其他任务,以充分发挥非阻塞IO的异步特性 //这里为了演示该方法的使用,只是一直打印"." System.out.print("."); } } //为了与后面打印的"."区别开来,这里输出换行符 System.out.print("????\n"); //分别实例化用来读写的缓冲区 ByteBuffer writeBuf = ByteBuffer.wrap(argument); ByteBuffer readBuf = ByteBuffer.allocate(argument.length); //接收到的总的字节数 int totalBytesRcvd = 0; //每一次调用read()方法接收到的字节数 int bytesRcvd; //循环执行,直到接收到的字节数与发送的字符串的字节数相等 while (totalBytesRcvd < argument.length){ //如果用来向通道中写数据的缓冲区中还有剩余的字节,则继续将数据写入信道 if (writeBuf.hasRemaining()){ System.out.println("通道中写数据的缓冲区中还有剩余的字节,则继续将数据写入信道"); clntChan.write(writeBuf); } //如果read()接收到-1,表明服务端关闭,抛出异常 if ((bytesRcvd = clntChan.read(readBuf)) == -1){ throw new SocketException("Connection closed prematurely"); } //计算接收到的总字节数 totalBytesRcvd += bytesRcvd; //在等待通信完成的过程中,程序可以执行其他任务,以体现非阻塞IO的异步特性 //这里为了演示该方法的使用,同样只是一直打印"." System.out.printf("读缓冲区收到总字节数:%d\n",totalBytesRcvd); } //打印出接收到的数据 System.out.println("Received: " + new String(readBuf.array(), 0, totalBytesRcvd)); //关闭信道 clntChan.close(); } }
apache-2.0
anchela/jackrabbit-oak
oak-core/src/main/java/org/apache/jackrabbit/oak/security/user/monitor/UserMonitorImpl.java
4084
package org.apache.jackrabbit.oak.security.user.monitor; import org.apache.jackrabbit.oak.stats.MeterStats; import org.apache.jackrabbit.oak.stats.StatisticsProvider; import org.apache.jackrabbit.oak.stats.StatsOptions; import org.apache.jackrabbit.oak.stats.TimerStats; import static java.util.concurrent.TimeUnit.NANOSECONDS; public class UserMonitorImpl implements UserMonitor { private static final String ADD_MEMBERS_FAILED = "security.user.add_members.failed"; private static final String ADD_MEMBERS_SUCCEEDED = "security.user.add_members.succeeded"; private static final String ADD_MEMBERS_TIMER = "security.user.add_members.timer"; private static final String REMOVE_MEMBERS_FAILED = "security.user.remove_members.failed"; private static final String REMOVE_MEMBERS_SUCCEEDED = "security.user.remove_members.succeeded"; private static final String REMOVE_MEMBERS_TIMER = "security.user.remove_members.timer"; private static final String GET_MEMBERS_TIMER = "security.user.get_members.timer"; private static final String GET_DECLARED_MEMBERS_TIMER = "security.user.get_declared_members.timer"; private static final String MEMBEROF_TIMER = "security.user.memberof.timer"; private static final String DECLARED_MEMBEROF_TIMER = "security.user.declared_memberof.timer"; private final MeterStats addMembersFailed; private final MeterStats addMembersSucceeded; private final TimerStats addMembersTimer; private final MeterStats removeMembersFailed; private final MeterStats removeMembersSucceeded; private final TimerStats removeMembersTimer; private final TimerStats getMembersTimer; private final TimerStats getDeclaredMembersTimer; private final TimerStats memberOfTimer; private final TimerStats declaredMemberOfTimer; public UserMonitorImpl(StatisticsProvider statisticsProvider) { addMembersFailed = statisticsProvider.getMeter(ADD_MEMBERS_FAILED, StatsOptions.DEFAULT); addMembersSucceeded = statisticsProvider.getMeter(ADD_MEMBERS_SUCCEEDED, StatsOptions.DEFAULT); addMembersTimer = statisticsProvider.getTimer(ADD_MEMBERS_TIMER, StatsOptions.METRICS_ONLY); removeMembersFailed = statisticsProvider.getMeter(REMOVE_MEMBERS_FAILED, StatsOptions.DEFAULT); removeMembersSucceeded = statisticsProvider.getMeter(REMOVE_MEMBERS_SUCCEEDED, StatsOptions.DEFAULT); removeMembersTimer = statisticsProvider.getTimer(REMOVE_MEMBERS_TIMER, StatsOptions.METRICS_ONLY); getMembersTimer = statisticsProvider.getTimer(GET_MEMBERS_TIMER, StatsOptions.METRICS_ONLY); getDeclaredMembersTimer = statisticsProvider.getTimer(GET_DECLARED_MEMBERS_TIMER, StatsOptions.METRICS_ONLY); memberOfTimer = statisticsProvider.getTimer(MEMBEROF_TIMER, StatsOptions.METRICS_ONLY); declaredMemberOfTimer = statisticsProvider.getTimer(DECLARED_MEMBEROF_TIMER, StatsOptions.METRICS_ONLY); } @Override public void doneGetMembers(long timeTakenNanos, boolean declaredOnly) { if (declaredOnly) { getMembersTimer.update(timeTakenNanos, NANOSECONDS); } else { getDeclaredMembersTimer.update(timeTakenNanos, NANOSECONDS); } } @Override public void doneMemberOf(long timeTakenNanos, boolean declaredOnly) { if (declaredOnly) { declaredMemberOfTimer.update(timeTakenNanos, NANOSECONDS); } else { memberOfTimer.update(timeTakenNanos, NANOSECONDS); } } @Override public void doneUpdateMembers(long timeTakenNanos, long totalProcessed, long failed, boolean isRemove) { long successCnt = totalProcessed - failed; if (isRemove) { removeMembersFailed.mark(failed); removeMembersSucceeded.mark(successCnt); removeMembersTimer.update(timeTakenNanos, NANOSECONDS); } else { addMembersFailed.mark(failed); addMembersSucceeded.mark(successCnt); addMembersTimer.update(timeTakenNanos, NANOSECONDS); } } }
apache-2.0
JNOSQL/diana-driver
orientdb-driver/src/test/java/org/jnosql/diana/orientdb/document/ContactType.java
680
/* * Copyright (c) 2017 Otávio Santana and others * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Apache License v2.0 is available at http://www.opensource.org/licenses/apache2.0.php. * * You may elect to redistribute this code under either of these licenses. * * Contributors: * * Otavio Santana */ package org.jnosql.diana.orientdb.document; public enum ContactType { EMAIL, MOBILE, PHONE }
apache-2.0
wso2/andes
modules/andes-core/broker/src/main/java/org/wso2/andes/configuration/qpid/ServerConfiguration.java
24956
/* * Copyright (c) 2005-2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.andes.configuration.qpid; import org.apache.commons.configuration.*; import org.apache.commons.configuration.Configuration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.andes.configuration.AndesConfigurationManager; import org.wso2.andes.configuration.enums.AndesConfiguration; import org.wso2.andes.configuration.modules.JKSStore; import org.wso2.andes.configuration.qpid.plugins.ConfigurationPlugin; import org.wso2.andes.kernel.AndesException; import org.wso2.andes.server.registry.ApplicationRegistry; import org.wso2.andes.server.virtualhost.VirtualHost; import org.wso2.andes.server.virtualhost.VirtualHostRegistry; import sun.misc.Signal; import sun.misc.SignalHandler; import java.io.File; import java.util.*; import java.util.Map.Entry; import static org.wso2.andes.transport.ConnectionSettings.WILDCARD_ADDRESS; public class ServerConfiguration extends ConfigurationPlugin implements SignalHandler { protected static final Log _logger = LogFactory.getLog(ServerConfiguration.class); // Default Configuration values public static final int DEFAULT_BUFFER_SIZE = 262144; public static final int DEFAULT_SOCKET_BUFFER_SIZE = 32768; public static final String DEFAULT_STATUS_UPDATES = "on"; public static final String SECURITY_CONFIG_RELOADED = "SECURITY CONFIGURATION RELOADED"; public static final int DEFAULT_FRAME_SIZE = 65536; public static final int DEFAULT_PORT = 5672; public static final int DEFAULT_SSL_PORT = 8672; public static final long DEFAULT_HOUSEKEEPING_PERIOD = 30000L; public static final int DEFAULT_JMXPORT = 8999; public static final String QPID_HOME = "QPID_HOME"; public static final String QPID_WORK = "QPID_WORK"; private Map<String, VirtualHostConfiguration> _virtualHosts = new HashMap<String, VirtualHostConfiguration>(); private File _configFile; private File _vhostsFile; // Map of environment variables to config items private static final Map<String, String> envVarMap = new HashMap<String, String>(); // Configuration values to be read from the configuration file public static final String MGMT_CUSTOM_REGISTRY_SOCKET = "management.custom-registry-socket"; public static final String STATUS_UPDATES = "status-updates"; public static final String ADVANCED_LOCALE = "advanced.locale"; static { envVarMap.put("QPID_ENABLEDIRECTBUFFERS", "advanced.enableDirectBuffers"); envVarMap.put("QPID_SSLPORT", "connector.ssl.port"); envVarMap.put("QPID_WRITEBIASED", "advanced.useWriteBiasedPool"); envVarMap.put("QPID_JMXPORT", "management.jmxport"); envVarMap.put("QPID_FRAMESIZE", "advanced.framesize"); envVarMap.put("QPID_MSGAUTH", "security.msg-auth"); envVarMap.put("QPID_AUTOREGISTER", "auto_register"); envVarMap.put("QPID_MANAGEMENTENABLED", "management.enabled"); envVarMap.put("QPID_HEARTBEATDELAY", "heartbeat.delay"); envVarMap.put("QPID_HEARTBEATTIMEOUTFACTOR", "heartbeat.timeoutFactor"); envVarMap.put("QPID_MAXIMUMMESSAGEAGE", "maximumMessageAge"); envVarMap.put("QPID_MAXIMUMMESSAGECOUNT", "maximumMessageCount"); envVarMap.put("QPID_MAXIMUMQUEUEDEPTH", "maximumQueueDepth"); envVarMap.put("QPID_MAXIMUMMESSAGESIZE", "maximumMessageSize"); envVarMap.put("QPID_MAXIMUMCHANNELCOUNT", "maximumChannelCount"); envVarMap.put("QPID_MINIMUMALERTREPEATGAP", "minimumAlertRepeatGap"); envVarMap.put("QPID_QUEUECAPACITY", "capacity"); envVarMap.put("QPID_FLOWRESUMECAPACITY", "flowResumeCapacity"); envVarMap.put("QPID_SOCKETRECEIVEBUFFER", "connector.socketReceiveBuffer"); envVarMap.put("QPID_SOCKETWRITEBUFFER", "connector.socketWriteBuffer"); envVarMap.put("QPID_TCPNODELAY", "connector.tcpNoDelay"); envVarMap.put("QPID_ENABLEPOOLEDALLOCATOR", "advanced.enablePooledAllocator"); envVarMap.put("QPID_STATUS-UPDATES", "status-updates"); } /** * Loads the given file and sets up the HUP signal handler. * <p/> * This will load the file and present the root level properties but will * not perform any virtualhost configuration. * <p/> * To perform this {@link #initialise()} must be called. * <p/> * This has been made a two step process to allow the Plugin Manager and * Configuration Manager to be initialised in the Application Registry. * <p/> * If using this ServerConfiguration via an ApplicationRegistry there is no * need to explictly call {@link #initialise()} as this is done via the * {@link ApplicationRegistry#initialise()} method. * * @param configurationURL * @throws org.apache.commons.configuration.ConfigurationException * */ public ServerConfiguration(File configurationURL) throws ConfigurationException { this(parseConfig(configurationURL)); _configFile = configurationURL; try { Signal sig = new sun.misc.Signal("HUP"); sun.misc.Signal.handle(sig, this); } catch (Exception e) { _logger.info("Signal HUP not supported for OS: " + System.getProperty("os.name")); // We're on something that doesn't handle SIGHUP, how sad, Windows. } } /** * Wraps the given Commons Configuration as a ServerConfiguration. * <p/> * Mainly used during testing and in locations where configuration is not * desired but the interface requires configuration. * <p/> * If the given configuration has VirtualHost configuration then * {@link #initialise()} must be called to perform the required setup. * <p/> * This has been made a two step process to allow the Plugin Manager and * Configuration Manager to be initialised in the Application Registry. * <p/> * If using this ServerConfiguration via an ApplicationRegistry there is no * need to explictly call {@link #initialise()} as this is done via the * {@link ApplicationRegistry#initialise()} method. * * @param conf */ public ServerConfiguration(org.apache.commons.configuration.Configuration conf) { _configuration = conf; } /** * Processes this configuration and setups any VirtualHosts defined in the * configuration. * <p/> * This has been separated from the constructor to allow the PluginManager * time to be created and provide plugins to the ConfigurationManager for * processing here. * <p/> * Called by {@link ApplicationRegistry#initialise()}. * <p/> * NOTE: A DEFAULT ApplicationRegistry must exist when using this method * or a new ApplicationRegistry will be created. * * @throws ConfigurationException */ public void initialise() throws ConfigurationException { setConfiguration("", _configuration); setupVirtualHosts(_configuration); } public String[] getElementsProcessed() { return new String[]{""}; } @Override public void validateConfiguration() throws ConfigurationException { // Support for security.jmx.access was removed when JMX access rights were incorporated into the main ACL. // This ensure that users remove the element from their configuration file. if (getListValue("security.jmx.access").size() > 0) { String message = "Validation error : security/jmx/access is no longer a supported element within the " + "configuration xml." + (_configFile == null ? "" : " Configuration file : " + _configFile); throw new ConfigurationException(message); } if (getListValue("security.jmx.principal-database").size() > 0) { String message = "Validation error : security/jmx/principal-database is no longer a supported element " + "within the configuration xml." + (_configFile == null ? "" : " Configuration file : " + _configFile); throw new ConfigurationException(message); } if (getListValue("security.principal-databases.principal-database(0).class").size() > 0) { String message = "Validation error : security/principal-databases is no longer supported within the " + "configuration xml." + (_configFile == null ? "" : " Configuration file : " + _configFile); throw new ConfigurationException(message); } } /* * Modified to enforce virtualhosts configuration in external file or main file, but not * both, as a fix for QPID-2360 and QPID-2361. */ @SuppressWarnings("unchecked") protected void setupVirtualHosts(org.apache.commons.configuration.Configuration conf) throws ConfigurationException { String[] vhostFiles = conf.getStringArray("virtualhosts"); org.apache.commons.configuration.Configuration vhostConfig = conf.subset("virtualhosts"); // Only one configuration mechanism allowed if (!(vhostFiles.length == 0) && !vhostConfig.subset("virtualhost").isEmpty()) { throw new ConfigurationException("Only one of external or embedded virtualhosts configuration allowed."); } // We can only have one vhosts XML file included if (vhostFiles.length > 1) { throw new ConfigurationException("Only one external virtualhosts configuration file allowed, " + "multiple filenames found."); } // Virtualhost configuration object org.apache.commons.configuration.Configuration vhostConfiguration = new HierarchicalConfiguration(); // Load from embedded configuration if possible if (!vhostConfig.subset("virtualhost").isEmpty()) { vhostConfiguration = vhostConfig; } else { // Load from the external configuration if possible for (String fileName : vhostFiles) { // Open the vhosts XML file and copy values from it to our config _vhostsFile = new File(fileName); if (!_vhostsFile.exists()) { throw new ConfigurationException("Virtualhosts file does not exist"); } vhostConfiguration = parseConfig(new File(fileName)); // save the default virtualhost name String defaultVirtualHost = vhostConfiguration.getString("default"); _configuration.setProperty("virtualhosts.default", defaultVirtualHost); } } // Now extract the virtual host names from the configuration object List hosts = vhostConfiguration.getList("virtualhost.name"); for (Object host : hosts) { String name = (String) host; // Add the virtual hosts to the server configuration VirtualHostConfiguration virtualhost = new VirtualHostConfiguration(name, vhostConfiguration.subset("virtualhost." + name)); _virtualHosts.put(virtualhost.getName(), virtualhost); } } private static void substituteEnvironmentVariables(org.apache.commons.configuration.Configuration conf) { for (Entry<String, String> var : envVarMap.entrySet()) { String val = System.getenv(var.getKey()); if (val != null) { conf.setProperty(var.getValue(), val); } } } private static org.apache.commons.configuration.Configuration parseConfig(File file) throws ConfigurationException { ConfigurationFactory factory = new ConfigurationFactory(); factory.setConfigurationFileName(file.getAbsolutePath()); org.apache.commons.configuration.Configuration conf = factory.getConfiguration(); Iterator<?> keys = conf.getKeys(); if (!keys.hasNext()) { conf = flatConfig(file); } substituteEnvironmentVariables(conf); return conf; } /** * Check the configuration file to see if status updates are enabled. * * @return true if status updates are enabled */ public boolean getStatusUpdatesEnabled() { // Retrieve the setting from configuration but default to on. String value = getStringValue(STATUS_UPDATES, DEFAULT_STATUS_UPDATES); return value.equalsIgnoreCase("on"); } /** * The currently defined {@see Locale} for this broker * * @return the configuration defined locale */ public Locale getLocale() { String localeString = getStringValue(ADVANCED_LOCALE); // Expecting locale of format langauge_country_variant // If the configuration does not have a defined locale use the JVM default if (localeString == null) { return Locale.getDefault(); } String[] parts = localeString.split("_"); Locale locale; switch (parts.length) { case 1: locale = new Locale(localeString); break; case 2: locale = new Locale(parts[0], parts[1]); break; default: StringBuilder variant = new StringBuilder(parts[2]); // If we have a variant such as the Java doc suggests for Spanish // Traditional_WIN we may end up with more than 3 parts on a // split with '_'. So we should recombine the variant. if (parts.length > 3) { for (int index = 3; index < parts.length; index++) { variant.append('_').append(parts[index]); } } locale = new Locale(parts[0], parts[1], variant.toString()); } return locale; } // Our configuration class needs to make the interpolate method // public so it can be called below from the config method. public static class MyConfiguration extends CompositeConfiguration { public String interpolate(String obj) { return super.interpolate(obj); } } public static org.apache.commons.configuration.Configuration flatConfig(File file) throws ConfigurationException { // We have to override the interpolate methods so that // interpolation takes place accross the entirety of the // composite configuration. Without doing this each // configuration object only interpolates variables defined // inside itself. final MyConfiguration conf = new MyConfiguration(); conf.addConfiguration(new SystemConfiguration() { protected String interpolate(String o) { return conf.interpolate(o); } }); conf.addConfiguration(new XMLConfiguration(file) { protected String interpolate(String o) { return conf.interpolate(o); } }); return conf; } public void handle(Signal arg0) { try { reparseConfigFileSecuritySections(); } catch (ConfigurationException e) { _logger.error("Could not reload configuration file security sections", e); } } public void reparseConfigFileSecuritySections() throws ConfigurationException { if (_configFile != null) { org.apache.commons.configuration.Configuration newConfig = parseConfig(_configFile); setConfiguration("", newConfig); ApplicationRegistry.getInstance().getSecurityManager().configureHostPlugins(this); // Reload virtualhosts from correct location org.apache.commons.configuration.Configuration newVhosts; if (_vhostsFile == null) { newVhosts = newConfig.subset("virtualhosts"); } else { newVhosts = parseConfig(_vhostsFile); } VirtualHostRegistry vhostRegistry = ApplicationRegistry.getInstance().getVirtualHostRegistry(); for (String hostName : _virtualHosts.keySet()) { VirtualHost vhost = vhostRegistry.getVirtualHost(hostName); Configuration vhostConfig = newVhosts.subset("virtualhost." + hostName); vhost.getConfiguration().setConfiguration("virtualhosts.virtualhost", vhostConfig); // XXX vhost.getSecurityManager().configureGlobalPlugins(this); vhost.getSecurityManager().configureHostPlugins(vhost.getConfiguration()); } _logger.warn(SECURITY_CONFIG_RELOADED); } } public String getQpidWork() { return System.getProperty(QPID_WORK, System.getProperty("java.io.tmpdir")); } public void setJMXManagementPort(int mport) { getConfig().setProperty("management.jmxport", mport); } public int getJMXManagementPort() { return getIntValue("management.jmxport", DEFAULT_JMXPORT); } public boolean getUseCustomRMISocketFactory() { return getBooleanValue(MGMT_CUSTOM_REGISTRY_SOCKET, true); } public boolean getPlatformMbeanserver() { return getBooleanValue("management.platform-mbeanserver", true); } public String[] getVirtualHosts() { return _virtualHosts.keySet().toArray(new String[_virtualHosts.size()]); } public String getPluginDirectory() { return getStringValue("plugin-directory"); } public String getCacheDirectory() { return getStringValue("cache-directory"); } public VirtualHostConfiguration getVirtualHostConfig(String name) { return _virtualHosts.get(name); } public int getFrameSize() { return getIntValue("advanced.framesize", DEFAULT_FRAME_SIZE); } public boolean getSynchedClocks() { return getBooleanValue("advanced.synced-clocks"); } public boolean getMsgAuth() { return getBooleanValue("security.msg-auth"); } public String getManagementKeyStorePath() { return getStringValue("management.ssl.keyStorePath"); } public boolean getManagementSSLEnabled() { return getBooleanValue("management.ssl.enabled", true); } public String getManagementKeyStorePassword() { return getStringValue("management.ssl.keyStorePassword"); } public boolean getQueueAutoRegister() { return getBooleanValue("queue.auto_register", true); } public boolean getManagementEnabled() { return getBooleanValue("management.enabled", true); } public void setManagementEnabled(boolean enabled) { getConfig().setProperty("management.enabled", enabled); } public int getHeartBeatDelay() { return getIntValue("heartbeat.delay", 0); } public double getHeartBeatTimeout() { return getDoubleValue("heartbeat.timeoutFactor", 2.0); } public long getMaximumMessageAge() { return getLongValue("maximumMessageAge"); } public long getMaximumMessageCount() { return getLongValue("maximumMessageCount"); } public long getMaximumQueueDepth() { return getLongValue("maximumQueueDepth"); } public long getMaximumMessageSize() { return getLongValue("maximumMessageSize"); } public long getMinimumAlertRepeatGap() { return getLongValue("minimumAlertRepeatGap"); } public long getCapacity() { return getLongValue("capacity"); } public long getFlowResumeCapacity() { return getLongValue("flowResumeCapacity", getCapacity()); } public int getConnectorProcessors() { return getIntValue("connector.processors", 4); } /** * Retrieve Port from Andes configurations(broker.xml). * * @return Port */ public List getPorts() { Integer port = AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_DEFAULT_CONNECTION_PORT); return Collections.singletonList(port); } public List getPortExclude010() { return getListValue("connector.non010port"); } public List getPortExclude091() { return getListValue("connector.non091port"); } public List getPortExclude09() { return getListValue("connector.non09port"); } public List getPortExclude08() { return getListValue("connector.non08port"); } /** * Retrieve bind address from Andes configurations(broker.xml). * * @return Bind address */ public String getBind() { return AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_BIND_ADDRESS); } public int getReceiveBufferSize() { return getIntValue("connector.socketReceiveBuffer", DEFAULT_SOCKET_BUFFER_SIZE); } public int getWriteBufferSize() { return getIntValue("connector.socketWriteBuffer", DEFAULT_SOCKET_BUFFER_SIZE); } public boolean getTcpNoDelay() { return getBooleanValue("connector.tcpNoDelay", true); } public boolean getEnableExecutorPool() { return getBooleanValue("advanced.filterchain[@enableExecutorPool]"); } public boolean getEnableSSL() { return (Boolean)AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_ENABLED); } public boolean getSSLOnly() { return (Boolean)AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_ENABLED) && !(Boolean)AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_DEFAULT_CONNECTION_ENABLED); } public boolean getMQTTSSLOnly() { return (Boolean) AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_MQTT_SSL_CONNECTION_ENABLED) && !(Boolean)AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_MQTT_DEFAULT_CONNECTION_ENABLED); } /** * Retrieve SSL Port from Andes configurations(broker.xml). * * @return SSL Port List */ public List getSSLPorts() { Integer sslPort = AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_PORT); return Collections.singletonList(sslPort); } public String getKeystorePath() { return ((JKSStore)AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_KEYSTORE)).getStoreLocation(); } public String getKeystorePassword() { return ((JKSStore)AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_KEYSTORE)).getPassword(); } public String getKeyStoreCertType() { return ((JKSStore)AndesConfigurationManager.readValue(AndesConfiguration.TRANSPORTS_AMQP_SSL_CONNECTION_KEYSTORE)).getStoreAlgorithm(); } public boolean getUseBiasedWrites() { return getBooleanValue("advanced.useWriteBiasedPool"); } public String getDefaultVirtualHost() { return getStringValue("virtualhosts.default"); } public void setHousekeepingExpiredMessageCheckPeriod(long value) { getConfig().setProperty("housekeeping.expiredMessageCheckPeriod", value); } public long getHousekeepingCheckPeriod() { return getLongValue("housekeeping.checkPeriod", getLongValue("housekeeping.expiredMessageCheckPeriod", DEFAULT_HOUSEKEEPING_PERIOD)); } public boolean isStatisticsGenerationBrokerEnabled() { return getConfig().getBoolean("statistics.generation.broker", false); } public boolean isStatisticsGenerationVirtualhostsEnabled() { return getConfig().getBoolean("statistics.generation.virtualhosts", false); } public boolean isStatisticsGenerationConnectionsEnabled() { return getConfig().getBoolean("statistics.generation.connections", false); } public long getStatisticsReportingPeriod() { return getConfig().getLong("statistics.reporting.period", 0L); } public boolean isStatisticsReportResetEnabled() { return getConfig().getBoolean("statistics.reporting.reset", false); } public int getMaxChannelCount() { return getIntValue("maximumChannelCount", 256); } }
apache-2.0
iMDT/katharsis-framework-j6
katharsis-core/src/main/java/io/katharsis/queryspec/QuerySpecBulkRelationshipRepository.java
677
package io.katharsis.queryspec; import java.io.Serializable; import java.util.Map; /** * {@code QuerySpecRelationshipRepository} implementation that provides additional support to bulk-request relations. */ public interface QuerySpecBulkRelationshipRepository<T, I extends Serializable, D, J extends Serializable> extends QuerySpecRelationshipRepository<T, I, D, J> { /** * Bulk request multiple targets at once. */ Map<I, D> findOneTargets(Iterable<I> sourceIds, String fieldName, QuerySpec querySpec); /** * Bulk request multiple targets at once. */ Map<I, Iterable<D>> findManyTargets(Iterable<I> sourceIds, String fieldName, QuerySpec querySpec); }
apache-2.0
andymw/sandsotrc
src/sand/client/gui/SandActionsGUI.java
32929
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sand.client.gui; import java.util.List; import java.util.UUID; import javax.swing.JFrame; import javax.swing.JOptionPane; import sand.client.CredentialTuple; import sand.client.SandClientManager; /** * * @author spencer */ public class SandActionsGUI extends javax.swing.JFrame { private SandClientManager manager; private SandClientGUI parentWindow; /** * Creates new form SandActionsGUI */ public SandActionsGUI(SandClientManager man, SandClientGUI gui, boolean offlineMode) { manager = man; parentWindow = gui; initComponents(); if(offlineMode) { goToOfflineMode(); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { addPanel = new javax.swing.JPanel(); addButton = new javax.swing.JButton(); txtserviceAdd = new javax.swing.JTextField(); txtusernameAdd = new javax.swing.JTextField(); txtpasswordAdd = new javax.swing.JTextField(); lblserviceAdd = new javax.swing.JLabel(); lblusernameAdd = new javax.swing.JLabel(); lblpasswordAdd = new javax.swing.JLabel(); lbldescriptionAdd = new javax.swing.JLabel(); txtdescriptionAdd = new javax.swing.JTextField(); lookupPanel = new javax.swing.JPanel(); txtserviceLookup = new javax.swing.JTextField(); lblserviceLookup = new javax.swing.JLabel(); lookupButton = new javax.swing.JButton(); lookupAllbutton = new javax.swing.JButton(); editPanel = new javax.swing.JPanel(); lblserviceEdit = new javax.swing.JLabel(); txtserviceEdit = new javax.swing.JTextField(); editButton = new javax.swing.JButton(); removePanel = new javax.swing.JPanel(); lblserviceRemove = new javax.swing.JLabel(); txtserviceRemove = new javax.swing.JTextField(); lblusernameRemove = new javax.swing.JLabel(); txtusernameRemove = new javax.swing.JTextField(); removeButton = new javax.swing.JButton(); removeAllButton = new javax.swing.JButton(); menuBar = new javax.swing.JMenuBar(); fileMenu = new javax.swing.JMenu(); fileMenuViewLogs = new javax.swing.JMenuItem(); fileMenuLogoff = new javax.swing.JMenuItem(); userMenu = new javax.swing.JMenu(); userMenuEditInfo = new javax.swing.JMenuItem(); userMenuRemoveAccount = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); addPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Add Credential"))); addButton.setText("Add"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); lblserviceAdd.setText("Service"); lblusernameAdd.setText("Username"); lblpasswordAdd.setText("Password"); lbldescriptionAdd.setText("Description"); javax.swing.GroupLayout addPanelLayout = new javax.swing.GroupLayout(addPanel); addPanel.setLayout(addPanelLayout); addPanelLayout.setHorizontalGroup( addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(addPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(addPanelLayout.createSequentialGroup() .addComponent(lbldescriptionAdd) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtdescriptionAdd)) .addGroup(addPanelLayout.createSequentialGroup() .addComponent(lblserviceAdd) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtserviceAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblusernameAdd) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtusernameAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(addPanelLayout.createSequentialGroup() .addComponent(lblpasswordAdd) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtpasswordAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); addPanelLayout.setVerticalGroup( addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(addPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtserviceAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtusernameAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtpasswordAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblserviceAdd) .addComponent(lblusernameAdd) .addComponent(lblpasswordAdd)) .addGap(18, 18, 18) .addGroup(addPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbldescriptionAdd) .addComponent(txtdescriptionAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(addButton)) .addContainerGap(20, Short.MAX_VALUE)) ); lookupPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Lookup Credential")); lblserviceLookup.setText("Service"); lookupButton.setText("Lookup"); lookupButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lookupButtonActionPerformed(evt); } }); lookupAllbutton.setText("Lookup all Credentials"); lookupAllbutton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lookupAllbuttonActionPerformed(evt); } }); javax.swing.GroupLayout lookupPanelLayout = new javax.swing.GroupLayout(lookupPanel); lookupPanel.setLayout(lookupPanelLayout); lookupPanelLayout.setHorizontalGroup( lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(lookupPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(lookupPanelLayout.createSequentialGroup() .addComponent(lblserviceLookup) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtserviceLookup)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, lookupPanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lookupButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lookupAllbutton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) ); lookupPanelLayout.setVerticalGroup( lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(lookupPanelLayout.createSequentialGroup() .addGap(23, 23, 23) .addGroup(lookupPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtserviceLookup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblserviceLookup)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lookupButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE) .addComponent(lookupAllbutton) .addContainerGap()) ); editPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Edit Credential")); lblserviceEdit.setText("Service"); editButton.setText("Edit"); editButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { editButtonActionPerformed(evt); } }); javax.swing.GroupLayout editPanelLayout = new javax.swing.GroupLayout(editPanel); editPanel.setLayout(editPanelLayout); editPanelLayout.setHorizontalGroup( editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(editPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(editButton, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(editPanelLayout.createSequentialGroup() .addComponent(lblserviceEdit) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtserviceEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)) ); editPanelLayout.setVerticalGroup( editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(editPanelLayout.createSequentialGroup() .addGap(24, 24, 24) .addGroup(editPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblserviceEdit) .addComponent(txtserviceEdit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editButton) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); removePanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Remove Credential")); lblserviceRemove.setText("Service"); lblusernameRemove.setText("Username"); removeButton.setText("Remove"); removeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeButtonActionPerformed(evt); } }); removeAllButton.setText("Remove All Credentials"); removeAllButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeAllButtonActionPerformed(evt); } }); javax.swing.GroupLayout removePanelLayout = new javax.swing.GroupLayout(removePanel); removePanel.setLayout(removePanelLayout); removePanelLayout.setHorizontalGroup( removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(removePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(removePanelLayout.createSequentialGroup() .addComponent(lblserviceRemove) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtserviceRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lblusernameRemove) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtusernameRemove, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, removePanelLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(removeButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(removeAllButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) ); removePanelLayout.setVerticalGroup( removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(removePanelLayout.createSequentialGroup() .addContainerGap() .addGroup(removePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblserviceRemove) .addComponent(txtserviceRemove, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lblusernameRemove) .addComponent(txtusernameRemove, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removeButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE) .addComponent(removeAllButton) .addContainerGap()) ); fileMenu.setText("File"); fileMenuViewLogs.setText("View Logs"); fileMenuViewLogs.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fileMenuViewLogsActionPerformed(evt); } }); fileMenu.add(fileMenuViewLogs); fileMenuLogoff.setText("Logout"); fileMenuLogoff.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fileMenuLogoffActionPerformed(evt); } }); fileMenu.add(fileMenuLogoff); menuBar.add(fileMenu); userMenu.setText("User"); userMenuEditInfo.setText("Edit User Info"); userMenuEditInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { userMenuEditInfoActionPerformed(evt); } }); userMenu.add(userMenuEditInfo); userMenuRemoveAccount.setText("Delete User Account"); userMenuRemoveAccount.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { userMenuRemoveAccountActionPerformed(evt); } }); userMenu.add(userMenuRemoveAccount); menuBar.add(userMenu); setJMenuBar(menuBar); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(removePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(lookupPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(editPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(addPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(lookupPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(editPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed // TODO add your handling code here: String service = txtserviceAdd.getText(); String user = txtusernameAdd.getText(); String pass = txtpasswordAdd.getText(); String desc = txtdescriptionAdd.getText(); if(service.equals("") || user.equals("") || pass.equals("")) { // These are required System.out.println("Service, Username, AND Password are required"); JOptionPane.showMessageDialog(this, "Service, Username, AND Password are required", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); return; } else { System.out.println("Adding credential..."); UUID uuid = manager.addCredential(service, user, pass, desc); if (uuid == null) { System.out.println("Add credential FAILED!"); JOptionPane.showMessageDialog(this, "Add credential FAILED.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); } else { System.out.println("Credential added.");//was added with ID " + uuid.toString()); clearFields(1); JOptionPane.showMessageDialog(this, "Credential added.", SandClientGUI.popUpTitle, JOptionPane.INFORMATION_MESSAGE); } } }//GEN-LAST:event_addButtonActionPerformed private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed int toEdit = -1; String service = txtserviceEdit.getText(); if(service.equals("")) { System.out.println("Service is required"); JOptionPane.showMessageDialog(this, "Service is required.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); return; } else { List<CredentialTuple> creds = manager.lookupMatching(service, null); if (creds == null || creds.isEmpty()) { System.out.println("Credentials of hostname " + service + " not found"); JOptionPane.showMessageDialog(this, "Credentials of hostname " + service + " not found", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); return; } else if (creds.size() == 1) { // Only one to edit toEdit = 0; } else { // multiple edit Object[] possibilities = new Object[creds.size()]; int i; for (i = 0; i < creds.size(); i++) { possibilities[i] = i+1 + ") " + creds.get(i).username + " " + creds.get(i).password; } String response = (String)JOptionPane.showInputDialog( this, "Select the credential you would like to edit:", "Credential Select", JOptionPane.PLAIN_MESSAGE, null, possibilities, ""); if (response != null && response.length() > 0) { response = response.substring(0,1); try { toEdit = (Integer.parseInt(response)) - 1; } catch (NumberFormatException e) { toEdit = 0; // don't know what else to do } } else { // cancel was hit or nothing was selected return; } } // new edit window load with data save a new one and remove the old EditCredGUI frame = new EditCredGUI(manager, creds.get(toEdit)); frame.setTitle("S.A.N.D."); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); clearFields(3); } }//GEN-LAST:event_editButtonActionPerformed private void lookupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lookupButtonActionPerformed // TODO add your handling code here: String service = txtserviceLookup.getText(); if(service.equals("")) { System.out.println("Service is required"); JOptionPane.showMessageDialog(this, "Service is required.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); return; } else { List<CredentialTuple> creds = manager.lookupMatching(service, null); if (creds == null || creds.size() == 0) { System.out.println("Credentials of hostname " + service + " not found"); JOptionPane.showMessageDialog(this, "Credentials of hostname " + service + " not found", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); return; } clearFields(2); LookupTableGUI frame = new LookupTableGUI(creds); frame.setTitle("S.A.N.D."); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); } }//GEN-LAST:event_lookupButtonActionPerformed private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeButtonActionPerformed int toRemove = -1; String service = txtserviceRemove.getText(); String user = txtusernameRemove.getText(); if(service.equals("") || user.equals("")) { //System.out.println("Service AND Username is required"); JOptionPane.showMessageDialog(this, "Service AND Username is required", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); return; } else { List<CredentialTuple> creds = manager.lookupMatching(service, user); if (creds == null || creds.isEmpty()) { //System.out.println("Credentials of hostname " + service + " not found"); JOptionPane.showMessageDialog(this, "Credentials of hostname " + service + " not found", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); return; } else if (creds.size() == 1) { // Only one to edit toRemove = 0; } else { // multiple available to remove Object[] possibilities = new Object[creds.size()]; int i; for (i = 0; i < creds.size(); i++) { possibilities[i] = i+1 + ") " + creds.get(i).username + " " + creds.get(i).password + " " + creds.get(i).description; } String response = (String)JOptionPane.showInputDialog( this, "Select the credential you would like to delete:", "Credential Select", JOptionPane.PLAIN_MESSAGE, null, possibilities, ""); if (response != null && response.length() > 0) { response = response.substring(0,1); try { toRemove = (Integer.parseInt(response)) - 1; } catch (NumberFormatException e) { toRemove = 0; // don't know what else to do } } else { // cancel was hit or nothing was selected return; } } CredentialTuple cred = creds.get(toRemove); boolean success = manager.removeCredential(cred.getUUID()); if(success) { clearFields(4); JOptionPane.showMessageDialog(this, "Removal Succeeded", SandClientGUI.popUpTitle, JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Remove credential failed.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_removeButtonActionPerformed private void fileMenuViewLogsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuViewLogsActionPerformed int numLogs = 20; try { String s = (String)JOptionPane.showInputDialog(this,"How many log entries back would you like to view?", "Logs", JOptionPane.PLAIN_MESSAGE, null, null,""); numLogs = Integer.parseInt(s); } catch (NumberFormatException e) { JOptionPane.showMessageDialog(this, "Must enter a valid number. Default to 20 log entries.", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); numLogs = 20; } List<String> logs = manager.getUserLogs(numLogs); LogsGUI gui = new LogsGUI(logs); gui.setTitle("S.A.N.D."); gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); gui.pack(); gui.setVisible(true); }//GEN-LAST:event_fileMenuViewLogsActionPerformed private void fileMenuLogoffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileMenuLogoffActionPerformed logout(); }//GEN-LAST:event_fileMenuLogoffActionPerformed private void userMenuEditInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userMenuEditInfoActionPerformed EditUserInfoGUI frame = new EditUserInfoGUI(manager); frame.setTitle("S.A.N.D."); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); }//GEN-LAST:event_userMenuEditInfoActionPerformed private void lookupAllbuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lookupAllbuttonActionPerformed List<CredentialTuple> creds = manager.lookupAll(); if (creds == null || creds.isEmpty()) { JOptionPane.showMessageDialog(this, "No Credentials Found", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); return; } else { LookupTableGUI frame = new LookupTableGUI(creds); frame.setTitle("S.A.N.D."); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); } }//GEN-LAST:event_lookupAllbuttonActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing boolean shouldLogout = logout(); if(!shouldLogout) { return; } }//GEN-LAST:event_formWindowClosing private void removeAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllButtonActionPerformed int selectedOption = JOptionPane.showConfirmDialog(null, "Are you sure you want to remove ALL Credentials?", "Remove all?", JOptionPane.YES_NO_OPTION); if (selectedOption == JOptionPane.YES_OPTION) { boolean success = manager.removeCredential(null,null,true); if(success) { JOptionPane.showMessageDialog(this, "Credentials all removed", SandClientGUI.popUpTitle, JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Not all credentials could be removed", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); } } else { // Do Nothing } }//GEN-LAST:event_removeAllButtonActionPerformed private void userMenuRemoveAccountActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userMenuRemoveAccountActionPerformed int selectedOption = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete your account? This will erase all credentials and remove your account.", "Delete Account?", JOptionPane.YES_NO_OPTION); if (selectedOption == JOptionPane.YES_OPTION) { boolean success = manager.deleteAccount(); if (success) { JOptionPane.showMessageDialog(this, "Account deleted", SandClientGUI.popUpTitle, JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(this, "Account deletion failed", SandClientGUI.popUpTitle, JOptionPane.ERROR_MESSAGE); } } }//GEN-LAST:event_userMenuRemoveAccountActionPerformed private boolean logout() { int selectedOption = JOptionPane.showConfirmDialog(null, "Before logging out please close all information windows. \nAre you sure you want to logout?", "Logout?", JOptionPane.YES_NO_OPTION); if (selectedOption == JOptionPane.YES_OPTION) { try{ manager.logout(); } catch (Exception e) { e.printStackTrace(); return false; } this.dispose(); parentWindow.setVisible(true); return true; } else { this.setVisible(true); return false; } } private void goToOfflineMode() { addPanel.setVisible(false); editPanel.setVisible(false); removePanel.setVisible(false); userMenu.setVisible(false); fileMenuViewLogs.setVisible((false)); } /** * * @param mode * 0 runs all clear * 1 - add * 2 - lookup * 3 - edit * 4 - remove */ private void clearFields(int mode) { if(mode == 1 || mode <1) { txtserviceAdd.setText(""); txtusernameAdd.setText(""); txtpasswordAdd.setText(""); txtdescriptionAdd.setText(""); } if(mode == 2 || mode <1) { txtserviceLookup.setText(""); } if(mode == 3 || mode <1){ txtserviceEdit.setText(""); } if(mode == 4 || mode <1) { txtserviceRemove.setText(""); txtusernameRemove.setText(""); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(SandActionsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(SandActionsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(SandActionsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(SandActionsGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new SandActionsGUI(null,null,false).setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addButton; private javax.swing.JPanel addPanel; private javax.swing.JButton editButton; private javax.swing.JPanel editPanel; private javax.swing.JMenu fileMenu; private javax.swing.JMenuItem fileMenuLogoff; private javax.swing.JMenuItem fileMenuViewLogs; private javax.swing.JLabel lbldescriptionAdd; private javax.swing.JLabel lblpasswordAdd; private javax.swing.JLabel lblserviceAdd; private javax.swing.JLabel lblserviceEdit; private javax.swing.JLabel lblserviceLookup; private javax.swing.JLabel lblserviceRemove; private javax.swing.JLabel lblusernameAdd; private javax.swing.JLabel lblusernameRemove; private javax.swing.JButton lookupAllbutton; private javax.swing.JButton lookupButton; private javax.swing.JPanel lookupPanel; private javax.swing.JMenuBar menuBar; private javax.swing.JButton removeAllButton; private javax.swing.JButton removeButton; private javax.swing.JPanel removePanel; private javax.swing.JTextField txtdescriptionAdd; private javax.swing.JTextField txtpasswordAdd; private javax.swing.JTextField txtserviceAdd; private javax.swing.JTextField txtserviceEdit; private javax.swing.JTextField txtserviceLookup; private javax.swing.JTextField txtserviceRemove; private javax.swing.JTextField txtusernameAdd; private javax.swing.JTextField txtusernameRemove; private javax.swing.JMenu userMenu; private javax.swing.JMenuItem userMenuEditInfo; private javax.swing.JMenuItem userMenuRemoveAccount; // End of variables declaration//GEN-END:variables }
apache-2.0
unipop-graph/unipop
unipop-rest/src/org/unipop/rest/RestController.java
10217
package org.unipop.rest; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.exceptions.UnirestException; import com.mashape.unirest.request.BaseRequest; import org.apache.tinkerpop.gremlin.structure.Edge; import org.apache.tinkerpop.gremlin.structure.Element; import org.apache.tinkerpop.gremlin.structure.Vertex; import org.apache.tinkerpop.gremlin.util.iterator.EmptyIterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.unipop.query.UniQuery; import org.unipop.query.controller.SimpleController; import org.unipop.query.mutation.AddEdgeQuery; import org.unipop.query.mutation.AddVertexQuery; import org.unipop.query.mutation.PropertyQuery; import org.unipop.query.mutation.RemoveQuery; import org.unipop.query.search.DeferredVertexQuery; import org.unipop.query.search.SearchQuery; import org.unipop.query.search.SearchVertexQuery; import org.unipop.schema.element.ElementSchema; import org.unipop.schema.reference.DeferredVertex; import org.unipop.structure.traversalfilter.TraversalFilter; import org.unipop.structure.UniEdge; import org.unipop.structure.UniElement; import org.unipop.structure.UniGraph; import org.unipop.structure.UniVertex; import java.util.*; import java.util.function.*; import java.util.stream.Collector; import java.util.stream.Collectors; /** * Created by sbarzilay on 24/11/16. */ public class RestController implements SimpleController { private static final Logger logger = LoggerFactory.getLogger(RestController.class); private final UniGraph graph; private Set<? extends RestVertexSchema> vertexSchemas = new HashSet<>(); private Set<? extends RestEdgeSchema> edgeSchemas = new HashSet<>(); TraversalFilter traversalFilter; public RestController(UniGraph graph, Set<RestSchema> schemas, TraversalFilter traversalFilter) { this.traversalFilter = traversalFilter; this.graph = graph; Set<RestSchema> documentSchemas = collectSchemas(schemas); this.vertexSchemas = documentSchemas.stream().filter(schema -> schema instanceof RestVertexSchema) .map(schema -> ((RestVertexSchema) schema)).collect(Collectors.toSet()); this.edgeSchemas = documentSchemas.stream().filter(schema -> schema instanceof RestEdgeSchema) .map(schema -> ((RestEdgeSchema) schema)).collect(Collectors.toSet()); logger.debug("Instantiated RestController: {}", this); } private Set<RestSchema> collectSchemas(Set<? extends ElementSchema> schemas) { Set<RestSchema> docSchemas = new HashSet<>(); schemas.forEach(schema -> { if (schema instanceof RestSchema) { docSchemas.add((RestSchema) schema); Set<RestSchema> childSchemas = collectSchemas(schema.getChildSchemas()); docSchemas.addAll(childSchemas); } }); return docSchemas; } @Override public Iterator<Edge> search(SearchVertexQuery uniQuery) { RestCollector<RestEdgeSchema, BaseRequest, Edge> collector = new RestCollector<>(schema -> schema.getSearch(uniQuery), (schema, result) -> schema.parseResults(result, uniQuery)); Map<RestEdgeSchema, BaseRequest> schemas = edgeSchemas.stream() .filter(schema -> this.traversalFilter.filter(schema, uniQuery.getTraversal())).collect(collector); return search(uniQuery, schemas, collector); } @Override public <E extends Element> Iterator<E> search(SearchQuery<E> uniQuery) { RestCollector<RestSchema<E>, BaseRequest, E> collector = new RestCollector<>(schema -> schema.getSearch(uniQuery), (schema, result) -> schema.parseResults(result, uniQuery)); Set<? extends RestSchema<E>> schemas = getSchemas(uniQuery.getReturnType()); Map<RestSchema<E>, BaseRequest> collect = schemas.stream() .filter(schema -> this.traversalFilter.filter(schema,uniQuery.getTraversal())).collect(collector); return search(uniQuery, collect, collector); } @Override public void fetchProperties(DeferredVertexQuery uniQuery) { RestCollector<RestVertexSchema, BaseRequest, Vertex> collector = new RestCollector<>(schema -> schema.getSearch(uniQuery), (schema, result) -> schema.parseResults(result, uniQuery)); Map<RestVertexSchema, BaseRequest> schemas = vertexSchemas.stream() .filter(schema -> this.traversalFilter.filter(schema,uniQuery.getTraversal())).collect(collector); Iterator<Vertex> iterator = search(uniQuery, schemas, collector); Map<Object, DeferredVertex> vertexMap = uniQuery.getVertices().stream() .collect(Collectors.toMap(UniElement::id, Function.identity(), (a, b) -> a)); iterator.forEachRemaining(newVertex -> { DeferredVertex deferredVertex = vertexMap.get(newVertex.id()); if (deferredVertex != null) deferredVertex.loadProperties(newVertex); }); } @Override public <E extends Element> void remove(RemoveQuery<E> uniQuery) { uniQuery.getElements().forEach(element -> { Set<? extends RestSchema<Element>> schemas = getSchemas(element.getClass()); for (RestSchema<Element> schema : schemas) { BaseRequest delete = schema.delete(element); try { HttpResponse<JsonNode> jsonNodeHttpResponse = delete.asJson(); if(jsonNodeHttpResponse.getStatus() == 200) break; } catch (UnirestException e) { e.printStackTrace(); } } }); } @Override public Vertex addVertex(AddVertexQuery uniQuery) { UniVertex vertex = new UniVertex(uniQuery.getProperties(), null, graph); for (RestVertexSchema vertexSchema : vertexSchemas) { try { BaseRequest baseRequest = vertexSchema.addElement(vertex); if (baseRequest == null) return vertex; baseRequest.asJson(); } catch (UnirestException e) { e.printStackTrace(); } catch (NoSuchElementException e) { continue; } } return vertex; } @Override public <E extends Element> void property(PropertyQuery<E> uniQuery) { E element = uniQuery.getElement(); Set<? extends RestSchema<E>> schemas = getSchemas(element.getClass()); for (RestSchema<E> schema : schemas) { try { BaseRequest baseRequest = schema.addElement(element); if (baseRequest == null) return; baseRequest.asJson(); } catch (UnirestException e) { e.printStackTrace(); } catch (NoSuchElementException e) { continue; } } } private <E extends Element> Set<? extends RestSchema<E>> getSchemas(Class elementClass) { if (Vertex.class.isAssignableFrom(elementClass)) return (Set<? extends RestSchema<E>>) vertexSchemas; else return (Set<? extends RestSchema<E>>) edgeSchemas; } @Override public Edge addEdge(AddEdgeQuery uniQuery) { UniEdge edge = new UniEdge(uniQuery.getProperties(), uniQuery.getOutVertex(), uniQuery.getInVertex(), null, graph); for (RestEdgeSchema edgeSchema : edgeSchemas) { try { BaseRequest baseRequest = edgeSchema.addElement(edge); if (baseRequest == null) return edge; baseRequest.asJson(); } catch (UnirestException e) { e.printStackTrace(); } catch (NoSuchElementException e) { continue; } } return edge; } private <E extends Element, S extends RestSchema<E>> Iterator<E> search(UniQuery query, Map<S, BaseRequest> schemas, RestCollector<S, BaseRequest, E> collector) { if (schemas.size() == 0) return EmptyIterator.instance(); logger.debug("Preparing search. Schemas: {}", schemas); List<HttpResponse<JsonNode>> results = schemas.values().stream().map(request -> { try { return request.asJson(); } catch (UnirestException e) { throw new RuntimeException("request: " + request.toString() + " unsuccessful"); } }).collect(Collectors.toList()); Iterator<S> schemaIterator = schemas.keySet().iterator(); return results.stream().flatMap(result -> collector.parse.apply(schemaIterator.next(), result).stream()).iterator(); } public class RestCollector<K, V, R> implements Collector<K, Map<K, V>, Map<K, V>> { private final Function<? super K, ? extends V> valueMapper; private final BiFunction<? super K, HttpResponse<JsonNode>, ? extends Collection<R>> parse; private RestCollector(Function<? super K, ? extends V> valueMapper, BiFunction<? super K, HttpResponse<JsonNode>, Collection<R>> parse) { this.valueMapper = valueMapper; this.parse = parse; } @Override public Supplier<Map<K, V>> supplier() { return HashMap<K, V>::new; } @Override public BiConsumer<Map<K, V>, K> accumulator() { return (map, t) -> { V value = valueMapper.apply(t); if (value != null) map.put(t, value); }; } @Override public BinaryOperator<Map<K, V>> combiner() { return (map1, map2) -> { map1.putAll(map2); return map1; }; } @Override public Function<Map<K, V>, Map<K, V>> finisher() { return m -> m; } @Override public Set<Collector.Characteristics> characteristics() { return EnumSet.of(Collector.Characteristics.IDENTITY_FINISH); } } }
apache-2.0
vespa-engine/vespa
vespajlib/src/main/java/com/yahoo/concurrent/Timer.java
707
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.concurrent; /** * This interface wraps access to some timer that can be used to measure elapsed time, in milliseconds. This * abstraction allows for unit testing the behavior of time-based constructs. * * @author Simon Thoresen Hult */ public interface Timer { /** * Returns the current value of some arbitrary timer, in milliseconds. This method can only be used to measure * elapsed time and is not related to any other notion of system or wall-clock time. * * @return The current value of the timer, in milliseconds. */ long milliTime(); }
apache-2.0
CompendiumNG/fxpoc
src/main/java/org/jrebirth/sample/service/SampleService.java
1117
package org.jrebirth.sample.service; import org.jrebirth.core.service.DefaultService; import org.jrebirth.core.wave.Wave; import org.jrebirth.core.wave.WaveTypeBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class <strong>SampleService</strong>. * * @author */ public final class SampleService extends DefaultService { /** Perform something. */ public static final WaveTypeBase DO_SOMETHING = WaveTypeBase.build("SOMETHING"); /** Wave type to return when something was done. */ public static final WaveTypeBase RE_SOMETHING_DONE = WaveTypeBase.build("SOMETHING_DONE"); /** The class logger. */ private static final Logger LOGGER = LoggerFactory.getLogger(SampleService.class); /** * {@inheritDoc} */ public void initService() { // Define the service method registerCallback(DO_SOMETHING, RE_SOMETHING_DONE); } /** * Do something. * * @param wave the source wave */ public void something(final Wave wave) { LOGGER.trace("Do Something."); // Put code to do it ! } }
apache-2.0
oehme/analysing-gradle-performance
my-app/src/main/java/org/gradle/test/performance/mediummonolithicjavaproject/p156/Production3127.java
2048
package org.gradle.test.performance.mediummonolithicjavaproject.p156; import org.gradle.test.performance.mediummonolithicjavaproject.p155.Production3118; public class Production3127 { private Production3118 property0; public Production3118 getProperty0() { return property0; } public void setProperty0(Production3118 value) { property0 = value; } private Production3122 property1; public Production3122 getProperty1() { return property1; } public void setProperty1(Production3122 value) { property1 = value; } private Production3126 property2; public Production3126 getProperty2() { return property2; } public void setProperty2(Production3126 value) { property2 = value; } private String property3; public String getProperty3() { return property3; } public void setProperty3(String value) { property3 = value; } private String property4; public String getProperty4() { return property4; } public void setProperty4(String value) { property4 = value; } private String property5; public String getProperty5() { return property5; } public void setProperty5(String value) { property5 = value; } private String property6; public String getProperty6() { return property6; } public void setProperty6(String value) { property6 = value; } private String property7; public String getProperty7() { return property7; } public void setProperty7(String value) { property7 = value; } private String property8; public String getProperty8() { return property8; } public void setProperty8(String value) { property8 = value; } private String property9; public String getProperty9() { return property9; } public void setProperty9(String value) { property9 = value; } }
apache-2.0
sequenceiq/cloudbreak
core/src/main/java/com/sequenceiq/cloudbreak/core/flow2/cluster/downscale/ClusterDownscaleState.java
694
package com.sequenceiq.cloudbreak.core.flow2.cluster.downscale; import com.sequenceiq.cloudbreak.core.flow2.FlowState; import com.sequenceiq.cloudbreak.core.flow2.RestartAction; import com.sequenceiq.cloudbreak.core.flow2.restart.FillInMemoryStateStoreRestartAction; enum ClusterDownscaleState implements FlowState { INIT_STATE, COLLECT_CANDIDATES_STATE, DECOMMISSION_STATE, UPDATE_INSTANCE_METADATA_STATE, CLUSTER_DOWNSCALE_FAILED_STATE, FINAL_STATE; private Class<? extends RestartAction> restartAction = FillInMemoryStateStoreRestartAction.class; @Override public Class<? extends RestartAction> restartAction() { return restartAction; } }
apache-2.0
julius5/Ejercicios
ejercicios/src/ejercicio32/ejercicio32.java
2433
package ejercicio32; import java.util.Scanner; /** * Ejercicio 32: Hacer un programa que nos permita introducir un numero por * teclado y sobre el se realicen las siguientes operaciones: comprobar si es * primo, hallar su factorial o imprimir su tabla de multiplicar. * * @author meny * @since 13/05/2015 * @ver 1.0 */ public class ejercicio32 { public static void main(String[] args) { Scanner escaner = new Scanner(System.in); //--- Variables int a = 0, n = 0; int x; int Resultado, y = 0; double factorial = 0; System.out.println("Introduce un numero:"); n = escaner.nextInt(); System.out.println("\n"); System.out.println("Que deseas hacer? \n 1) Comprobar si es Primo \n " + "2) Hallar su Factorial \n 3) Imprimir tabla de multiplicar"); x = escaner.nextInt(); System.out.println(""); switch (x) { case 1: { if (n >= 1) { for (int i = 1; i < (n + 1); i++) { if (n % i == 0) { a++; } } if (a != 2) { System.out.println("No es Primo"); } else { System.out.println("Si es Primo"); } } else { System.out.println("El numero no puede ser procesado"); } break; } case 2: { factorial = n; for (int i = n; i > 2; i--) { factorial = factorial * (i - 1); } System.out.println("El Factorial de "+n+" es: " + factorial); break; } case 3: { if (n <= 10) { for (int i = 0; i <= 10; i++) { Resultado = n * y; System.out.println(n + " x " + y + " = " + Resultado); y++; } } else { System.out.println("El numero introducido es mayor que 10"); } break; } default: System.out.println("Opcion invalida"); } } }
apache-2.0
gonmarques/commons-collections
src/test/java/org/apache/commons/collections4/map/UnmodifiableMapTest.java
3163
/* * 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.commons.collections4.map; import java.util.HashMap; import java.util.Map; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.Unmodifiable; /** * Extension of {@link AbstractMapTest} for exercising the * {@link UnmodifiableMap} implementation. * * @since 3.0 * @version $Id$ */ public class UnmodifiableMapTest<K, V> extends AbstractIterableMapTest<K, V> { public UnmodifiableMapTest(final String testName) { super(testName); } //------------------------------------------------------------------- @Override public IterableMap<K, V> makeObject() { return (IterableMap<K, V>) UnmodifiableMap.unmodifiableMap(new HashMap<K, V>()); } @Override public boolean isPutChangeSupported() { return false; } @Override public boolean isPutAddSupported() { return false; } @Override public boolean isRemoveSupported() { return false; } @Override public IterableMap<K, V> makeFullMap() { final Map<K, V> m = new HashMap<K, V>(); addSampleMappings(m); return (IterableMap<K, V>) UnmodifiableMap.unmodifiableMap(m); } //----------------------------------------------------------------------- public void testUnmodifiable() { assertTrue(makeObject() instanceof Unmodifiable); assertTrue(makeFullMap() instanceof Unmodifiable); } public void testDecorateFactory() { final Map<K, V> map = makeFullMap(); assertSame(map, UnmodifiableMap.unmodifiableMap(map)); try { UnmodifiableMap.unmodifiableMap(null); fail(); } catch (final IllegalArgumentException ex) {} } //----------------------------------------------------------------------- @Override public String getCompatibilityVersion() { return "4"; } // public void testCreate() throws Exception { // resetEmpty(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableMap.emptyCollection.version4.obj"); // resetFull(); // writeExternalFormToDisk( // (java.io.Serializable) map, // "src/test/resources/data/test/UnmodifiableMap.fullCollection.version4.obj"); // } }
apache-2.0
datazuul/ion-cms-maven
backoffice/src/main/java/org/nextime/ion/backoffice/messageBoard/MessageBoard.java
1784
package org.nextime.ion.backoffice.messageBoard; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collections; import java.util.Vector; import javax.servlet.http.HttpServlet; public class MessageBoard implements Serializable { private Vector messages; private static MessageBoard instance; private static String storePath; public Vector getMessages() { Collections.sort(messages); return messages; } public void addMessage(Message m) { messages.add(m); store(); } public void removeMessage(Message m) { messages.remove(m); store(); } private MessageBoard() { messages = new Vector(); } public static MessageBoard getInstance() { if (instance == null) { try { FileInputStream fis = new FileInputStream(storePath); ObjectInputStream ois = new ObjectInputStream(fis); instance = (MessageBoard) ois.readObject(); } catch (Exception e) { instance = new MessageBoard(); e.printStackTrace(); } } return instance; } protected static void init(HttpServlet servlet) { storePath = servlet.getServletContext().getRealPath( "/WEB-INF/messageBoard/store"); } private void store() { try { FileOutputStream fos = new FileOutputStream(storePath); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(this); } catch (Exception e) { e.printStackTrace(); } } }
apache-2.0
alibaba/nacos
istio/src/main/java/com/alibaba/nacos/istio/xds/NacosXdsService.java
8564
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * 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.alibaba.nacos.istio.xds; import com.alibaba.nacos.istio.api.ApiGenerator; import com.alibaba.nacos.istio.api.ApiGeneratorFactory; import com.alibaba.nacos.istio.common.*; import com.alibaba.nacos.istio.misc.Loggers; import com.alibaba.nacos.istio.util.NonceGenerator; import com.google.protobuf.Any; import io.envoyproxy.envoy.service.discovery.v3.AggregatedDiscoveryServiceGrpc; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; import io.grpc.stub.StreamObserver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import static com.alibaba.nacos.istio.api.ApiConstants.MESH_CONFIG_PROTO_PACKAGE; import static com.alibaba.nacos.istio.api.ApiConstants.SERVICE_ENTRY_PROTO_PACKAGE; /** * @author special.fy */ @Service public class NacosXdsService extends AggregatedDiscoveryServiceGrpc.AggregatedDiscoveryServiceImplBase { private final Map<String, AbstractConnection<DiscoveryResponse>> connections = new ConcurrentHashMap<>(16); public boolean hasClientConnection() { return connections.size() != 0; } @Autowired ApiGeneratorFactory apiGeneratorFactory; @Autowired NacosResourceManager resourceManager; @Override public StreamObserver<DiscoveryRequest> streamAggregatedResources(StreamObserver<DiscoveryResponse> responseObserver) { // TODO add authN // Init snapshot of nacos service info. resourceManager.initResourceSnapshot(); AbstractConnection<DiscoveryResponse> newConnection = new XdsConnection(responseObserver); return new StreamObserver<DiscoveryRequest>() { private boolean initRequest = true; @Override public void onNext(DiscoveryRequest discoveryRequest) { // init connection if (initRequest) { newConnection.setConnectionId(discoveryRequest.getNode().getId()); connections.put(newConnection.getConnectionId(), newConnection); initRequest = false; } process(discoveryRequest, newConnection); } @Override public void onError(Throwable throwable) { Loggers.MAIN.error("xds: {} stream error.", newConnection.getConnectionId(), throwable); clear(); } @Override public void onCompleted() { Loggers.MAIN.info("xds: {} stream close.", newConnection.getConnectionId()); responseObserver.onCompleted(); clear(); } private void clear() { connections.remove(newConnection.getConnectionId()); } }; } public void process(DiscoveryRequest discoveryRequest, AbstractConnection<DiscoveryResponse> connection) { if (!shouldPush(discoveryRequest, connection)) { return; } DiscoveryResponse response = buildDiscoveryResponse(discoveryRequest.getTypeUrl(), resourceManager.getResourceSnapshot()); connection.push(response, connection.getWatchedStatusByType(discoveryRequest.getTypeUrl())); } private boolean shouldPush(DiscoveryRequest discoveryRequest, AbstractConnection<DiscoveryResponse> connection) { String type = discoveryRequest.getTypeUrl(); String connectionId = connection.getConnectionId(); // Suitable for bug of istio // See https://github.com/istio/istio/pull/34633 if (type.equals(MESH_CONFIG_PROTO_PACKAGE)) { Loggers.MAIN.info("xds: type {} should be ignored.", type); return false; } if (discoveryRequest.getErrorDetail().getCode() != 0) { Loggers.MAIN.error("xds: ACK error, connection-id: {}, code: {}, message: {}", connectionId, discoveryRequest.getErrorDetail().getCode(), discoveryRequest.getErrorDetail().getMessage()); return false; } WatchedStatus watchedStatus; if (discoveryRequest.getResponseNonce().isEmpty()) { Loggers.MAIN.info("xds: init request, type {}, connection-id {}, version {}", type, connectionId, discoveryRequest.getVersionInfo()); watchedStatus = new WatchedStatus(); watchedStatus.setType(discoveryRequest.getTypeUrl()); connection.addWatchedResource(discoveryRequest.getTypeUrl(), watchedStatus); return true; } watchedStatus = connection.getWatchedStatusByType(discoveryRequest.getTypeUrl()); if (watchedStatus == null) { Loggers.MAIN.info("xds: reconnect, type {}, connection-id {}, version {}, nonce {}.", type, connectionId, discoveryRequest.getVersionInfo(), discoveryRequest.getResponseNonce()); watchedStatus = new WatchedStatus(); watchedStatus.setType(discoveryRequest.getTypeUrl()); connection.addWatchedResource(discoveryRequest.getTypeUrl(), watchedStatus); return true; } if (!watchedStatus.getLatestNonce().equals(discoveryRequest.getResponseNonce())) { Loggers.MAIN.warn("xds: request dis match, type {}, connection-id {}", discoveryRequest.getTypeUrl(), connection.getConnectionId()); return false; } // This request is ack, we should record version and nonce. watchedStatus.setAckedVersion(discoveryRequest.getVersionInfo()); watchedStatus.setAckedNonce(discoveryRequest.getResponseNonce()); Loggers.MAIN.info("xds: ack, type {}, connection-id {}, version {}, nonce {}", type, connectionId, discoveryRequest.getVersionInfo(), discoveryRequest.getResponseNonce()); return false; } public void handleEvent(ResourceSnapshot resourceSnapshot, Event event) { switch (event.getType()) { case Service: if (connections.size() == 0) { return; } Loggers.MAIN.info("xds: event {} trigger push.", event.getType()); // Service Entry via MCP DiscoveryResponse serviceEntryResponse = buildDiscoveryResponse(SERVICE_ENTRY_PROTO_PACKAGE, resourceSnapshot); // TODO CDS, EDS for (AbstractConnection<DiscoveryResponse> connection : connections.values()) { // Service Entry via MCP WatchedStatus watchedStatus = connection.getWatchedStatusByType(SERVICE_ENTRY_PROTO_PACKAGE); if (watchedStatus != null) { connection.push(serviceEntryResponse, watchedStatus); } // TODO CDS, EDS } break; case Endpoint: Loggers.MAIN.warn("Currently, endpoint event is not supported."); break; default: Loggers.MAIN.warn("Invalid event {}, ignore it.", event.getType()); } } private DiscoveryResponse buildDiscoveryResponse(String type, ResourceSnapshot resourceSnapshot) { @SuppressWarnings("unchecked") ApiGenerator<Any> serviceEntryGenerator = (ApiGenerator<Any>) apiGeneratorFactory.getApiGenerator(type); List<Any> rawResources = serviceEntryGenerator.generate(resourceSnapshot); String nonce = NonceGenerator.generateNonce(); return DiscoveryResponse.newBuilder() .setTypeUrl(type) .addAllResources(rawResources) .setVersionInfo(resourceSnapshot.getVersion()) .setNonce(nonce).build(); } }
apache-2.0
angelusmetal/adventure
src/main/java/com/adventure/engine/script/syntax/ListValue.java
868
package com.adventure.engine.script.syntax; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; public class ListValue implements Value { final List<String> values; public ListValue(String[] values) { this.values = new ArrayList<String>(values.length); for (String value : values) { this.values.add(value.trim()); } } @Override public boolean isSimple() { return false; } @Override public boolean isList() { return true; } @Override public boolean isCompound() { return false; } @Override public String getAsString() { return StringUtils.join(values,", "); } @Override public List<String> getAsList() { return values; } @Override public List<Expression> getNested() { return null; } @Override public String toString() { return StringUtils.join(values,", "); } }
apache-2.0
GcsSloop/diycode-sdk
sdk/src/main/java/com/gcssloop/diycode_sdk/api/topic/bean/Topic.java
4302
/* * Copyright 2017 GcsSloop * * 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. * * Last modified 2017-03-08 01:01:18 * * GitHub: https://github.com/GcsSloop * Website: http://www.gcssloop.com * Weibo: http://weibo.com/GcsSloop */ package com.gcssloop.diycode_sdk.api.topic.bean; import com.gcssloop.diycode_sdk.api.base.bean.Abilities; import com.gcssloop.diycode_sdk.api.user.bean.User; import java.io.Serializable; /** * topic 简略信息 */ public class Topic implements Serializable { private int id; // 唯一 id private String title; // 标题 private String created_at; // 创建时间 private String updated_at; // 更新时间 private String replied_at; // 最近一次回复时间 private int replies_count; // 回复总数量 private String node_name; // 节点名称 private int node_id; // 节点 id private int last_reply_user_id; // 最近一次回复的用户 id private String last_reply_user_login; // 最近一次回复的用户登录名 private User user; // 创建该话题的用户(信息) private boolean deleted; // 是否是被删除的 private boolean excellent; // 是否是加精的 private Abilities abilities; // 当前用户对该话题拥有的权限 public void setId(int id) { this.id = id; } public int getId() { return this.id; } public void setTitle(String title) { this.title = title; } public String getTitle() { return this.title; } public void setCreated_at(String created_at) { this.created_at = created_at; } public String getCreated_at() { return this.created_at; } public void setUpdated_at(String updated_at) { this.updated_at = updated_at; } public String getUpdated_at() { return this.updated_at; } public void setReplied_at(String replied_at) { this.replied_at = replied_at; } public String getReplied_at() { return this.replied_at; } public void setReplies_count(int replies_count) { this.replies_count = replies_count; } public int getReplies_count() { return this.replies_count; } public void setNode_name(String node_name) { this.node_name = node_name; } public String getNode_name() { return this.node_name; } public void setNode_id(int node_id) { this.node_id = node_id; } public int getNode_id() { return this.node_id; } public void setLast_reply_user_id(int last_reply_user_id) { this.last_reply_user_id = last_reply_user_id; } public int getLast_reply_user_id() { return this.last_reply_user_id; } public void setLast_reply_user_login(String last_reply_user_login) { this.last_reply_user_login = last_reply_user_login; } public String getLast_reply_user_login() { return this.last_reply_user_login; } public void setUser(User user) { this.user = user; } public User getUser() { return this.user; } public void setDeleted(boolean deleted) { this.deleted = deleted; } public boolean getDeleted() { return this.deleted; } public void setExcellent(boolean excellent) { this.excellent = excellent; } public boolean getExcellent() { return this.excellent; } public void setAbilities(Abilities abilities) { this.abilities = abilities; } public Abilities getAbilities() { return this.abilities; } }
apache-2.0
aldaris/undertow
core/src/main/java/io/undertow/server/HttpServerExchange.java
87777
/* * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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 io.undertow.server; import io.undertow.UndertowLogger; import io.undertow.UndertowMessages; import io.undertow.UndertowOptions; import io.undertow.channels.DetachableStreamSinkChannel; import io.undertow.channels.DetachableStreamSourceChannel; import io.undertow.conduits.EmptyStreamSourceConduit; import io.undertow.connector.PooledByteBuffer; import io.undertow.io.AsyncReceiverImpl; import io.undertow.io.AsyncSenderImpl; import io.undertow.io.BlockingReceiverImpl; import io.undertow.io.BlockingSenderImpl; import io.undertow.io.Receiver; import io.undertow.io.Sender; import io.undertow.io.UndertowInputStream; import io.undertow.io.UndertowOutputStream; import io.undertow.security.api.SecurityContext; import io.undertow.server.handlers.Cookie; import io.undertow.util.AbstractAttachable; import io.undertow.util.AttachmentKey; import io.undertow.util.ConduitFactory; import io.undertow.util.Cookies; import io.undertow.util.HeaderMap; import io.undertow.util.Headers; import io.undertow.util.HttpString; import io.undertow.util.Methods; import io.undertow.util.NetworkUtils; import io.undertow.util.Protocols; import io.undertow.util.Rfc6265CookieSupport; import io.undertow.util.StatusCodes; import org.jboss.logging.Logger; import org.xnio.Buffers; import org.xnio.ChannelExceptionHandler; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.IoUtils; import org.xnio.XnioIoThread; import org.xnio.channels.Channels; import org.xnio.channels.Configurable; import org.xnio.channels.StreamSinkChannel; import org.xnio.channels.StreamSourceChannel; import org.xnio.conduits.Conduit; import org.xnio.conduits.ConduitStreamSinkChannel; import org.xnio.conduits.ConduitStreamSourceChannel; import org.xnio.conduits.StreamSinkConduit; import org.xnio.conduits.StreamSourceConduit; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.FileChannel; import java.util.ArrayDeque; import java.util.Deque; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import static org.xnio.Bits.allAreSet; import static org.xnio.Bits.anyAreClear; import static org.xnio.Bits.anyAreSet; import static org.xnio.Bits.intBitMask; /** * An HTTP server request/response exchange. An instance of this class is constructed as soon as the request headers are * fully parsed. * * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a> */ public final class HttpServerExchange extends AbstractAttachable { // immutable state private static final Logger log = Logger.getLogger(HttpServerExchange.class); private static final RuntimePermission SET_SECURITY_CONTEXT = new RuntimePermission("io.undertow.SET_SECURITY_CONTEXT"); private static final String ISO_8859_1 = "ISO-8859-1"; private static final String HTTPS = "https"; /** * The HTTP reason phrase to send. This is an attachment rather than a field as it is rarely used. If this is not set * a generic description from the RFC is used instead. */ private static final AttachmentKey<String> REASON_PHRASE = AttachmentKey.create(String.class); /** * The attachment key that buffered request data is attached under. */ static final AttachmentKey<PooledByteBuffer[]> BUFFERED_REQUEST_DATA = AttachmentKey.create(PooledByteBuffer[].class); /** * Attachment key that can be used to hold additional request attributes */ public static final AttachmentKey<Map<String, String>> REQUEST_ATTRIBUTES = AttachmentKey.create(Map.class); /** * Attachment key that can be used as a flag of secure attribute */ public static final AttachmentKey<Boolean> SECURE_REQUEST = AttachmentKey.create(Boolean.class); private final ServerConnection connection; private final HeaderMap requestHeaders; private final HeaderMap responseHeaders; private int exchangeCompletionListenersCount = 0; private ExchangeCompletionListener[] exchangeCompleteListeners; private DefaultResponseListener[] defaultResponseListeners; private Map<String, Deque<String>> queryParameters; private Map<String, Deque<String>> pathParameters; private Map<String, Cookie> requestCookies; private Map<String, Cookie> responseCookies; /** * The actual response channel. May be null if it has not been created yet. */ private WriteDispatchChannel responseChannel; /** * The actual request channel. May be null if it has not been created yet. */ protected ReadDispatchChannel requestChannel; private BlockingHttpExchange blockingHttpExchange; private HttpString protocol; /** * The security context */ private SecurityContext securityContext; // mutable state private int state = 200; private HttpString requestMethod; private String requestScheme; /** * The original request URI. This will include the host name if it was specified by the client. * <p> * This is not decoded in any way, and does not include the query string. * <p> * Examples: * GET http://localhost:8080/myFile.jsf?foo=bar HTTP/1.1 -> 'http://localhost:8080/myFile.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -> '/my+File.jsf' */ private String requestURI; /** * The request path. This will be decoded by the server, and does not include the query string. * <p> * This path is not canonicalised, so care must be taken to ensure that escape attacks are not possible. * <p> * Examples: * GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -> '/b/../my+File.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -> '/my File.jsf' */ private String requestPath; /** * The remaining unresolved portion of request path. If a {@link io.undertow.server.handlers.CanonicalPathHandler} is * installed this will be canonicalised. * <p> * Initially this will be equal to {@link #requestPath}, however it will be modified as handlers resolve the path. */ private String relativePath; /** * The resolved part of the canonical path. */ private String resolvedPath = ""; /** * the query string */ private String queryString = ""; private int requestWrapperCount = 0; private ConduitWrapper<StreamSourceConduit>[] requestWrappers; //we don't allocate these by default, as for get requests they are not used private int responseWrapperCount = 0; private ConduitWrapper<StreamSinkConduit>[] responseWrappers; private Sender sender; private Receiver receiver; private long requestStartTime = -1; /** * The maximum entity size. This can be modified before the request stream is obtained, however once the request * stream is obtained this cannot be modified further. * <p> * The default value for this is determined by the {@link io.undertow.UndertowOptions#MAX_ENTITY_SIZE} option. A value * of 0 indicates that this is unbounded. * <p> * If this entity size is exceeded the request channel will be forcibly closed. * <p> * TODO: integrate this with HTTP 100-continue responses, to make it possible to send a 417 rather than just forcibly * closing the channel. * * @see io.undertow.UndertowOptions#MAX_ENTITY_SIZE */ private long maxEntitySize; /** * When the call stack return this task will be executed by the executor specified in {@link #dispatchExecutor}. * If the executor is null then it will be executed by the XNIO worker. */ private Runnable dispatchTask; /** * The executor that is to be used to dispatch the {@link #dispatchTask}. Note that this is not cleared * between dispatches, so once a request has been dispatched once then all subsequent dispatches will use * the same executor. */ private Executor dispatchExecutor; /** * The number of bytes that have been sent to the remote client. This does not include headers, * only the entity body, and does not take any transfer or content encoding into account. */ private long responseBytesSent = 0; private static final int MASK_RESPONSE_CODE = intBitMask(0, 9); /** * Flag that is set when the response sending begins */ private static final int FLAG_RESPONSE_SENT = 1 << 10; /** * Flag that is sent when the response has been fully written and flushed. */ private static final int FLAG_RESPONSE_TERMINATED = 1 << 11; /** * Flag that is set once the request has been fully read. For zero * length requests this is set immediately. */ private static final int FLAG_REQUEST_TERMINATED = 1 << 12; /** * Flag that is set if this is a persistent connection, and the * connection should be re-used. */ private static final int FLAG_PERSISTENT = 1 << 14; /** * If this flag is set it means that the request has been dispatched, * and will not be ending when the call stack returns. * <p> * This could be because it is being dispatched to a worker thread from * an IO thread, or because resume(Reads/Writes) has been called. */ private static final int FLAG_DISPATCHED = 1 << 15; /** * Flag that is set if the {@link #requestURI} field contains the hostname. */ private static final int FLAG_URI_CONTAINS_HOST = 1 << 16; /** * If this flag is set then the request is current running through a * handler chain. * <p> * This will be true most of the time, this only time this will return * false is when performing async operations outside the scope of a call to * {@link Connectors#executeRootHandler(HttpHandler, HttpServerExchange)}, * such as when performing async IO. * <p> * If this is true then when the call stack returns the exchange will either be dispatched, * or the exchange will be ended. */ private static final int FLAG_IN_CALL = 1 << 17; /** * Flag that indicates that reads should be resumed when the call stack returns. */ private static final int FLAG_SHOULD_RESUME_READS = 1 << 18; /** * Flag that indicates that writes should be resumed when the call stack returns */ private static final int FLAG_SHOULD_RESUME_WRITES = 1 << 19; /** * Flag that indicates that the request channel has been reset, and {@link #getRequestChannel()} can be called again */ private static final int FLAG_REQUEST_RESET= 1 << 20; /** * The source address for the request. If this is null then the actual source address from the channel is used */ private InetSocketAddress sourceAddress; /** * The destination address for the request. If this is null then the actual source address from the channel is used */ private InetSocketAddress destinationAddress; public HttpServerExchange(final ServerConnection connection, long maxEntitySize) { this(connection, new HeaderMap(), new HeaderMap(), maxEntitySize); } public HttpServerExchange(final ServerConnection connection) { this(connection, 0); } public HttpServerExchange(final ServerConnection connection, final HeaderMap requestHeaders, final HeaderMap responseHeaders, long maxEntitySize) { this.connection = connection; this.maxEntitySize = maxEntitySize; this.requestHeaders = requestHeaders; this.responseHeaders = responseHeaders; } /** * Get the request protocol string. Normally this is one of the strings listed in {@link Protocols}. * * @return the request protocol string */ public HttpString getProtocol() { return protocol; } /** * Sets the http protocol * * @param protocol */ public HttpServerExchange setProtocol(final HttpString protocol) { this.protocol = protocol; return this; } /** * Determine whether this request conforms to HTTP 0.9. * * @return {@code true} if the request protocol is equal to {@link Protocols#HTTP_0_9}, {@code false} otherwise */ public boolean isHttp09() { return protocol.equals(Protocols.HTTP_0_9); } /** * Determine whether this request conforms to HTTP 1.0. * * @return {@code true} if the request protocol is equal to {@link Protocols#HTTP_1_0}, {@code false} otherwise */ public boolean isHttp10() { return protocol.equals(Protocols.HTTP_1_0); } /** * Determine whether this request conforms to HTTP 1.1. * * @return {@code true} if the request protocol is equal to {@link Protocols#HTTP_1_1}, {@code false} otherwise */ public boolean isHttp11() { return protocol.equals(Protocols.HTTP_1_1); } public boolean isSecure() { Boolean secure = getAttachment(SECURE_REQUEST); if(secure != null && secure) { return true; } String scheme = getRequestScheme(); if (scheme != null && scheme.equalsIgnoreCase(HTTPS)) { return true; } return false; } /** * Get the HTTP request method. Normally this is one of the strings listed in {@link io.undertow.util.Methods}. * * @return the HTTP request method */ public HttpString getRequestMethod() { return requestMethod; } /** * Set the HTTP request method. * * @param requestMethod the HTTP request method */ public HttpServerExchange setRequestMethod(final HttpString requestMethod) { this.requestMethod = requestMethod; return this; } /** * Get the request URI scheme. Normally this is one of {@code http} or {@code https}. * * @return the request URI scheme */ public String getRequestScheme() { return requestScheme; } /** * Set the request URI scheme. * * @param requestScheme the request URI scheme */ public HttpServerExchange setRequestScheme(final String requestScheme) { this.requestScheme = requestScheme; return this; } /** * The original request URI. This will include the host name, protocol etc * if it was specified by the client. * <p> * This is not decoded in any way, and does not include the query string. * <p> * Examples: * GET http://localhost:8080/myFile.jsf?foo=bar HTTP/1.1 -&gt; 'http://localhost:8080/myFile.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -&gt; '/my+File.jsf' */ public String getRequestURI() { return requestURI; } /** * Sets the request URI * * @param requestURI The new request URI */ public HttpServerExchange setRequestURI(final String requestURI) { this.requestURI = requestURI; return this; } /** * Sets the request URI * * @param requestURI The new request URI * @param containsHost If this is true the request URI contains the host part */ public HttpServerExchange setRequestURI(final String requestURI, boolean containsHost) { this.requestURI = requestURI; if (containsHost) { this.state |= FLAG_URI_CONTAINS_HOST; } else { this.state &= ~FLAG_URI_CONTAINS_HOST; } return this; } /** * If a request was submitted to the server with a full URI instead of just a path this * will return true. For example: * <p> * GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -&gt; true * POST /my+File.jsf?foo=bar HTTP/1.1 -&gt; false * * @return <code>true</code> If the request URI contains the host part of the URI */ public boolean isHostIncludedInRequestURI() { return anyAreSet(state, FLAG_URI_CONTAINS_HOST); } /** * The request path. This will be decoded by the server, and does not include the query string. * <p> * This path is not canonicalised, so care must be taken to ensure that escape attacks are not possible. * <p> * Examples: * GET http://localhost:8080/b/../my+File.jsf?foo=bar HTTP/1.1 -&gt; '/b/../my+File.jsf' * POST /my+File.jsf?foo=bar HTTP/1.1 -&gt; '/my File.jsf' */ public String getRequestPath() { return requestPath; } /** * Set the request URI path. * * @param requestPath the request URI path */ public HttpServerExchange setRequestPath(final String requestPath) { this.requestPath = requestPath; return this; } /** * Get the request relative path. This is the path which should be evaluated by the current handler. * <p> * If the {@link io.undertow.server.handlers.CanonicalPathHandler} is installed in the current chain * then this path with be canonicalized * * @return the request relative path */ public String getRelativePath() { return relativePath; } /** * Set the request relative path. * * @param relativePath the request relative path */ public HttpServerExchange setRelativePath(final String relativePath) { this.relativePath = relativePath; return this; } /** * Get the resolved path. * * @return the resolved path */ public String getResolvedPath() { return resolvedPath; } /** * Set the resolved path. * * @param resolvedPath the resolved path */ public HttpServerExchange setResolvedPath(final String resolvedPath) { this.resolvedPath = resolvedPath; return this; } /** * * @return The query string, without the leading ? */ public String getQueryString() { return queryString; } public HttpServerExchange setQueryString(final String queryString) { this.queryString = queryString; return this; } /** * Reconstructs the complete URL as seen by the user. This includes scheme, host name etc, * but does not include query string. * <p> * This is not decoded. */ public String getRequestURL() { if (isHostIncludedInRequestURI()) { return getRequestURI(); } else { return getRequestScheme() + "://" + getHostAndPort() + getRequestURI(); } } /** * Returns the request charset. If none was explicitly specified it will return * "ISO-8859-1", which is the default charset for HTTP requests. * * @return The character encoding */ public String getRequestCharset() { return extractCharset(requestHeaders); } /** * Returns the response charset. If none was explicitly specified it will return * "ISO-8859-1", which is the default charset for HTTP requests. * * @return The character encoding */ public String getResponseCharset() { HeaderMap headers = responseHeaders; return extractCharset(headers); } private String extractCharset(HeaderMap headers) { String contentType = headers.getFirst(Headers.CONTENT_TYPE); if (contentType != null) { String value = Headers.extractQuotedValueFromHeader(contentType, "charset"); if (value != null) { return value; } } return ISO_8859_1; } /** * Return the host that this request was sent to, in general this will be the * value of the Host header, minus the port specifier. * <p> * If this resolves to an IPv6 address it will not be enclosed by square brackets. * Care must be taken when constructing URLs based on this method to ensure IPv6 URLs * are handled correctly. * * @return The host part of the destination address */ public String getHostName() { String host = requestHeaders.getFirst(Headers.HOST); if (host == null || "".equals(host.trim())) { host = getDestinationAddress().getHostString(); } else { if (host.startsWith("[")) { host = host.substring(1, host.indexOf(']')); } else if (host.indexOf(':') != -1) { host = host.substring(0, host.indexOf(':')); } } return host; } /** * Return the host, and also the port if this request was sent to a non-standard port. In general * this will just be the value of the Host header. * <p> * If this resolves to an IPv6 address it *will* be enclosed by square brackets. The return * value of this method is suitable for inclusion in a URL. * * @return The host and port part of the destination address */ public String getHostAndPort() { String host = requestHeaders.getFirst(Headers.HOST); if (host == null || "".equals(host.trim())) { InetSocketAddress address = getDestinationAddress(); host = NetworkUtils.formatPossibleIpv6Address(address.getHostString()); int port = address.getPort(); if (!((getRequestScheme().equals("http") && port == 80) || (getRequestScheme().equals("https") && port == 443))) { host = host + ":" + port; } } return host; } /** * Return the port that this request was sent to. In general this will be the value of the Host * header, minus the host name. * * @return The port part of the destination address */ public int getHostPort() { String host = requestHeaders.getFirst(Headers.HOST); if (host != null) { //for ipv6 addresses we make sure we take out the first part, which can have multiple occurrences of : final int colonIndex; if (host.startsWith("[")) { colonIndex = host.indexOf(':', host.indexOf(']')); } else { colonIndex = host.indexOf(':'); } if (colonIndex != -1) { try { return Integer.parseInt(host.substring(colonIndex + 1)); } catch (NumberFormatException ignore) {} } if (getRequestScheme().equals("https")) { return 443; } else if (getRequestScheme().equals("http")) { return 80; } } return getDestinationAddress().getPort(); } /** * Get the underlying HTTP connection. * * @return the underlying HTTP connection */ public ServerConnection getConnection() { return connection; } public boolean isPersistent() { return anyAreSet(state, FLAG_PERSISTENT); } /** * * @return <code>true</code> If the current thread in the IO thread for the exchange */ public boolean isInIoThread() { return getIoThread() == Thread.currentThread(); } /** * * @return True if this exchange represents an upgrade response */ public boolean isUpgrade() { return getStatusCode() == StatusCodes.SWITCHING_PROTOCOLS; } /** * * @return The number of bytes sent in the entity body */ public long getResponseBytesSent() { if(Connectors.isEntityBodyAllowed(this) && !getRequestMethod().equals(Methods.HEAD)) { return responseBytesSent; } else { return 0; //body is not allowed, even if we attempt to write it will be ignored } } /** * Updates the number of response bytes sent. Used when compression is in use * @param bytes The number of bytes to increase the response size by. May be negative */ void updateBytesSent(long bytes) { if(Connectors.isEntityBodyAllowed(this) && !getRequestMethod().equals(Methods.HEAD)) { responseBytesSent += bytes; } } public HttpServerExchange setPersistent(final boolean persistent) { if (persistent) { this.state = this.state | FLAG_PERSISTENT; } else { this.state = this.state & ~FLAG_PERSISTENT; } return this; } public boolean isDispatched() { return anyAreSet(state, FLAG_DISPATCHED); } public HttpServerExchange unDispatch() { state &= ~FLAG_DISPATCHED; dispatchTask = null; return this; } /** * {@link #dispatch(Executor, Runnable)} should be used instead of this method, as it is hard to use safely. * * Use {@link io.undertow.util.SameThreadExecutor#INSTANCE} if you do not want to dispatch to another thread. * * @return this exchange */ @Deprecated public HttpServerExchange dispatch() { state |= FLAG_DISPATCHED; return this; } /** * Dispatches this request to the XNIO worker thread pool. Once the call stack returns * the given runnable will be submitted to the executor. * <p> * In general handlers should first check the value of {@link #isInIoThread()} before * calling this method, and only dispatch if the request is actually running in the IO * thread. * * @param runnable The task to run * @throws IllegalStateException If this exchange has already been dispatched */ public HttpServerExchange dispatch(final Runnable runnable) { dispatch(null, runnable); return this; } /** * Dispatches this request to the given executor. Once the call stack returns * the given runnable will be submitted to the executor. * <p> * In general handlers should first check the value of {@link #isInIoThread()} before * calling this method, and only dispatch if the request is actually running in the IO * thread. * * @param runnable The task to run * @throws IllegalStateException If this exchange has already been dispatched */ public HttpServerExchange dispatch(final Executor executor, final Runnable runnable) { if (isInCall()) { if (executor != null) { this.dispatchExecutor = executor; } state |= FLAG_DISPATCHED; if(anyAreSet(state, FLAG_SHOULD_RESUME_READS | FLAG_SHOULD_RESUME_WRITES)) { throw UndertowMessages.MESSAGES.resumedAndDispatched(); } this.dispatchTask = runnable; } else { if (executor == null) { getConnection().getWorker().execute(runnable); } else { executor.execute(runnable); } } return this; } public HttpServerExchange dispatch(final HttpHandler handler) { dispatch(null, handler); return this; } public HttpServerExchange dispatch(final Executor executor, final HttpHandler handler) { final Runnable runnable = new Runnable() { @Override public void run() { Connectors.executeRootHandler(handler, HttpServerExchange.this); } }; dispatch(executor, runnable); return this; } /** * Sets the executor that is used for dispatch operations where no executor is specified. * * @param executor The executor to use */ public HttpServerExchange setDispatchExecutor(final Executor executor) { if (executor == null) { dispatchExecutor = null; } else { dispatchExecutor = executor; } return this; } /** * Gets the current executor that is used for dispatch operations. This may be null * * @return The current dispatch executor */ public Executor getDispatchExecutor() { return dispatchExecutor; } /** * @return The current dispatch task */ Runnable getDispatchTask() { return dispatchTask; } boolean isInCall() { return anyAreSet(state, FLAG_IN_CALL); } HttpServerExchange setInCall(boolean value) { if (value) { state |= FLAG_IN_CALL; } else { state &= ~FLAG_IN_CALL; } return this; } /** * Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the * request and response as terminated, which means that once the current request is completed the raw channel * can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()} * * @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being * read */ public HttpServerExchange upgradeChannel(final HttpUpgradeListener listener) { if (!connection.isUpgradeSupported()) { throw UndertowMessages.MESSAGES.upgradeNotSupported(); } if(!getRequestHeaders().contains(Headers.UPGRADE)) { throw UndertowMessages.MESSAGES.notAnUpgradeRequest(); } UndertowLogger.REQUEST_LOGGER.debugf("Upgrading request %s", this); connection.setUpgradeListener(listener); setStatusCode(StatusCodes.SWITCHING_PROTOCOLS); getResponseHeaders().put(Headers.CONNECTION, Headers.UPGRADE_STRING); return this; } /** * Upgrade the channel to a raw socket. This method set the response code to 101, and then marks both the * request and response as terminated, which means that once the current request is completed the raw channel * can be obtained from {@link io.undertow.server.protocol.http.HttpServerConnection#getChannel()} * * @param productName the product name to report to the client * @throws IllegalStateException if a response or upgrade was already sent, or if the request body is already being * read */ public HttpServerExchange upgradeChannel(String productName, final HttpUpgradeListener listener) { if (!connection.isUpgradeSupported()) { throw UndertowMessages.MESSAGES.upgradeNotSupported(); } UndertowLogger.REQUEST_LOGGER.debugf("Upgrading request %s", this); connection.setUpgradeListener(listener); setStatusCode(StatusCodes.SWITCHING_PROTOCOLS); final HeaderMap headers = getResponseHeaders(); headers.put(Headers.UPGRADE, productName); headers.put(Headers.CONNECTION, Headers.UPGRADE_STRING); return this; } /** * * @param connectListener * @return */ public HttpServerExchange acceptConnectRequest(HttpUpgradeListener connectListener) { if(!getRequestMethod().equals(Methods.CONNECT)) { throw UndertowMessages.MESSAGES.notAConnectRequest(); } connection.setConnectListener(connectListener); return this; } public HttpServerExchange addExchangeCompleteListener(final ExchangeCompletionListener listener) { if(isComplete() || this.exchangeCompletionListenersCount == -1) { throw UndertowMessages.MESSAGES.exchangeAlreadyComplete(); } final int exchangeCompletionListenersCount = this.exchangeCompletionListenersCount++; ExchangeCompletionListener[] exchangeCompleteListeners = this.exchangeCompleteListeners; if (exchangeCompleteListeners == null || exchangeCompleteListeners.length == exchangeCompletionListenersCount) { ExchangeCompletionListener[] old = exchangeCompleteListeners; this.exchangeCompleteListeners = exchangeCompleteListeners = new ExchangeCompletionListener[exchangeCompletionListenersCount + 2]; if(old != null) { System.arraycopy(old, 0, exchangeCompleteListeners, 0, exchangeCompletionListenersCount); } } exchangeCompleteListeners[exchangeCompletionListenersCount] = listener; return this; } public HttpServerExchange addDefaultResponseListener(final DefaultResponseListener listener) { int i = 0; if(defaultResponseListeners == null) { defaultResponseListeners = new DefaultResponseListener[2]; } else { while (i != defaultResponseListeners.length && defaultResponseListeners[i] != null) { ++i; } if (i == defaultResponseListeners.length) { DefaultResponseListener[] old = defaultResponseListeners; defaultResponseListeners = new DefaultResponseListener[defaultResponseListeners.length + 2]; System.arraycopy(old, 0, defaultResponseListeners, 0, old.length); } } defaultResponseListeners[i] = listener; return this; } /** * Get the source address of the HTTP request. * * @return the source address of the HTTP request */ public InetSocketAddress getSourceAddress() { if (sourceAddress != null) { return sourceAddress; } return connection.getPeerAddress(InetSocketAddress.class); } /** * Sets the source address of the HTTP request. If this is not explicitly set * the actual source address of the channel is used. * * @param sourceAddress The address */ public HttpServerExchange setSourceAddress(InetSocketAddress sourceAddress) { this.sourceAddress = sourceAddress; return this; } /** * Get the destination address of the HTTP request. * * @return the destination address of the HTTP request */ public InetSocketAddress getDestinationAddress() { if (destinationAddress != null) { return destinationAddress; } return connection.getLocalAddress(InetSocketAddress.class); } /** * Sets the destination address of the HTTP request. If this is not explicitly set * the actual destination address of the channel is used. * * @param destinationAddress The address */ public HttpServerExchange setDestinationAddress(InetSocketAddress destinationAddress) { this.destinationAddress = destinationAddress; return this; } /** * Get the request headers. * * @return the request headers */ public HeaderMap getRequestHeaders() { return requestHeaders; } /** * @return The content length of the request, or <code>-1</code> if it has not been set */ public long getRequestContentLength() { String contentLengthString = requestHeaders.getFirst(Headers.CONTENT_LENGTH); if (contentLengthString == null) { return -1; } return Long.parseLong(contentLengthString); } /** * Get the response headers. * * @return the response headers */ public HeaderMap getResponseHeaders() { return responseHeaders; } /** * @return The content length of the response, or <code>-1</code> if it has not been set */ public long getResponseContentLength() { String contentLengthString = responseHeaders.getFirst(Headers.CONTENT_LENGTH); if (contentLengthString == null) { return -1; } return Long.parseLong(contentLengthString); } /** * Sets the response content length * * @param length The content length */ public HttpServerExchange setResponseContentLength(long length) { if (length == -1) { responseHeaders.remove(Headers.CONTENT_LENGTH); } else { responseHeaders.put(Headers.CONTENT_LENGTH, Long.toString(length)); } return this; } /** * Returns a mutable map of query parameters. * * @return The query parameters */ public Map<String, Deque<String>> getQueryParameters() { if (queryParameters == null) { queryParameters = new TreeMap<>(); } return queryParameters; } public HttpServerExchange addQueryParam(final String name, final String param) { if (queryParameters == null) { queryParameters = new TreeMap<>(); } Deque<String> list = queryParameters.get(name); if (list == null) { queryParameters.put(name, list = new ArrayDeque<>(2)); } list.add(param); return this; } /** * Returns a mutable map of path parameters * * @return The path parameters */ public Map<String, Deque<String>> getPathParameters() { if (pathParameters == null) { pathParameters = new TreeMap<>(); } return pathParameters; } public HttpServerExchange addPathParam(final String name, final String param) { if (pathParameters == null) { pathParameters = new TreeMap<>(); } Deque<String> list = pathParameters.get(name); if (list == null) { pathParameters.put(name, list = new ArrayDeque<>(2)); } list.add(param); return this; } /** * @return A mutable map of request cookies */ public Map<String, Cookie> getRequestCookies() { if (requestCookies == null) { requestCookies = Cookies.parseRequestCookies( getConnection().getUndertowOptions().get(UndertowOptions.MAX_COOKIES, 200), getConnection().getUndertowOptions().get(UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE, false), requestHeaders.get(Headers.COOKIE)); } return requestCookies; } /** * Sets a response cookie * * @param cookie The cookie */ public HttpServerExchange setResponseCookie(final Cookie cookie) { if (getConnection().getUndertowOptions().get(UndertowOptions.ENABLE_RFC6265_COOKIE_VALIDATION, UndertowOptions.DEFAULT_ENABLE_RFC6265_COOKIE_VALIDATION)) { if (cookie.getValue() != null && !cookie.getValue().isEmpty()) { Rfc6265CookieSupport.validateCookieValue(cookie.getValue()); } if (cookie.getPath() != null && !cookie.getPath().isEmpty()) { Rfc6265CookieSupport.validatePath(cookie.getPath()); } if (cookie.getDomain() != null && !cookie.getDomain().isEmpty()) { Rfc6265CookieSupport.validateDomain(cookie.getDomain()); } } if (responseCookies == null) { responseCookies = new TreeMap<>(); //hashmap is slow to allocate in JDK7 } responseCookies.put(cookie.getName(), cookie); return this; } /** * @return A mutable map of response cookies */ public Map<String, Cookie> getResponseCookies() { if (responseCookies == null) { responseCookies = new TreeMap<>(); } return responseCookies; } /** * For internal use only * * @return The response cookies, or null if they have not been set yet */ Map<String, Cookie> getResponseCookiesInternal() { return responseCookies; } /** * @return <code>true</code> If the response has already been started */ public boolean isResponseStarted() { return allAreSet(state, FLAG_RESPONSE_SENT); } /** * Get the inbound request. If there is no request body, calling this method * may cause the next request to immediately be processed. The {@link StreamSourceChannel#close()} or {@link StreamSourceChannel#shutdownReads()} * method must be called at some point after the request is processed to prevent resource leakage and to allow * the next request to proceed. Any unread content will be discarded. * * @return the channel for the inbound request, or {@code null} if another party already acquired the channel */ public StreamSourceChannel getRequestChannel() { if (requestChannel != null) { if(anyAreSet(state, FLAG_REQUEST_RESET)) { state &= ~FLAG_REQUEST_RESET; return requestChannel; } return null; } if (anyAreSet(state, FLAG_REQUEST_TERMINATED)) { return requestChannel = new ReadDispatchChannel(new ConduitStreamSourceChannel(Configurable.EMPTY, new EmptyStreamSourceConduit(getIoThread()))); } final ConduitWrapper<StreamSourceConduit>[] wrappers = this.requestWrappers; final ConduitStreamSourceChannel sourceChannel = connection.getSourceChannel(); if (wrappers != null) { this.requestWrappers = null; final WrapperConduitFactory<StreamSourceConduit> factory = new WrapperConduitFactory<>(wrappers, requestWrapperCount, sourceChannel.getConduit(), this); sourceChannel.setConduit(factory.create()); } return requestChannel = new ReadDispatchChannel(sourceChannel); } void resetRequestChannel() { state |= FLAG_REQUEST_RESET; } public boolean isRequestChannelAvailable() { return requestChannel == null || anyAreSet(state, FLAG_REQUEST_RESET); } /** * Returns true if the completion handler for this exchange has been invoked, and the request is considered * finished. */ public boolean isComplete() { return allAreSet(state, FLAG_REQUEST_TERMINATED | FLAG_RESPONSE_TERMINATED); } /** * Returns true if all data has been read from the request, or if there * was not data. * * @return true if the request is complete */ public boolean isRequestComplete() { PooledByteBuffer[] data = getAttachment(BUFFERED_REQUEST_DATA); if(data != null) { return false; } return allAreSet(state, FLAG_REQUEST_TERMINATED); } /** * @return true if the responses is complete */ public boolean isResponseComplete() { return allAreSet(state, FLAG_RESPONSE_TERMINATED); } /** * Force the codec to treat the request as fully read. Should only be invoked by handlers which downgrade * the socket or implement a transfer coding. */ void terminateRequest() { int oldVal = state; if (allAreSet(oldVal, FLAG_REQUEST_TERMINATED)) { // idempotent return; } if (requestChannel != null) { requestChannel.requestDone(); } this.state = oldVal | FLAG_REQUEST_TERMINATED; if (anyAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) { invokeExchangeCompleteListeners(); } } private void invokeExchangeCompleteListeners() { if (exchangeCompletionListenersCount > 0) { int i = exchangeCompletionListenersCount - 1; ExchangeCompletionListener next = exchangeCompleteListeners[i]; exchangeCompletionListenersCount = -1; next.exchangeEvent(this, new ExchangeCompleteNextListener(exchangeCompleteListeners, this, i)); } else if (exchangeCompletionListenersCount == 0) { exchangeCompletionListenersCount = -1; connection.exchangeComplete(this); } } /** * Get the response channel. The channel must be closed and fully flushed before the next response can be started. * In order to close the channel you must first call {@link org.xnio.channels.StreamSinkChannel#shutdownWrites()}, * and then call {@link org.xnio.channels.StreamSinkChannel#flush()} until it returns true. Alternatively you can * call {@link #endExchange()}, which will close the channel as part of its cleanup. * <p> * Closing a fixed-length response before the corresponding number of bytes has been written will cause the connection * to be reset and subsequent requests to fail; thus it is important to ensure that the proper content length is * delivered when one is specified. The response channel may not be writable until after the response headers have * been sent. * <p> * If this method is not called then an empty or default response body will be used, depending on the response code set. * <p> * The returned channel will begin to write out headers when the first write request is initiated, or when * {@link org.xnio.channels.StreamSinkChannel#shutdownWrites()} is called on the channel with no content being written. * Once the channel is acquired, however, the response code and headers may not be modified. * <p> * * @return the response channel, or {@code null} if another party already acquired the channel */ public StreamSinkChannel getResponseChannel() { if (responseChannel != null) { return null; } final ConduitWrapper<StreamSinkConduit>[] wrappers = responseWrappers; this.responseWrappers = null; final ConduitStreamSinkChannel sinkChannel = connection.getSinkChannel(); if (sinkChannel == null) { return null; } if(wrappers != null) { final WrapperStreamSinkConduitFactory factory = new WrapperStreamSinkConduitFactory(wrappers, responseWrapperCount, this, sinkChannel.getConduit()); sinkChannel.setConduit(factory.create()); } else { sinkChannel.setConduit(connection.getSinkConduit(this, sinkChannel.getConduit())); } this.responseChannel = new WriteDispatchChannel(sinkChannel); this.startResponse(); return responseChannel; } /** * Get the response sender. * <p> * For blocking exchanges this will return a sender that uses the underlying output stream. * * @return the response sender, or {@code null} if another party already acquired the channel or the sender * @see #getResponseChannel() */ public Sender getResponseSender() { if (blockingHttpExchange != null) { return blockingHttpExchange.getSender(); } if (sender != null) { return sender; } return sender = new AsyncSenderImpl(this); } public Receiver getRequestReceiver() { if(blockingHttpExchange != null) { return blockingHttpExchange.getReceiver(); } if(receiver != null) { return receiver; } return receiver = new AsyncReceiverImpl(this); } /** * @return <code>true</code> if {@link #getResponseChannel()} has not been called */ public boolean isResponseChannelAvailable() { return responseChannel == null; } /** * Get the status code. * * @see #getStatusCode() * @return the status code */ @Deprecated public int getResponseCode() { return state & MASK_RESPONSE_CODE; } /** * Change the status code for this response. If not specified, the code will be a {@code 200}. Setting * the status code after the response headers have been transmitted has no effect. * * @see #setStatusCode(int) * @param statusCode the new code * @throws IllegalStateException if a response or upgrade was already sent */ @Deprecated public HttpServerExchange setResponseCode(final int statusCode) { return setStatusCode(statusCode); } /** * Get the status code. * * @return the status code */ public int getStatusCode() { return state & MASK_RESPONSE_CODE; } /** * Change the status code for this response. If not specified, the code will be a {@code 200}. Setting * the status code after the response headers have been transmitted has no effect. * * @param statusCode the new code * @throws IllegalStateException if a response or upgrade was already sent */ public HttpServerExchange setStatusCode(final int statusCode) { if (statusCode < 0 || statusCode > 999) { throw new IllegalArgumentException("Invalid response code"); } int oldVal = state; if (allAreSet(oldVal, FLAG_RESPONSE_SENT)) { throw UndertowMessages.MESSAGES.responseAlreadyStarted(); } if(statusCode >= 500) { if(UndertowLogger.ERROR_RESPONSE.isDebugEnabled()) { UndertowLogger.ERROR_RESPONSE.debugf(new RuntimeException(), "Setting error code %s for exchange %s", statusCode, this); } } this.state = oldVal & ~MASK_RESPONSE_CODE | statusCode & MASK_RESPONSE_CODE; return this; } /** * Sets the HTTP reason phrase. Depending on the protocol this may or may not be honoured. In particular HTTP2 * has removed support for the reason phrase. * * This method should only be used to interact with legacy frameworks that give special meaning to the reason phrase. * * @param message The status message * @return this exchange */ public HttpServerExchange setReasonPhrase(String message) { putAttachment(REASON_PHRASE, message); return this; } /** * * @return The current reason phrase */ public String getReasonPhrase() { return getAttachment(REASON_PHRASE); } /** * Adds a {@link ConduitWrapper} to the request wrapper chain. * * @param wrapper the wrapper */ public HttpServerExchange addRequestWrapper(final ConduitWrapper<StreamSourceConduit> wrapper) { ConduitWrapper<StreamSourceConduit>[] wrappers = requestWrappers; if (requestChannel != null) { throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided(); } if (wrappers == null) { wrappers = requestWrappers = new ConduitWrapper[2]; } else if (wrappers.length == requestWrapperCount) { requestWrappers = new ConduitWrapper[wrappers.length + 2]; System.arraycopy(wrappers, 0, requestWrappers, 0, wrappers.length); wrappers = requestWrappers; } wrappers[requestWrapperCount++] = wrapper; return this; } /** * Adds a {@link ConduitWrapper} to the response wrapper chain. * * @param wrapper the wrapper */ public HttpServerExchange addResponseWrapper(final ConduitWrapper<StreamSinkConduit> wrapper) { ConduitWrapper<StreamSinkConduit>[] wrappers = responseWrappers; if (responseChannel != null) { throw UndertowMessages.MESSAGES.responseChannelAlreadyProvided(); } if(wrappers == null) { this.responseWrappers = wrappers = new ConduitWrapper[2]; } else if (wrappers.length == responseWrapperCount) { responseWrappers = new ConduitWrapper[wrappers.length + 2]; System.arraycopy(wrappers, 0, responseWrappers, 0, wrappers.length); wrappers = responseWrappers; } wrappers[responseWrapperCount++] = wrapper; return this; } /** * Calling this method puts the exchange in blocking mode, and creates a * {@link BlockingHttpExchange} object to store the streams. * <p> * When an exchange is in blocking mode the input stream methods become * available, other than that there is presently no major difference * between blocking an non-blocking modes. * * @return The existing blocking exchange, if any */ public BlockingHttpExchange startBlocking() { final BlockingHttpExchange old = this.blockingHttpExchange; blockingHttpExchange = new DefaultBlockingHttpExchange(this); return old; } /** * Calling this method puts the exchange in blocking mode, using the given * blocking exchange as the source of the streams. * <p> * When an exchange is in blocking mode the input stream methods become * available, other than that there is presently no major difference * between blocking an non-blocking modes. * <p> * Note that this method may be called multiple times with different * exchange objects, to allow handlers to modify the streams * that are being used. * * @return The existing blocking exchange, if any */ public BlockingHttpExchange startBlocking(final BlockingHttpExchange httpExchange) { final BlockingHttpExchange old = this.blockingHttpExchange; blockingHttpExchange = httpExchange; return old; } /** * Returns true if {@link #startBlocking()} or {@link #startBlocking(BlockingHttpExchange)} has been called. * * @return <code>true</code> If this is a blocking HTTP server exchange */ public boolean isBlocking() { return blockingHttpExchange != null; } /** * @return The input stream * @throws IllegalStateException if {@link #startBlocking()} has not been called */ public InputStream getInputStream() { if (blockingHttpExchange == null) { throw UndertowMessages.MESSAGES.startBlockingHasNotBeenCalled(); } return blockingHttpExchange.getInputStream(); } /** * @return The output stream * @throws IllegalStateException if {@link #startBlocking()} has not been called */ public OutputStream getOutputStream() { if (blockingHttpExchange == null) { throw UndertowMessages.MESSAGES.startBlockingHasNotBeenCalled(); } return blockingHttpExchange.getOutputStream(); } /** * Force the codec to treat the response as fully written. Should only be invoked by handlers which downgrade * the socket or implement a transfer coding. */ HttpServerExchange terminateResponse() { int oldVal = state; if (allAreSet(oldVal, FLAG_RESPONSE_TERMINATED)) { // idempotent return this; } if(responseChannel != null) { responseChannel.responseDone(); } this.state = oldVal | FLAG_RESPONSE_TERMINATED; if (anyAreSet(oldVal, FLAG_REQUEST_TERMINATED)) { invokeExchangeCompleteListeners(); } return this; } /** * @return The request start time using the JVM's high-resolution time source, * in nanoseconds, or -1 if this was not recorded * @see UndertowOptions#RECORD_REQUEST_START_TIME * @see Connectors#setRequestStartTime(HttpServerExchange) */ public long getRequestStartTime() { return requestStartTime; } HttpServerExchange setRequestStartTime(long requestStartTime) { this.requestStartTime = requestStartTime; return this; } /** * Ends the exchange by fully draining the request channel, and flushing the response channel. * <p> * This can result in handoff to an XNIO worker, so after this method is called the exchange should * not be modified by the caller. * <p> * If the exchange is already complete this method is a noop */ public HttpServerExchange endExchange() { final int state = this.state; if (allAreSet(state, FLAG_REQUEST_TERMINATED | FLAG_RESPONSE_TERMINATED)) { if(blockingHttpExchange != null) { //we still have to close the blocking exchange in this case, IoUtils.safeClose(blockingHttpExchange); } return this; } if(defaultResponseListeners != null) { int i = defaultResponseListeners.length - 1; while (i >= 0) { DefaultResponseListener listener = defaultResponseListeners[i]; if (listener != null) { defaultResponseListeners[i] = null; try { if (listener.handleDefaultResponse(this)) { return this; } } catch (Throwable e) { UndertowLogger.REQUEST_LOGGER.debug("Exception running default response listener", e); } } i--; } } if (anyAreClear(state, FLAG_REQUEST_TERMINATED)) { connection.terminateRequestChannel(this); } if (blockingHttpExchange != null) { try { //TODO: can we end up in this situation in a IO thread? blockingHttpExchange.close(); } catch (IOException e) { UndertowLogger.REQUEST_IO_LOGGER.ioException(e); IoUtils.safeClose(connection); } catch (Throwable t) { UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t); IoUtils.safeClose(connection); } } //417 means that we are rejecting the request //so the client should not actually send any data if (anyAreClear(state, FLAG_REQUEST_TERMINATED)) { //not really sure what the best thing to do here is //for now we are just going to drain the channel if (requestChannel == null) { getRequestChannel(); } int totalRead = 0; for (; ; ) { try { long read = Channels.drain(requestChannel, Long.MAX_VALUE); totalRead += read; if (read == 0) { //if the response code is 417 this is a rejected continuation request. //however there is a chance the client could have sent the data anyway //so we attempt to drain, and if we have not drained anything then we //assume the server has not sent any data if (getStatusCode() != StatusCodes.EXPECTATION_FAILED || totalRead > 0) { requestChannel.getReadSetter().set(ChannelListeners.drainListener(Long.MAX_VALUE, new ChannelListener<StreamSourceChannel>() { @Override public void handleEvent(final StreamSourceChannel channel) { if (anyAreClear(state, FLAG_RESPONSE_TERMINATED)) { closeAndFlushResponse(); } } }, new ChannelExceptionHandler<StreamSourceChannel>() { @Override public void handleException(final StreamSourceChannel channel, final IOException e) { //make sure the listeners have been invoked //unless the connection has been killed this is a no-op invokeExchangeCompleteListeners(); UndertowLogger.REQUEST_LOGGER.debug("Exception draining request stream", e); IoUtils.safeClose(connection); } } )); requestChannel.resumeReads(); return this; } else { break; } } else if (read == -1) { break; } } catch (Throwable t) { if (t instanceof IOException) { UndertowLogger.REQUEST_IO_LOGGER.ioException((IOException) t); } else { UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t); } invokeExchangeCompleteListeners(); IoUtils.safeClose(connection); return this; } } } if (anyAreClear(state, FLAG_RESPONSE_TERMINATED)) { closeAndFlushResponse(); } return this; } private void closeAndFlushResponse() { if(!connection.isOpen()) { //not much point trying to flush //make sure the listeners have been invoked invokeExchangeCompleteListeners(); return; } try { if (isResponseChannelAvailable()) { if(!getRequestMethod().equals(Methods.CONNECT) && !(getRequestMethod().equals(Methods.HEAD) && getResponseHeaders().contains(Headers.CONTENT_LENGTH)) && Connectors.isEntityBodyAllowed(this)) { //according to getResponseHeaders().put(Headers.CONTENT_LENGTH, "0"); } getResponseChannel(); } responseChannel.shutdownWrites(); if (!responseChannel.flush()) { responseChannel.getWriteSetter().set(ChannelListeners.flushingChannelListener( new ChannelListener<StreamSinkChannel>() { @Override public void handleEvent(final StreamSinkChannel channel) { channel.suspendWrites(); channel.getWriteSetter().set(null); //defensive programming, should never happen if (anyAreClear(state, FLAG_RESPONSE_TERMINATED)) { UndertowLogger.ROOT_LOGGER.responseWasNotTerminated(connection, HttpServerExchange.this); IoUtils.safeClose(connection); } } }, new ChannelExceptionHandler<Channel>() { @Override public void handleException(final Channel channel, final IOException exception) { //make sure the listeners have been invoked invokeExchangeCompleteListeners(); UndertowLogger.REQUEST_LOGGER.debug("Exception ending request", exception); IoUtils.safeClose(connection); } } )); responseChannel.resumeWrites(); } else { //defensive programming, should never happen if (anyAreClear(state, FLAG_RESPONSE_TERMINATED)) { UndertowLogger.ROOT_LOGGER.responseWasNotTerminated(connection, this); IoUtils.safeClose(connection); } } } catch (Throwable t) { if (t instanceof IOException) { UndertowLogger.REQUEST_IO_LOGGER.ioException((IOException) t); } else { UndertowLogger.REQUEST_IO_LOGGER.handleUnexpectedFailure(t); } invokeExchangeCompleteListeners(); IoUtils.safeClose(connection); } } /** * Transmit the response headers. After this method successfully returns, * the response channel may become writable. * <p> * If this method fails the request and response channels will be closed. * <p> * This method runs asynchronously. If the channel is writable it will * attempt to write as much of the response header as possible, and then * queue the rest in a listener and return. * <p> * If future handlers in the chain attempt to write before this is finished * XNIO will just magically sort it out so it works. This is not actually * implemented yet, so we just terminate the connection straight away at * the moment. * <p> * TODO: make this work properly * * @throws IllegalStateException if the response headers were already sent */ HttpServerExchange startResponse() throws IllegalStateException { int oldVal = state; if (allAreSet(oldVal, FLAG_RESPONSE_SENT)) { throw UndertowMessages.MESSAGES.responseAlreadyStarted(); } this.state = oldVal | FLAG_RESPONSE_SENT; log.tracef("Starting to write response for %s", this); return this; } public XnioIoThread getIoThread() { return connection.getIoThread(); } /** * @return The maximum entity size for this exchange */ public long getMaxEntitySize() { return maxEntitySize; } /** * Sets the max entity size for this exchange. This cannot be modified after the request channel has been obtained. * * @param maxEntitySize The max entity size */ public HttpServerExchange setMaxEntitySize(final long maxEntitySize) { if (!isRequestChannelAvailable()) { throw UndertowMessages.MESSAGES.requestChannelAlreadyProvided(); } this.maxEntitySize = maxEntitySize; connection.maxEntitySizeUpdated(this); return this; } public SecurityContext getSecurityContext() { return securityContext; } public void setSecurityContext(SecurityContext securityContext) { SecurityManager sm = System.getSecurityManager(); if(sm != null) { sm.checkPermission(SET_SECURITY_CONTEXT); } this.securityContext = securityContext; } /** * Adds a listener that will be invoked on response commit * * @param listener The response listener */ public void addResponseCommitListener(final ResponseCommitListener listener) { //technically it is possible to modify the exchange after the response conduit has been created //as the response channel should not be retrieved until it is about to be written to //if we get complaints about this we can add support for it, however it makes the exchange bigger and the connectors more complex addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() { @Override public StreamSinkConduit wrap(ConduitFactory<StreamSinkConduit> factory, HttpServerExchange exchange) { listener.beforeCommit(exchange); return factory.create(); } }); } /** * Actually resumes reads or writes, if the relevant method has been called. * * @return <code>true</code> if reads or writes were resumed */ boolean runResumeReadWrite() { boolean ret = false; if(anyAreSet(state, FLAG_SHOULD_RESUME_WRITES)) { responseChannel.runResume(); ret = true; } if(anyAreSet(state, FLAG_SHOULD_RESUME_READS)) { requestChannel.runResume(); ret = true; } return ret; } boolean isResumed() { return anyAreSet(state, FLAG_SHOULD_RESUME_WRITES | FLAG_SHOULD_RESUME_READS); } private static class ExchangeCompleteNextListener implements ExchangeCompletionListener.NextListener { private final ExchangeCompletionListener[] list; private final HttpServerExchange exchange; private int i; ExchangeCompleteNextListener(final ExchangeCompletionListener[] list, final HttpServerExchange exchange, int i) { this.list = list; this.exchange = exchange; this.i = i; } @Override public void proceed() { if (--i >= 0) { final ExchangeCompletionListener next = list[i]; next.exchangeEvent(exchange, this); } else if(i == -1) { exchange.connection.exchangeComplete(exchange); } } } private static class DefaultBlockingHttpExchange implements BlockingHttpExchange { private InputStream inputStream; private UndertowOutputStream outputStream; private Sender sender; private final HttpServerExchange exchange; DefaultBlockingHttpExchange(final HttpServerExchange exchange) { this.exchange = exchange; } public InputStream getInputStream() { if (inputStream == null) { inputStream = new UndertowInputStream(exchange); } return inputStream; } public UndertowOutputStream getOutputStream() { if (outputStream == null) { outputStream = new UndertowOutputStream(exchange); } return outputStream; } @Override public Sender getSender() { if (sender == null) { sender = new BlockingSenderImpl(exchange, getOutputStream()); } return sender; } @Override public void close() throws IOException { try { getInputStream().close(); } finally { getOutputStream().close(); } } @Override public Receiver getReceiver() { return new BlockingReceiverImpl(exchange, getInputStream()); } } /** * Channel implementation that is actually provided to clients of the exchange. * <p> * We do not provide the underlying conduit channel, as this is shared between requests, so we need to make sure that after this request * is done the the channel cannot affect the next request. * <p> * It also delays a wakeup/resumesWrites calls until the current call stack has returned, thus ensuring that only 1 thread is * active in the exchange at any one time. */ private class WriteDispatchChannel extends DetachableStreamSinkChannel implements StreamSinkChannel { private boolean wakeup; WriteDispatchChannel(final ConduitStreamSinkChannel delegate) { super(delegate); } @Override protected boolean isFinished() { return allAreSet(state, FLAG_RESPONSE_TERMINATED); } @Override public void resumeWrites() { if (isInCall()) { state |= FLAG_SHOULD_RESUME_WRITES; if(anyAreSet(state, FLAG_DISPATCHED)) { throw UndertowMessages.MESSAGES.resumedAndDispatched(); } } else if(!isFinished()){ delegate.resumeWrites(); } } @Override public void suspendWrites() { state &= ~FLAG_SHOULD_RESUME_WRITES; super.suspendWrites(); } @Override public void wakeupWrites() { if (isFinished()) { return; } if (isInCall()) { wakeup = true; state |= FLAG_SHOULD_RESUME_WRITES; if(anyAreSet(state, FLAG_DISPATCHED)) { throw UndertowMessages.MESSAGES.resumedAndDispatched(); } } else { delegate.wakeupWrites(); } } @Override public boolean isWriteResumed() { return anyAreSet(state, FLAG_SHOULD_RESUME_WRITES) || super.isWriteResumed(); } public void runResume() { if (isWriteResumed()) { if(isFinished()) { invokeListener(); } else { if (wakeup) { wakeup = false; state &= ~FLAG_SHOULD_RESUME_WRITES; delegate.wakeupWrites(); } else { state &= ~FLAG_SHOULD_RESUME_WRITES; delegate.resumeWrites(); } } } else if(wakeup) { wakeup = false; invokeListener(); } } private void invokeListener() { if(writeSetter != null) { super.getIoThread().execute(new Runnable() { @Override public void run() { ChannelListeners.invokeChannelListener(WriteDispatchChannel.this, writeSetter.get()); } }); } } @Override public void awaitWritable() throws IOException { if(Thread.currentThread() == super.getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } super.awaitWritable(); } @Override public void awaitWritable(long time, TimeUnit timeUnit) throws IOException { if(Thread.currentThread() == super.getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } super.awaitWritable(time, timeUnit); } @Override public long transferFrom(FileChannel src, long position, long count) throws IOException { long l = super.transferFrom(src, position, count); if(l > 0) { responseBytesSent += l; } return l; } @Override public long transferFrom(StreamSourceChannel source, long count, ByteBuffer throughBuffer) throws IOException { long l = super.transferFrom(source, count, throughBuffer); if(l > 0) { responseBytesSent += l; } return l; } @Override public long write(ByteBuffer[] srcs, int offset, int length) throws IOException { long l = super.write(srcs, offset, length); responseBytesSent += l; return l; } @Override public long write(ByteBuffer[] srcs) throws IOException { long l = super.write(srcs); responseBytesSent += l; return l; } @Override public int writeFinal(ByteBuffer src) throws IOException { int l = super.writeFinal(src); responseBytesSent += l; return l; } @Override public long writeFinal(ByteBuffer[] srcs, int offset, int length) throws IOException { long l = super.writeFinal(srcs, offset, length); responseBytesSent += l; return l; } @Override public long writeFinal(ByteBuffer[] srcs) throws IOException { long l = super.writeFinal(srcs); responseBytesSent += l; return l; } @Override public int write(ByteBuffer src) throws IOException { int l = super.write(src); responseBytesSent += l; return l; } } /** * Channel implementation that is actually provided to clients of the exchange. We do not provide the underlying * conduit channel, as this will become the next requests conduit channel, so if a thread is still hanging onto this * exchange it can result in problems. * <p> * It also delays a readResume call until the current call stack has returned, thus ensuring that only 1 thread is * active in the exchange at any one time. * <p> * It also handles buffered request data. */ private final class ReadDispatchChannel extends DetachableStreamSourceChannel implements StreamSourceChannel { private boolean wakeup = true; private boolean readsResumed = false; ReadDispatchChannel(final ConduitStreamSourceChannel delegate) { super(delegate); } @Override protected boolean isFinished() { return allAreSet(state, FLAG_REQUEST_TERMINATED); } @Override public void resumeReads() { readsResumed = true; if (isInCall()) { state |= FLAG_SHOULD_RESUME_READS; if(anyAreSet(state, FLAG_DISPATCHED)) { throw UndertowMessages.MESSAGES.resumedAndDispatched(); } } else if (!isFinished()) { delegate.resumeReads(); } } public void wakeupReads() { if (isInCall()) { wakeup = true; state |= FLAG_SHOULD_RESUME_READS; if(anyAreSet(state, FLAG_DISPATCHED)) { throw UndertowMessages.MESSAGES.resumedAndDispatched(); } } else { if(isFinished()) { invokeListener(); } else { delegate.wakeupReads(); } } } private void invokeListener() { if(readSetter != null) { super.getIoThread().execute(new Runnable() { @Override public void run() { ChannelListeners.invokeChannelListener(ReadDispatchChannel.this, readSetter.get()); } }); } } public void requestDone() { if(delegate instanceof ConduitStreamSourceChannel) { ((ConduitStreamSourceChannel)delegate).setReadListener(null); ((ConduitStreamSourceChannel)delegate).setCloseListener(null); } else { delegate.getReadSetter().set(null); delegate.getCloseSetter().set(null); } } @Override public long transferTo(long position, long count, FileChannel target) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.transferTo(position, count, target); } return target.transferFrom(this, position, count); } @Override public void awaitReadable() throws IOException { if(Thread.currentThread() == super.getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { super.awaitReadable(); } } @Override public void suspendReads() { readsResumed = false; state &= ~(FLAG_SHOULD_RESUME_READS); super.suspendReads(); } @Override public long transferTo(long count, ByteBuffer throughBuffer, StreamSinkChannel target) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.transferTo(count, throughBuffer, target); } //make sure there is no garbage in throughBuffer throughBuffer.position(0); throughBuffer.limit(0); long copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { int res = target.write(buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (res == 0) { return copied; } else { copied += res; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.transferTo(count, throughBuffer, target); } else { return copied; } } @Override public void awaitReadable(long time, TimeUnit timeUnit) throws IOException { if(Thread.currentThread() == super.getIoThread()) { throw UndertowMessages.MESSAGES.awaitCalledFromIoThread(); } PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { super.awaitReadable(time, timeUnit); } } @Override public long read(ByteBuffer[] dsts, int offset, int length) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.read(dsts, offset, length); } long copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { copied += Buffers.copy(dsts, offset, length, buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (!Buffers.hasRemaining(dsts, offset, length)) { return copied; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.read(dsts, offset, length); } else { return copied; } } @Override public long read(ByteBuffer[] dsts) throws IOException { return read(dsts, 0, dsts.length); } @Override public boolean isOpen() { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered != null) { return true; } return super.isOpen(); } @Override public void close() throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered != null) { for (PooledByteBuffer pooled : buffered) { if (pooled != null) { pooled.close(); } } } removeAttachment(BUFFERED_REQUEST_DATA); super.close(); } @Override public boolean isReadResumed() { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered != null) { return readsResumed; } if(isFinished()) { return false; } return anyAreSet(state, FLAG_SHOULD_RESUME_READS) || super.isReadResumed(); } @Override public int read(ByteBuffer dst) throws IOException { PooledByteBuffer[] buffered = getAttachment(BUFFERED_REQUEST_DATA); if (buffered == null) { return super.read(dst); } int copied = 0; for (int i = 0; i < buffered.length; ++i) { PooledByteBuffer pooled = buffered[i]; if (pooled != null) { final ByteBuffer buf = pooled.getBuffer(); if (buf.hasRemaining()) { copied += Buffers.copy(dst, buf); if (!buf.hasRemaining()) { pooled.close(); buffered[i] = null; } if (!dst.hasRemaining()) { return copied; } } else { pooled.close(); buffered[i] = null; } } } removeAttachment(BUFFERED_REQUEST_DATA); if (copied == 0) { return super.read(dst); } else { return copied; } } public void runResume() { if (isReadResumed()) { if(isFinished()) { invokeListener(); } else { if (wakeup) { wakeup = false; state &= ~FLAG_SHOULD_RESUME_READS; delegate.wakeupReads(); } else { state &= ~FLAG_SHOULD_RESUME_READS; delegate.resumeReads(); } } } else if(wakeup) { wakeup = false; invokeListener(); } } } public static class WrapperStreamSinkConduitFactory implements ConduitFactory<StreamSinkConduit> { private final HttpServerExchange exchange; private final ConduitWrapper<StreamSinkConduit>[] wrappers; private int position; private final StreamSinkConduit first; public WrapperStreamSinkConduitFactory(ConduitWrapper<StreamSinkConduit>[] wrappers, int wrapperCount, HttpServerExchange exchange, StreamSinkConduit first) { this.wrappers = wrappers; this.exchange = exchange; this.first = first; this.position = wrapperCount - 1; } @Override public StreamSinkConduit create() { if (position == -1) { return exchange.getConnection().getSinkConduit(exchange, first); } else { return wrappers[position--].wrap(this, exchange); } } } public static class WrapperConduitFactory<T extends Conduit> implements ConduitFactory<T> { private final HttpServerExchange exchange; private final ConduitWrapper<T>[] wrappers; private int position; private T first; public WrapperConduitFactory(ConduitWrapper<T>[] wrappers, int wrapperCount, T first, HttpServerExchange exchange) { this.wrappers = wrappers; this.exchange = exchange; this.position = wrapperCount - 1; this.first = first; } @Override public T create() { if (position == -1) { return first; } else { return wrappers[position--].wrap(this, exchange); } } } @Override public String toString() { return "HttpServerExchange{ " + getRequestMethod().toString() + " " + getRequestURI() + '}'; } }
apache-2.0
MAtzmueller/Kadconia
src/de/dhbw/vote/VoteFragment.java
2268
package de.dhbw.vote; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import de.dhbw.navigation.R; /** * Created by Mark on 29.09.2016. */ public class VoteFragment extends Fragment { private Context mContext; private View mView; private WebView mWebView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { setHasOptionsMenu(true); mContext = getActivity(); mView = inflater.inflate(R.layout.fragment_vote, container, false); mWebView = (WebView) mView.findViewById(R.id.vote_webview); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.setWebViewClient(new VoteFragment.CustomWebViewClient()); mWebView.loadUrl("https://minecraft-server.eu/vote/index/2421"); return mView; } private class CustomWebViewClient extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { String voteName = PreferenceManager.getDefaultSharedPreferences(mContext).getString(getString(R.string.pref_vote_name_key),""); view.loadUrl("javascript:(function(){var id=setInterval(function(){if(document.getElementsByName('minecraftname').length>0){document.getElementsByName('minecraftname')[0].value='"+voteName+"';clearInterval(id);}},100);})()"); super.onPageFinished(view, url); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){ super.onReceivedError(view, errorCode, description, failingUrl); } } }
apache-2.0
tesshucom/subsonic-fx-player
subsonic-fx-player-impl/src/main/java/com/tesshu/subsonic/client/fx/view/Icon.java
1139
/** * Copyright © 2017 tesshu.com (webmaster@tesshu.com) * * 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.tesshu.subsonic.client.fx.view; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import javafx.scene.control.Label; import javafx.scene.control.Labeled; @Component @Scope("prototype") public class Icon extends Label implements ICustomComponent<Labeled> { public Icon(IconKey iconKey) { getStyleClass().add("icon"); setText(iconKey.value()); setTranslateY(-1); } @Override public Labeled getInstance() { return this; } }
apache-2.0
googleads/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/admanager/jaxws/v202111/CustomTargetingKey.java
6403
// Copyright 2021 Google LLC // // 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.api.ads.admanager.jaxws.v202111; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * * {@code CustomTargetingKey} represents a key used for custom targeting. * * * <p>Java class for CustomTargetingKey complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="CustomTargetingKey"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="id" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/> * &lt;element name="name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="displayName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="type" type="{https://www.google.com/apis/ads/publisher/v202111}CustomTargetingKey.Type" minOccurs="0"/> * &lt;element name="valueDeclarationType" type="{https://www.google.com/apis/ads/publisher/v202111}ValueDeclarationType" minOccurs="0"/> * &lt;element name="status" type="{https://www.google.com/apis/ads/publisher/v202111}CustomTargetingKey.Status" minOccurs="0"/> * &lt;element name="reportableType" type="{https://www.google.com/apis/ads/publisher/v202111}ReportableType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "CustomTargetingKey", propOrder = { "id", "name", "displayName", "type", "valueDeclarationType", "status", "reportableType" }) public class CustomTargetingKey { protected Long id; protected String name; protected String displayName; @XmlSchemaType(name = "string") protected CustomTargetingKeyType type; @XmlSchemaType(name = "string") protected ValueDeclarationType valueDeclarationType; @XmlSchemaType(name = "string") protected CustomTargetingKeyStatus status; @XmlSchemaType(name = "string") protected ReportableType reportableType; /** * Gets the value of the id property. * * @return * possible object is * {@link Long } * */ public Long getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link Long } * */ public void setId(Long value) { this.id = value; } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the displayName property. * * @return * possible object is * {@link String } * */ public String getDisplayName() { return displayName; } /** * Sets the value of the displayName property. * * @param value * allowed object is * {@link String } * */ public void setDisplayName(String value) { this.displayName = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link CustomTargetingKeyType } * */ public CustomTargetingKeyType getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link CustomTargetingKeyType } * */ public void setType(CustomTargetingKeyType value) { this.type = value; } /** * Gets the value of the valueDeclarationType property. * * @return * possible object is * {@link ValueDeclarationType } * */ public ValueDeclarationType getValueDeclarationType() { return valueDeclarationType; } /** * Sets the value of the valueDeclarationType property. * * @param value * allowed object is * {@link ValueDeclarationType } * */ public void setValueDeclarationType(ValueDeclarationType value) { this.valueDeclarationType = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link CustomTargetingKeyStatus } * */ public CustomTargetingKeyStatus getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link CustomTargetingKeyStatus } * */ public void setStatus(CustomTargetingKeyStatus value) { this.status = value; } /** * Gets the value of the reportableType property. * * @return * possible object is * {@link ReportableType } * */ public ReportableType getReportableType() { return reportableType; } /** * Sets the value of the reportableType property. * * @param value * allowed object is * {@link ReportableType } * */ public void setReportableType(ReportableType value) { this.reportableType = value; } }
apache-2.0
gavanx/pdflearn
pdfbox/src/main/java/org/apache/pdfbox/pdmodel/encryption/ProtectionPolicy.java
2116
/* * 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.pdfbox.pdmodel.encryption; /** * This class represents the protection policy to apply to a document. * <p> * Objects implementing this abstract class can be passed to the protect method of PDDocument * to protect a document. * * @author Benoit Guillon (benoit.guillon@snv.jussieu.fr) * @see org.apache.pdfbox.pdmodel.PDDocument#protect(ProtectionPolicy) */ public abstract class ProtectionPolicy { private static final int DEFAULT_KEY_LENGTH = 40; private int encryptionKeyLength = DEFAULT_KEY_LENGTH; /** * set the length in (bits) of the secret key that will be * used to encrypt document data. * The default value is 40 bits, which provides a low security level * but is compatible with old versions of Acrobat Reader. * * @param l the length in bits (must be 40, 128 or 256) */ public void setEncryptionKeyLength(int l) { if (l != 40 && l != 128 && l != 256) { throw new IllegalArgumentException("Invalid key length '" + l + "' value must be 40, 128 or 256!"); } encryptionKeyLength = l; } /** * Get the length of the secrete key that will be used to encrypt * document data. * * @return The length (in bits) of the encryption key. */ public int getEncryptionKeyLength() { return encryptionKeyLength; } }
apache-2.0
googleads/google-ads-java
google-ads-stubs-v9/src/main/java/com/google/ads/googleads/v9/resources/AssetGroupListingGroupFilterProto.java
17035
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v9/resources/asset_group_listing_group_filter.proto package com.google.ads.googleads.v9.resources; public final class AssetGroupListingGroupFilterProto { private AssetGroupListingGroupFilterProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v9_resources_AssetGroupListingGroupFilter_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v9_resources_AssetGroupListingGroupFilter_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBiddingCategory_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBiddingCategory_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBrand_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBrand_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductChannel_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductChannel_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCondition_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCondition_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCustomAttribute_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCustomAttribute_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductItemId_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductItemId_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductType_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductType_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\nHgoogle/ads/googleads/v9/resources/asse" + "t_group_listing_group_filter.proto\022!goog" + "le.ads.googleads.v9.resources\032Ogoogle/ad" + "s/googleads/v9/enums/listing_group_filte" + "r_bidding_category_level.proto\032Ogoogle/a" + "ds/googleads/v9/enums/listing_group_filt" + "er_custom_attribute_index.proto\032Hgoogle/" + "ads/googleads/v9/enums/listing_group_fil" + "ter_product_channel.proto\032Jgoogle/ads/go" + "ogleads/v9/enums/listing_group_filter_pr" + "oduct_condition.proto\032Kgoogle/ads/google" + "ads/v9/enums/listing_group_filter_produc" + "t_type_level.proto\032Bgoogle/ads/googleads" + "/v9/enums/listing_group_filter_type_enum" + ".proto\032Agoogle/ads/googleads/v9/enums/li" + "sting_group_filter_vertical.proto\032\037googl" + "e/api/field_behavior.proto\032\031google/api/r" + "esource.proto\032\034google/api/annotations.pr" + "oto\"\365\005\n\034AssetGroupListingGroupFilter\022T\n\r" + "resource_name\030\001 \001(\tB=\340A\005\372A7\n5googleads.g" + "oogleapis.com/AssetGroupListingGroupFilt" + "er\022@\n\013asset_group\030\002 \001(\tB+\340A\005\372A%\n#googlea" + "ds.googleapis.com/AssetGroup\022\017\n\002id\030\003 \001(\003" + "B\003\340A\003\022c\n\004type\030\004 \001(\0162P.google.ads.googlea" + "ds.v9.enums.ListingGroupFilterTypeEnum.L" + "istingGroupFilterTypeB\003\340A\005\022o\n\010vertical\030\005" + " \001(\0162X.google.ads.googleads.v9.enums.Lis" + "tingGroupFilterVerticalEnum.ListingGroup" + "FilterVerticalB\003\340A\005\022R\n\ncase_value\030\006 \001(\0132" + ">.google.ads.googleads.v9.resources.List" + "ingGroupFilterDimension\022b\n\033parent_listin" + "g_group_filter\030\007 \001(\tB=\340A\005\372A7\n5googleads." + "googleapis.com/AssetGroupListingGroupFil" + "ter:\235\001\352A\231\001\n5googleads.googleapis.com/Ass" + "etGroupListingGroupFilter\022`customers/{cu" + "stomer_id}/assetGroupListingGroupFilters" + "/{asset_group_id}~{listing_group_filter_" + "id}\"\271\r\n\033ListingGroupFilterDimension\022y\n\030p" + "roduct_bidding_category\030\001 \001(\0132U.google.a" + "ds.googleads.v9.resources.ListingGroupFi" + "lterDimension.ProductBiddingCategoryH\000\022d" + "\n\rproduct_brand\030\002 \001(\0132K.google.ads.googl" + "eads.v9.resources.ListingGroupFilterDime" + "nsion.ProductBrandH\000\022h\n\017product_channel\030" + "\003 \001(\0132M.google.ads.googleads.v9.resource" + "s.ListingGroupFilterDimension.ProductCha" + "nnelH\000\022l\n\021product_condition\030\004 \001(\0132O.goog" + "le.ads.googleads.v9.resources.ListingGro" + "upFilterDimension.ProductConditionH\000\022y\n\030" + "product_custom_attribute\030\005 \001(\0132U.google." + "ads.googleads.v9.resources.ListingGroupF" + "ilterDimension.ProductCustomAttributeH\000\022" + "g\n\017product_item_id\030\006 \001(\0132L.google.ads.go" + "ogleads.v9.resources.ListingGroupFilterD" + "imension.ProductItemIdH\000\022b\n\014product_type" + "\030\007 \001(\0132J.google.ads.googleads.v9.resourc" + "es.ListingGroupFilterDimension.ProductTy" + "peH\000\032\261\001\n\026ProductBiddingCategory\022\017\n\002id\030\001 " + "\001(\003H\000\210\001\001\022\177\n\005level\030\002 \001(\0162p.google.ads.goo" + "gleads.v9.enums.ListingGroupFilterBiddin" + "gCategoryLevelEnum.ListingGroupFilterBid" + "dingCategoryLevelB\005\n\003_id\032,\n\014ProductBrand" + "\022\022\n\005value\030\001 \001(\tH\000\210\001\001B\010\n\006_value\032\207\001\n\016Produ" + "ctChannel\022u\n\007channel\030\001 \001(\0162d.google.ads." + "googleads.v9.enums.ListingGroupFilterPro" + "ductChannelEnum.ListingGroupFilterProduc" + "tChannel\032\217\001\n\020ProductCondition\022{\n\tconditi" + "on\030\001 \001(\0162h.google.ads.googleads.v9.enums" + ".ListingGroupFilterProductConditionEnum." + "ListingGroupFilterProductCondition\032\267\001\n\026P" + "roductCustomAttribute\022\022\n\005value\030\001 \001(\tH\000\210\001" + "\001\022\177\n\005index\030\002 \001(\0162p.google.ads.googleads." + "v9.enums.ListingGroupFilterCustomAttribu" + "teIndexEnum.ListingGroupFilterCustomAttr" + "ibuteIndexB\010\n\006_value\032-\n\rProductItemId\022\022\n" + "\005value\030\001 \001(\tH\000\210\001\001B\010\n\006_value\032\244\001\n\013ProductT" + "ype\022\022\n\005value\030\001 \001(\tH\000\210\001\001\022w\n\005level\030\002 \001(\0162h" + ".google.ads.googleads.v9.enums.ListingGr" + "oupFilterProductTypeLevelEnum.ListingGro" + "upFilterProductTypeLevelB\010\n\006_valueB\013\n\tdi" + "mensionB\216\002\n%com.google.ads.googleads.v9." + "resourcesB!AssetGroupListingGroupFilterP" + "rotoP\001ZJgoogle.golang.org/genproto/googl" + "eapis/ads/googleads/v9/resources;resourc" + "es\242\002\003GAA\252\002!Google.Ads.GoogleAds.V9.Resou" + "rces\312\002!Google\\Ads\\GoogleAds\\V9\\Resources" + "\352\002%Google::Ads::GoogleAds::V9::Resources" + "b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.ads.googleads.v9.enums.ListingGroupFilterBiddingCategoryLevelProto.getDescriptor(), com.google.ads.googleads.v9.enums.ListingGroupFilterCustomAttributeIndexProto.getDescriptor(), com.google.ads.googleads.v9.enums.ListingGroupFilterProductChannelProto.getDescriptor(), com.google.ads.googleads.v9.enums.ListingGroupFilterProductConditionProto.getDescriptor(), com.google.ads.googleads.v9.enums.ListingGroupFilterProductTypeLevelProto.getDescriptor(), com.google.ads.googleads.v9.enums.ListingGroupFilterTypeEnumProto.getDescriptor(), com.google.ads.googleads.v9.enums.ListingGroupFilterVerticalProto.getDescriptor(), com.google.api.FieldBehaviorProto.getDescriptor(), com.google.api.ResourceProto.getDescriptor(), com.google.api.AnnotationsProto.getDescriptor(), }); internal_static_google_ads_googleads_v9_resources_AssetGroupListingGroupFilter_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_ads_googleads_v9_resources_AssetGroupListingGroupFilter_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v9_resources_AssetGroupListingGroupFilter_descriptor, new java.lang.String[] { "ResourceName", "AssetGroup", "Id", "Type", "Vertical", "CaseValue", "ParentListingGroupFilter", }); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor, new java.lang.String[] { "ProductBiddingCategory", "ProductBrand", "ProductChannel", "ProductCondition", "ProductCustomAttribute", "ProductItemId", "ProductType", "Dimension", }); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBiddingCategory_descriptor = internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor.getNestedTypes().get(0); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBiddingCategory_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBiddingCategory_descriptor, new java.lang.String[] { "Id", "Level", "Id", }); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBrand_descriptor = internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor.getNestedTypes().get(1); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBrand_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductBrand_descriptor, new java.lang.String[] { "Value", "Value", }); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductChannel_descriptor = internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor.getNestedTypes().get(2); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductChannel_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductChannel_descriptor, new java.lang.String[] { "Channel", }); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCondition_descriptor = internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor.getNestedTypes().get(3); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCondition_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCondition_descriptor, new java.lang.String[] { "Condition", }); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCustomAttribute_descriptor = internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor.getNestedTypes().get(4); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCustomAttribute_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductCustomAttribute_descriptor, new java.lang.String[] { "Value", "Index", "Value", }); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductItemId_descriptor = internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor.getNestedTypes().get(5); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductItemId_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductItemId_descriptor, new java.lang.String[] { "Value", "Value", }); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductType_descriptor = internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_descriptor.getNestedTypes().get(6); internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductType_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_ads_googleads_v9_resources_ListingGroupFilterDimension_ProductType_descriptor, new java.lang.String[] { "Value", "Level", "Value", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.FieldBehaviorProto.fieldBehavior); registry.add(com.google.api.ResourceProto.resource); registry.add(com.google.api.ResourceProto.resourceReference); com.google.protobuf.Descriptors.FileDescriptor .internalUpdateFileDescriptor(descriptor, registry); com.google.ads.googleads.v9.enums.ListingGroupFilterBiddingCategoryLevelProto.getDescriptor(); com.google.ads.googleads.v9.enums.ListingGroupFilterCustomAttributeIndexProto.getDescriptor(); com.google.ads.googleads.v9.enums.ListingGroupFilterProductChannelProto.getDescriptor(); com.google.ads.googleads.v9.enums.ListingGroupFilterProductConditionProto.getDescriptor(); com.google.ads.googleads.v9.enums.ListingGroupFilterProductTypeLevelProto.getDescriptor(); com.google.ads.googleads.v9.enums.ListingGroupFilterTypeEnumProto.getDescriptor(); com.google.ads.googleads.v9.enums.ListingGroupFilterVerticalProto.getDescriptor(); com.google.api.FieldBehaviorProto.getDescriptor(); com.google.api.ResourceProto.getDescriptor(); com.google.api.AnnotationsProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
apache-2.0
sothawo/taboo2
src/main/java/com/sothawo/taboo2/repository/BookmarkRepository.java
3647
/** * Copyright (c) 2015 sothawo * * http://www.sothawo.com */ package com.sothawo.taboo2.repository; import com.sothawo.taboo2.AlreadyExistsException; import com.sothawo.taboo2.Bookmark; import com.sothawo.taboo2.NotFoundException; import java.util.Collection; /** * Implementations of this interface store and retrieve Bookmarks. Extends AutoCloseable so it might be used in contexts * using this feature. * * @author P.J. Meisch (pj.meisch@sothawo.com). */ public interface BookmarkRepository extends AutoCloseable { // -------------------------- OTHER METHODS -------------------------- /** * creates a bookmark in the repository. * * @param bookmark * the new bookmark. must not have the id set * @return the created bookmark with it's id * @throws IllegalArgumentException * if the id is set in bookmark * @throws AlreadyExistsException * if a bookmark with the given url already exists */ Bookmark createBookmark(Bookmark bookmark); /** * deletes the bookmark with the given id. * * @param id * id of the bookmark to delete * @throws NotFoundException * if no bookmark is found for the given id */ void deleteBookmark(String id); /** * returns all bookmarks without their ids. * * @return the bookmarks */ Collection<Bookmark> dumpBookmarks(); /** * returns all bookmarks in the repository. * * @return the bookmarks */ Collection<Bookmark> getAllBookmarks(); /** * returns all tags that are stored in the repository. * * @return Collection of tags, may be emoty, not null */ Collection<String> getAllTags(); /** * returns the bookmark for the given id. * * @param id * id of the bookmark * @return the bookmark * @throws NotFoundException * if no bookmark is found for the given id */ Bookmark getBookmarkById(String id); /** * returns the bookmarks that contain the given string. The search must be case insensitive. * * @param s * the substring to search * @return the found bookmarks */ Collection<Bookmark> getBookmarksWithSearch(String s); /** * returns all bookmarks that have all of the given tags. * * @param tags * the tags to be searched * @param opAnd * if true, the tags are to be combined using AND, otherwise OR * @return the found bookmarks */ Collection<Bookmark> getBookmarksWithTags(Collection<String> tags, boolean opAnd); /** * returns all bookmarks that have all of the given tags and that contain the given search string. * * @param tags * the tags to be searched * @param opAnd * if true, the tags are to be combined using AND, otherwise OR * @param s * the string to search for * @return the found bookmarks */ Collection<Bookmark> getBookmarksWithTagsAndSearch(Collection<String> tags, boolean opAnd, String s); /** * removes all bookmarks and tags from the repository. */ void purge(); /** * updates a bookmark. * * @param bookmark * the bookmark to update * @throws NullPointerException * when bookmark is null * @throws IllegalArgumentException * when the bookmark has no id * @throws NotFoundException * when no bookmark with the given id is found */ void updateBookmark(Bookmark bookmark); }
apache-2.0
yangfuhai/jboot
src/main/java/io/jboot/utils/NamedThreadPools.java
2088
/** * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com). * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.jboot.utils; import java.util.concurrent.*; /** * @author michael yang (fuhai999@gmail.com) * @Date: 2019/11/22 */ public class NamedThreadPools { public static ExecutorService newFixedThreadPool(int nThreads, String name) { return newFixedThreadPool(nThreads, new NamedThreadFactory(name)); } public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); } public static ExecutorService newCachedThreadPool(String name) { return newCachedThreadPool(new NamedThreadFactory(name)); } public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), threadFactory); } public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, String name) { return newScheduledThreadPool(corePoolSize, new NamedThreadFactory(name)); } public static ScheduledExecutorService newScheduledThreadPool( int corePoolSize, ThreadFactory threadFactory) { return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory); } }
apache-2.0
dubenju/javay
src/java/com/wavpack/encoder/BitsUtils.java
2571
/* ** BitsUtils.java ** ** Copyright (c) 2008 Peter McQuillan ** ** All Rights Reserved. ** ** Distributed under the BSD Software License (see license.txt) ** */ package com.wavpack.encoder; class BitsUtils { ////////////////////////// Bitstream functions //////////////////////////////// // Open the specified BitStream using the specified buffer pointers. It is // assumed that enough buffer space has been allocated for all data that will // be written, otherwise an error will be generated. static void bs_open_write(Bitstream bs, int buffer_start, int buffer_end) { bs.error = 0; bs.sr = 0; bs.bc = 0; bs.buf_index = buffer_start; bs.start_index = bs.buf_index; bs.end = (int) buffer_end; bs.active = 1; // indicates that the bitstream is being used } // This function is only called from the putbit() and putbits() when // the buffer is full, which is now flagged as an error. static void bs_wrap(Bitstream bs) { bs.buf_index = bs.start_index; bs.error = 1; } // This function calculates the approximate number of bytes remaining in the // bitstream buffer and can be used as an early-warning of an impending overflow. static long bs_remain_write(Bitstream bs) { long bytes_written; if (bs.error > 0) { return (long) -1; } return bs.end - bs.buf_index; } // This function forces a flushing write of the standard BitStream, and // returns the total number of bytes written into the buffer. static long bs_close_write(WavpackStream wps) { Bitstream bs = wps.wvbits; long bytes_written = 0; if (bs.error != 0) { return (long) -1; } while ((bs.bc != 0) || (((bs.buf_index - bs.start_index) & 1) != 0)) { WordsUtils.putbit_1(wps); } bytes_written = bs.buf_index - bs.start_index; return bytes_written; } // This function forces a flushing write of the correction BitStream, and // returns the total number of bytes written into the buffer. static long bs_close_correction_write(WavpackStream wps) { Bitstream bs = wps.wvcbits; long bytes_written = 0; if (bs.error != 0) { return (long) -1; } while ((bs.bc != 0) || (((bs.buf_index - bs.start_index) & 1) != 0)) { WordsUtils.putbit_correction_1(wps); } bytes_written = bs.buf_index - bs.start_index; return bytes_written; } }
apache-2.0
GerritCodeReview/gerrit-attic
src/main/java/com/google/gerrit/server/config/AuthConfig.java
5851
// Copyright (C) 2009 The Android Open Source Project // // 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.gerrit.server.config; import com.google.gerrit.client.reviewdb.AccountExternalId; import com.google.gerrit.client.reviewdb.AccountGroup; import com.google.gerrit.client.reviewdb.AuthType; import com.google.gerrit.client.reviewdb.SystemConfig; import com.google.gwtjsonrpc.server.SignedToken; import com.google.gwtjsonrpc.server.XsrfException; import com.google.inject.Inject; import com.google.inject.Singleton; import org.spearce.jgit.lib.Config; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** Authentication related settings from {@code gerrit.config}. */ @Singleton public class AuthConfig { private final AuthType authType; private final String httpHeader; private final String logoutUrl; private final String[] trusted; private final SignedToken emailReg; private final AccountGroup.Id administratorGroup; private final Set<AccountGroup.Id> anonymousGroups; private final Set<AccountGroup.Id> registeredGroups; private final boolean allowGoogleAccountUpgrade; @Inject AuthConfig(@GerritServerConfig final Config cfg, final SystemConfig s) throws XsrfException { authType = toType(cfg); httpHeader = cfg.getString("auth", null, "httpheader"); logoutUrl = cfg.getString("auth", null, "logouturl"); trusted = toTrusted(cfg); emailReg = new SignedToken(5 * 24 * 60 * 60, s.registerEmailPrivateKey); final HashSet<AccountGroup.Id> r = new HashSet<AccountGroup.Id>(2); r.add(s.anonymousGroupId); r.add(s.registeredGroupId); registeredGroups = Collections.unmodifiableSet(r); anonymousGroups = Collections.singleton(s.anonymousGroupId); administratorGroup = s.adminGroupId; if (authType == AuthType.OPENID) { allowGoogleAccountUpgrade = cfg.getBoolean("auth", "allowgoogleaccountupgrade", false); } else { allowGoogleAccountUpgrade = false; } } private String[] toTrusted(final Config cfg) { final String[] r = cfg.getStringList("auth", null, "trustedopenid"); if (r.length == 0) { return new String[] {"http://", "https://"}; } return r; } private static AuthType toType(final Config cfg) { if (isBecomeAnyoneEnabled()) { return AuthType.DEVELOPMENT_BECOME_ANY_ACCOUNT; } return ConfigUtil.getEnum(cfg, "auth", null, "type", AuthType.OPENID); } private static boolean isBecomeAnyoneEnabled() { try { String s = "com.google.gerrit.server.http.BecomeAnyAccountLoginServlet"; return Boolean.getBoolean(s); } catch (SecurityException se) { return false; } } /** Type of user authentication used by this Gerrit server. */ public AuthType getAuthType() { return authType; } public String getLoginHttpHeader() { return httpHeader; } public String getLogoutURL() { return logoutUrl; } public SignedToken getEmailRegistrationToken() { return emailReg; } public boolean isAllowGoogleAccountUpgrade() { return allowGoogleAccountUpgrade; } /** Identity of the magic group with full powers. */ public AccountGroup.Id getAdministratorsGroup() { return administratorGroup; } /** Groups that all users, including anonymous users, belong to. */ public Set<AccountGroup.Id> getAnonymousGroups() { return anonymousGroups; } /** Groups that all users who have created an account belong to. */ public Set<AccountGroup.Id> getRegisteredGroups() { return registeredGroups; } public boolean isIdentityTrustable(final Collection<AccountExternalId> ids) { switch (getAuthType()) { case DEVELOPMENT_BECOME_ANY_ACCOUNT: case HTTP: case HTTP_LDAP: // Its safe to assume yes for an HTTP authentication type, as the // only way in is through some external system that the admin trusts // return true; case OPENID: // All identities must be trusted in order to trust the account. // for (final AccountExternalId e : ids) { if (!isTrusted(e)) { return false; } } return true; default: // Assume not, we don't understand the login format. // return false; } } private boolean isTrusted(final AccountExternalId id) { if (id.isScheme(AccountExternalId.LEGACY_GAE)) { // Assume this is a trusted token, its a legacy import from // a fairly well respected provider and only takes effect if // the administrator has the import still enabled // return isAllowGoogleAccountUpgrade(); } if (id.isScheme(AccountExternalId.SCHEME_MAILTO)) { // mailto identities are created by sending a unique validation // token to the address and asking them to come back to the site // with that token. // return true; } for (final String p : trusted) { if (matches(p, id)) { return true; } } return false; } private boolean matches(final String p, final AccountExternalId id) { if (p.startsWith("^") && p.endsWith("$")) { return id.getExternalId().matches(p); } else { return id.getExternalId().startsWith(p); } } }
apache-2.0
wavelets/smile
SmileData/src/smile/data/AttributeDataset.java
1562
/****************************************************************************** * Confidential Proprietary * * (c) Copyright Haifeng Li 2011, All Rights Reserved * ******************************************************************************/ package smile.data; /** * A dataset of fixed number of attributes. All attribute values are stored as * double even if the attribute may be nominal, ordinal, string, or date. * The dataset is stored row-wise internally, which is fast for frequently * accessing instances of dataset. * * @author Haifeng Li */ public class AttributeDataset extends Dataset<double[]> { /** * The list of attributes. */ private Attribute[] attributes; /** * Constructor. * @param name the name of dataset. * @param attributes the list of attributes in this dataset. */ public AttributeDataset(String name, Attribute[] attributes) { super(name); this.attributes = attributes; } /** * Constructor. * @param name the name of dataset. * @param attributes the list of attributes in this dataset. * @param response the attribute of response variable. */ public AttributeDataset(String name, Attribute[] attributes, Attribute response) { super(name, response); this.attributes = attributes; } /** * Returns the list of attributes in this dataset. */ public Attribute[] attributes() { return attributes; } }
apache-2.0
jecuendet/maven4openxava
dist/openxava/workspace/OpenXavaTest/gen-src-xava/org/openxava/test/model/IReceptionist.java
967
// File generated by OpenXava: Wed Sep 11 11:56:52 CEST 2013 // Archivo generado por OpenXava: Wed Sep 11 11:56:52 CEST 2013 // WARNING: NO EDIT // OJO: NO EDITAR // Component: Customer Java interface for aggregate/Interfaz java para Agregado: Receptionist package org.openxava.test.model; import java.math.*; import java.rmi.RemoteException; public interface IReceptionist extends org.openxava.model.IModel { // Properties/Propiedades public static final String PROPERTY_oid = "oid"; int getOid() throws RemoteException; public static final String PROPERTY_name = "name"; String getName() throws RemoteException; void setName(String name) throws RemoteException; // References/Referencias // DeliveryPlace : Reference/Referencia org.openxava.test.model.IDeliveryPlace getDeliveryPlace() throws RemoteException; void setDeliveryPlace(org.openxava.test.model.IDeliveryPlace newDeliveryPlace) throws RemoteException; // Methods }
apache-2.0
Rowandjj/yitu
Yitu/src/cn/edu/chd/view/YiRotateMenu.java
4994
package cn.edu.chd.view; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.RelativeLayout; import cn.edu.chd.utils.YiAnimation; import cn.edu.chd.yitu.R; /** * @author Rowand jj * *¾ßÓз­×ªÐ§¹ûµÄ3¼¶²Ëµ¥ */ public class YiRotateMenu extends FrameLayout implements OnClickListener { private ImageButton home = null; private ImageButton second = null; private ImageButton second_left = null; private ImageButton second_right = null; private ImageButton third_1 = null; private ImageButton third_2 = null; private ImageButton third_3 = null; private ImageButton third_4 = null; private ImageButton third_5 = null; private ImageButton third_6 = null; private ImageButton third_7 = null; private boolean isLevel2Show = true; private boolean isLevel3Show = true; private RelativeLayout level2; private RelativeLayout level3; private boolean isEraserChecked = false; private boolean isBarrelChecked = false; /** * »Øµ÷½Ó¿Ú */ private OnMenuItemClickListener mListener = null; public YiRotateMenu(Context context, AttributeSet attrs) { this(context, attrs, 0); } public YiRotateMenu(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutInflater.from(context).inflate(R.layout.layout_rotate_menu, this); initComponent(); } /** * ³õʼ»¯¿Ø¼þ */ private void initComponent() { home = (ImageButton) findViewById(R.id.ib_home); second = (ImageButton) findViewById(R.id.second); second_left = (ImageButton) findViewById(R.id.second_left); second_right = (ImageButton) findViewById(R.id.second_right); third_1 = (ImageButton) findViewById(R.id.third_1); third_2 = (ImageButton) findViewById(R.id.third_2); third_3 = (ImageButton) findViewById(R.id.third_3); third_4 = (ImageButton) findViewById(R.id.third_4); third_5 = (ImageButton) findViewById(R.id.third_5); third_6 = (ImageButton) findViewById(R.id.third_6); third_7 = (ImageButton) findViewById(R.id.third_7); level2 = (RelativeLayout) findViewById(R.id.level2); level3 = (RelativeLayout) findViewById(R.id.level3); second_left.setOnClickListener(this); second_right.setOnClickListener(this); third_1.setOnClickListener(this); third_2.setOnClickListener(this); third_3.setOnClickListener(this); third_4.setOnClickListener(this); third_5.setOnClickListener(this); third_6.setOnClickListener(this); third_7.setOnClickListener(this); second.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (isLevel3Show) { // Òþ²Ø3¼¶µ¼º½²Ëµ¥ YiAnimation.startAnimationOUT(level3, 500, 0); } else { // ÏÔʾ3¼¶µ¼º½²Ëµ¥ YiAnimation.startAnimationIN(level3, 500); } isLevel3Show = !isLevel3Show; } }); home.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (!isLevel2Show) { // ÏÔʾ2¼¶µ¼º½²Ëµ¥ YiAnimation.startAnimationIN(level2, 500); } else { if (isLevel3Show) { // Òþ²Ø3¼¶µ¼º½²Ëµ¥ YiAnimation.startAnimationOUT(level3, 500, 0); // Òþ²Ø2¼¶µ¼º½²Ëµ¥ YiAnimation.startAnimationOUT(level2, 500, 500); isLevel3Show = !isLevel3Show; } else { // Òþ²Ø2¼¶µ¼º½²Ëµ¥ YiAnimation.startAnimationOUT(level2, 500, 0); } } isLevel2Show = !isLevel2Show; } }); } @Override public void onClick(View v) { if(mListener != null) { mListener.OnItemClick(v); } switch (v.getId()) { case R.id.third_4://Ìî³ä if(!isBarrelChecked) { third_4.setBackgroundResource(R.drawable.barrel_checked); if(isEraserChecked) { third_5.setBackgroundResource(R.drawable.eraser); isEraserChecked = false; } } else { third_4.setBackgroundResource(R.drawable.barrel); } isBarrelChecked = !isBarrelChecked; break; case R.id.third_5://ÏðÆ¤ if(!isEraserChecked) { third_5.setBackgroundResource(R.drawable.eraser_checked); if(isBarrelChecked) { third_4.setBackgroundResource(R.drawable.barrel); isBarrelChecked = false; } } else { third_5.setBackgroundResource(R.drawable.eraser); } isEraserChecked = !isEraserChecked; break; default: break; } } /** * ÉèÖûص÷½Ó¿Ú */ public void setOnMenuItemClickListener(OnMenuItemClickListener mListener) { this.mListener = mListener; } /** * *²Ëµ¥Ïî±»µã»÷Ëù´¥·¢µÄ»Øµ÷½Ó¿Ú */ public interface OnMenuItemClickListener { public void OnItemClick(View view); } }
apache-2.0
readymanong/ZhbitAPP
app/src/main/java/com/example/dm/zhbit/me/MeSettingsAty.java
3086
package com.example.dm.zhbit.me; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.dm.zhbit.R; import com.example.dm.zhbit.beans.AppUser; import com.example.dm.zhbit.main.MainActivity; import cn.bmob.v3.BmobUser; /** * 个人设置 */ public class MeSettingsAty extends Activity { private ImageButton titleLeftImv; private TextView titleTv; private Button logoutBtn; private RelativeLayout mAboutRout; private AppUser appUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.me_settings_layout); initView(); eventsDeal(); } private void initView() { titleLeftImv = (ImageButton) findViewById(R.id.me_settings_title).findViewById(R.id.title_imv); titleTv = (TextView) findViewById(R.id.me_settings_title).findViewById(R.id.title_center_text_tv); mAboutRout = (RelativeLayout) findViewById(R.id.settings_about_rout); logoutBtn = (Button) findViewById(R.id.settings_logout_btn); titleTv.setText("个人设置"); titleLeftImv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MeSettingsAty.this.finish(); } }); appUser = BmobUser.getCurrentUser(AppUser.class); if (appUser == null) { logoutBtn.setBackgroundColor(Color.parseColor("#616161")); logoutBtn.setClickable(false); } } private void eventsDeal() { logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (appUser != null) { final AlertDialog.Builder builder = new AlertDialog.Builder(MeSettingsAty.this); builder.setMessage("确定要退出当前账户吗?"); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AppUser.logOut(); startActivity(new Intent(MeSettingsAty.this, MainActivity.class)); MeSettingsAty.this.finish(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } } }); } }
apache-2.0
elasticsoftwarefoundation/elasticactors
main/core/src/main/java/org/elasticsoftware/elasticactors/util/concurrent/metrics/TraceThreadBoundRunnable.java
2449
/* * Copyright 2013 - 2022 The Original 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 org.elasticsoftware.elasticactors.util.concurrent.metrics; import org.elasticsoftware.elasticactors.tracing.CreationContext; import org.elasticsoftware.elasticactors.tracing.MessagingContextManager.MessagingScope; import org.elasticsoftware.elasticactors.tracing.TraceContext; import org.elasticsoftware.elasticactors.util.concurrent.ThreadBoundRunnable; import org.elasticsoftware.elasticactors.util.concurrent.WrapperThreadBoundRunnable; import javax.annotation.Nonnull; import static org.elasticsoftware.elasticactors.tracing.MessagingContextManager.getManager; final class TraceThreadBoundRunnable<T> implements WrapperThreadBoundRunnable<T> { private final ThreadBoundRunnable<T> delegate; private final TraceContext parent; private final CreationContext creationContext; static <T> TraceThreadBoundRunnable<T> wrap(@Nonnull ThreadBoundRunnable<T> delegate) { if (delegate instanceof TraceThreadBoundRunnable) { return (TraceThreadBoundRunnable<T>) delegate; } return new TraceThreadBoundRunnable<>(delegate); } private TraceThreadBoundRunnable(@Nonnull ThreadBoundRunnable<T> delegate) { this.delegate = delegate; MessagingScope scope = getManager().currentScope(); this.parent = scope != null ? scope.getTraceContext() : null; this.creationContext = scope != null ? scope.creationContextFromScope() : null; } @Override public void run() { try (MessagingScope ignored = getManager().enter(new TraceContext(parent), creationContext)) { this.delegate.run(); } } @Override public T getKey() { return delegate.getKey(); } @Nonnull @Override public ThreadBoundRunnable<T> getWrappedRunnable() { return delegate; } }
apache-2.0
e-biz/gatling-liferay
src/main/java/io/gatling/liferay/service/base/UrlRecordLocalServiceClpInvoker.java
11583
/** * Copyright 2011-2016 GatlingCorp (http://gatling.io) * * 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 io.gatling.liferay.service.base; import io.gatling.liferay.service.UrlRecordLocalServiceUtil; import java.util.Arrays; /** * @author Brian Wing Shun Chan * @generated */ public class UrlRecordLocalServiceClpInvoker { private String _methodName0; private String[] _methodParameterTypes0; private String _methodName1; private String[] _methodParameterTypes1; private String _methodName2; private String[] _methodParameterTypes2; private String _methodName3; private String[] _methodParameterTypes3; private String _methodName4; private String[] _methodParameterTypes4; private String _methodName5; private String[] _methodParameterTypes5; private String _methodName6; private String[] _methodParameterTypes6; private String _methodName7; private String[] _methodParameterTypes7; private String _methodName8; private String[] _methodParameterTypes8; private String _methodName9; private String[] _methodParameterTypes9; private String _methodName10; private String[] _methodParameterTypes10; private String _methodName11; private String[] _methodParameterTypes11; private String _methodName12; private String[] _methodParameterTypes12; private String _methodName13; private String[] _methodParameterTypes13; private String _methodName14; private String[] _methodParameterTypes14; private String _methodName15; private String[] _methodParameterTypes15; private String _methodName68; private String[] _methodParameterTypes68; private String _methodName69; private String[] _methodParameterTypes69; private String _methodName74; private String[] _methodParameterTypes74; private String _methodName75; private String[] _methodParameterTypes75; private String _methodName76; private String[] _methodParameterTypes76; private String _methodName77; private String[] _methodParameterTypes77; public UrlRecordLocalServiceClpInvoker() { _methodName0 = "addUrlRecord"; _methodParameterTypes0 = new String[] { "io.gatling.liferay.model.UrlRecord" }; _methodName1 = "createUrlRecord"; _methodParameterTypes1 = new String[] { "long" }; _methodName2 = "deleteUrlRecord"; _methodParameterTypes2 = new String[] { "long" }; _methodName3 = "deleteUrlRecord"; _methodParameterTypes3 = new String[] { "io.gatling.liferay.model.UrlRecord" }; _methodName4 = "dynamicQuery"; _methodParameterTypes4 = new String[] { }; _methodName5 = "dynamicQuery"; _methodParameterTypes5 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName6 = "dynamicQuery"; _methodParameterTypes6 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int" }; _methodName7 = "dynamicQuery"; _methodParameterTypes7 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "int", "int", "com.liferay.portal.kernel.util.OrderByComparator" }; _methodName8 = "dynamicQueryCount"; _methodParameterTypes8 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery" }; _methodName9 = "dynamicQueryCount"; _methodParameterTypes9 = new String[] { "com.liferay.portal.kernel.dao.orm.DynamicQuery", "com.liferay.portal.kernel.dao.orm.Projection" }; _methodName10 = "fetchUrlRecord"; _methodParameterTypes10 = new String[] { "long" }; _methodName11 = "getUrlRecord"; _methodParameterTypes11 = new String[] { "long" }; _methodName12 = "getPersistedModel"; _methodParameterTypes12 = new String[] { "java.io.Serializable" }; _methodName13 = "getUrlRecords"; _methodParameterTypes13 = new String[] { "int", "int" }; _methodName14 = "getUrlRecordsCount"; _methodParameterTypes14 = new String[] { }; _methodName15 = "updateUrlRecord"; _methodParameterTypes15 = new String[] { "io.gatling.liferay.model.UrlRecord" }; _methodName68 = "getBeanIdentifier"; _methodParameterTypes68 = new String[] { }; _methodName69 = "setBeanIdentifier"; _methodParameterTypes69 = new String[] { "java.lang.String" }; _methodName74 = "findByRecordId"; _methodParameterTypes74 = new String[] { "long" }; _methodName75 = "removeByRecordId"; _methodParameterTypes75 = new String[] { "long" }; _methodName76 = "countByRecordId"; _methodParameterTypes76 = new String[] { "long" }; _methodName77 = "save"; _methodParameterTypes77 = new String[] { "java.lang.String", "java.lang.String", "int", "long", "int" }; } public Object invokeMethod(String name, String[] parameterTypes, Object[] arguments) throws Throwable { if (_methodName0.equals(name) && Arrays.deepEquals(_methodParameterTypes0, parameterTypes)) { return UrlRecordLocalServiceUtil.addUrlRecord((io.gatling.liferay.model.UrlRecord) arguments[0]); } if (_methodName1.equals(name) && Arrays.deepEquals(_methodParameterTypes1, parameterTypes)) { return UrlRecordLocalServiceUtil.createUrlRecord(((Long) arguments[0]).longValue()); } if (_methodName2.equals(name) && Arrays.deepEquals(_methodParameterTypes2, parameterTypes)) { return UrlRecordLocalServiceUtil.deleteUrlRecord(((Long) arguments[0]).longValue()); } if (_methodName3.equals(name) && Arrays.deepEquals(_methodParameterTypes3, parameterTypes)) { return UrlRecordLocalServiceUtil.deleteUrlRecord((io.gatling.liferay.model.UrlRecord) arguments[0]); } if (_methodName4.equals(name) && Arrays.deepEquals(_methodParameterTypes4, parameterTypes)) { return UrlRecordLocalServiceUtil.dynamicQuery(); } if (_methodName5.equals(name) && Arrays.deepEquals(_methodParameterTypes5, parameterTypes)) { return UrlRecordLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery) arguments[0]); } if (_methodName6.equals(name) && Arrays.deepEquals(_methodParameterTypes6, parameterTypes)) { return UrlRecordLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery) arguments[0], ((Integer) arguments[1]).intValue(), ((Integer) arguments[2]).intValue()); } if (_methodName7.equals(name) && Arrays.deepEquals(_methodParameterTypes7, parameterTypes)) { return UrlRecordLocalServiceUtil.dynamicQuery((com.liferay.portal.kernel.dao.orm.DynamicQuery) arguments[0], ((Integer) arguments[1]).intValue(), ((Integer) arguments[2]).intValue(), (com.liferay.portal.kernel.util.OrderByComparator) arguments[3]); } if (_methodName8.equals(name) && Arrays.deepEquals(_methodParameterTypes8, parameterTypes)) { return UrlRecordLocalServiceUtil.dynamicQueryCount((com.liferay.portal.kernel.dao.orm.DynamicQuery) arguments[0]); } if (_methodName9.equals(name) && Arrays.deepEquals(_methodParameterTypes9, parameterTypes)) { return UrlRecordLocalServiceUtil.dynamicQueryCount((com.liferay.portal.kernel.dao.orm.DynamicQuery) arguments[0], (com.liferay.portal.kernel.dao.orm.Projection) arguments[1]); } if (_methodName10.equals(name) && Arrays.deepEquals(_methodParameterTypes10, parameterTypes)) { return UrlRecordLocalServiceUtil.fetchUrlRecord(((Long) arguments[0]).longValue()); } if (_methodName11.equals(name) && Arrays.deepEquals(_methodParameterTypes11, parameterTypes)) { return UrlRecordLocalServiceUtil.getUrlRecord(((Long) arguments[0]).longValue()); } if (_methodName12.equals(name) && Arrays.deepEquals(_methodParameterTypes12, parameterTypes)) { return UrlRecordLocalServiceUtil.getPersistedModel((java.io.Serializable) arguments[0]); } if (_methodName13.equals(name) && Arrays.deepEquals(_methodParameterTypes13, parameterTypes)) { return UrlRecordLocalServiceUtil.getUrlRecords(((Integer) arguments[0]).intValue(), ((Integer) arguments[1]).intValue()); } if (_methodName14.equals(name) && Arrays.deepEquals(_methodParameterTypes14, parameterTypes)) { return UrlRecordLocalServiceUtil.getUrlRecordsCount(); } if (_methodName15.equals(name) && Arrays.deepEquals(_methodParameterTypes15, parameterTypes)) { return UrlRecordLocalServiceUtil.updateUrlRecord((io.gatling.liferay.model.UrlRecord) arguments[0]); } if (_methodName68.equals(name) && Arrays.deepEquals(_methodParameterTypes68, parameterTypes)) { return UrlRecordLocalServiceUtil.getBeanIdentifier(); } if (_methodName69.equals(name) && Arrays.deepEquals(_methodParameterTypes69, parameterTypes)) { UrlRecordLocalServiceUtil.setBeanIdentifier((java.lang.String) arguments[0]); return null; } if (_methodName74.equals(name) && Arrays.deepEquals(_methodParameterTypes74, parameterTypes)) { return UrlRecordLocalServiceUtil.findByRecordId(((Long) arguments[0]).longValue()); } if (_methodName75.equals(name) && Arrays.deepEquals(_methodParameterTypes75, parameterTypes)) { UrlRecordLocalServiceUtil.removeByRecordId(((Long) arguments[0]).longValue()); return null; } if (_methodName76.equals(name) && Arrays.deepEquals(_methodParameterTypes76, parameterTypes)) { return UrlRecordLocalServiceUtil.countByRecordId(((Long) arguments[0]).longValue()); } if (_methodName77.equals(name) && Arrays.deepEquals(_methodParameterTypes77, parameterTypes)) { return UrlRecordLocalServiceUtil.save((java.lang.String) arguments[0], (java.lang.String) arguments[1], ((Integer) arguments[2]).intValue(), ((Long) arguments[3]).longValue(), ((Integer) arguments[4]).intValue()); } throw new UnsupportedOperationException(); } }
apache-2.0
k4kentchow/qqmusic
src/com/bdqn/qqmusic/filter/CharaterEncodingFilter.java
827
package com.bdqn.qqmusic.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class CharaterEncodingFilter implements Filter { public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.setContentType("text/html;charset=UTF-8"); chain.doFilter(req, resp); } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
apache-2.0
BlueBrain/bluima
modules/bluima_xml/src/main/java/ch/epfl/bbp/uima/xml/archivearticle3/ConfNum.java
8375
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.12.14 at 03:30:44 PM CET // package ch.epfl.bbp.uima.xml.archivearticle3; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;element ref="{}email"/> * &lt;element ref="{}ext-link"/> * &lt;element ref="{}uri"/> * &lt;element ref="{}inline-supplementary-material"/> * &lt;element ref="{}related-article"/> * &lt;element ref="{}related-object"/> * &lt;element ref="{}hr"/> * &lt;element ref="{}bold"/> * &lt;element ref="{}italic"/> * &lt;element ref="{}monospace"/> * &lt;element ref="{}overline"/> * &lt;element ref="{}overline-start"/> * &lt;element ref="{}overline-end"/> * &lt;element ref="{}roman"/> * &lt;element ref="{}sans-serif"/> * &lt;element ref="{}sc"/> * &lt;element ref="{}strike"/> * &lt;element ref="{}underline"/> * &lt;element ref="{}underline-start"/> * &lt;element ref="{}underline-end"/> * &lt;element ref="{}alternatives"/> * &lt;element ref="{}inline-graphic"/> * &lt;element ref="{}private-char"/> * &lt;element ref="{}chem-struct"/> * &lt;element ref="{}inline-formula"/> * &lt;element ref="{}tex-math"/> * &lt;element ref="{http://www.w3.org/1998/Math/MathML}math"/> * &lt;element ref="{}abbrev"/> * &lt;element ref="{}milestone-end"/> * &lt;element ref="{}milestone-start"/> * &lt;element ref="{}named-content"/> * &lt;element ref="{}styled-content"/> * &lt;element ref="{}fn"/> * &lt;element ref="{}target"/> * &lt;element ref="{}xref"/> * &lt;element ref="{}sub"/> * &lt;element ref="{}sup"/> * &lt;element ref="{}x"/> * &lt;/choice> * &lt;attribute name="content-type" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "conf-num") public class ConfNum { @XmlElementRefs({ @XmlElementRef(name = "sans-serif", type = SansSerif.class), @XmlElementRef(name = "monospace", type = Monospace.class), @XmlElementRef(name = "ext-link", type = ExtLink.class), @XmlElementRef(name = "milestone-start", type = MilestoneStart.class), @XmlElementRef(name = "x", type = X.class), @XmlElementRef(name = "xref", type = Xref.class), @XmlElementRef(name = "roman", type = Roman.class), @XmlElementRef(name = "sup", type = Sup.class), @XmlElementRef(name = "italic", type = Italic.class), @XmlElementRef(name = "sc", type = Sc.class), @XmlElementRef(name = "underline-end", type = UnderlineEnd.class), @XmlElementRef(name = "related-object", type = RelatedObject.class), @XmlElementRef(name = "bold", type = Bold.class), @XmlElementRef(name = "private-char", type = PrivateChar.class), @XmlElementRef(name = "alternatives", type = Alternatives.class), @XmlElementRef(name = "inline-formula", type = InlineFormula.class), @XmlElementRef(name = "target", type = Target.class), @XmlElementRef(name = "overline-start", type = OverlineStart.class), @XmlElementRef(name = "related-article", type = RelatedArticle.class), @XmlElementRef(name = "styled-content", type = StyledContent.class), @XmlElementRef(name = "fn", type = Fn.class), @XmlElementRef(name = "strike", type = Strike.class), @XmlElementRef(name = "underline-start", type = UnderlineStart.class), @XmlElementRef(name = "sub", type = Sub.class), @XmlElementRef(name = "overline", type = Overline.class), @XmlElementRef(name = "milestone-end", type = MilestoneEnd.class), @XmlElementRef(name = "named-content", type = NamedContent.class), @XmlElementRef(name = "inline-graphic", type = InlineGraphic.class), @XmlElementRef(name = "tex-math", type = TexMath.class), @XmlElementRef(name = "hr", type = Hr.class), @XmlElementRef(name = "chem-struct", type = ChemStruct.class), @XmlElementRef(name = "overline-end", type = OverlineEnd.class), @XmlElementRef(name = "inline-supplementary-material", type = InlineSupplementaryMaterial.class), @XmlElementRef(name = "abbrev", type = Abbrev.class), @XmlElementRef(name = "email", type = Email.class), @XmlElementRef(name = "math", namespace = "http://www.w3.org/1998/Math/MathML", type = JAXBElement.class), @XmlElementRef(name = "underline", type = Underline.class), @XmlElementRef(name = "uri", type = Uri.class) }) @XmlMixed protected List<Object> content; @XmlAttribute(name = "content-type") @XmlSchemaType(name = "anySimpleType") protected String contentType; /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SansSerif } * {@link Monospace } * {@link ExtLink } * {@link MilestoneStart } * {@link Roman } * {@link Xref } * {@link X } * {@link Sup } * {@link Italic } * {@link UnderlineEnd } * {@link Sc } * {@link RelatedObject } * {@link Bold } * {@link PrivateChar } * {@link InlineFormula } * {@link Alternatives } * {@link Target } * {@link OverlineStart } * {@link RelatedArticle } * {@link StyledContent } * {@link Strike } * {@link Fn } * {@link UnderlineStart } * {@link Overline } * {@link Sub } * {@link MilestoneEnd } * {@link NamedContent } * {@link InlineGraphic } * {@link TexMath } * {@link Hr } * {@link ChemStruct } * {@link String } * {@link InlineSupplementaryMaterial } * {@link OverlineEnd } * {@link Email } * {@link Abbrev } * {@link JAXBElement }{@code <}{@link MathType }{@code >} * {@link Underline } * {@link Uri } * * */ public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } /** * Gets the value of the contentType property. * * @return * possible object is * {@link String } * */ public String getContentType() { return contentType; } /** * Sets the value of the contentType property. * * @param value * allowed object is * {@link String } * */ public void setContentType(String value) { this.contentType = value; } }
apache-2.0
google/framework-for-osdu
osdu-r2/os-workflow/workflow-core/src/main/java/org/opengroup/osdu/workflow/validation/ValidationServiceImpl.java
2221
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengroup.osdu.workflow.validation; import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.ConstraintViolationException; import javax.validation.Validator; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.opengroup.osdu.core.common.model.workflow.StartWorkflowRequest; import org.opengroup.osdu.workflow.model.GetStatusRequest; import org.opengroup.osdu.workflow.model.UpdateStatusRequest; import org.opengroup.osdu.workflow.provider.interfaces.IValidationService; import org.opengroup.osdu.workflow.validation.group.IValidationSequence; import org.springframework.stereotype.Service; @Service @Slf4j @RequiredArgsConstructor public class ValidationServiceImpl implements IValidationService { final Validator validator; @Override public void validateGetStatusRequest(GetStatusRequest request) { validate(request, "Invalid GetStatus request"); } @Override public void validateUpdateStatusRequest(UpdateStatusRequest request) { validate(request, "Invalid Update Workflow Status request"); } @Override public void validateStartWorkflowRequest(StartWorkflowRequest request) { validate(request, "Invalid StartWorkflowRequest"); } private <T> void validate(T value, String errorMsg) { Set<ConstraintViolation<T>> constraintViolations = validator.validate(value, IValidationSequence.class); if (CollectionUtils.isNotEmpty(constraintViolations)) { throw new ConstraintViolationException(errorMsg, constraintViolations); } } }
apache-2.0
unidal/cat
cat-home/src/main/java/com/dianping/cat/system/page/config/processor/DisplayConfigProcessor.java
1462
package com.dianping.cat.system.page.config.processor; import org.codehaus.plexus.util.StringUtils; import org.unidal.lookup.annotation.Inject; import com.dianping.cat.heartbeat.config.HeartbeatDisplayPolicyManager; import com.dianping.cat.report.page.activity.config.ActivityConfigManager; import com.dianping.cat.system.page.config.Action; import com.dianping.cat.system.page.config.Model; import com.dianping.cat.system.page.config.Payload; public class DisplayConfigProcessor { @Inject private HeartbeatDisplayPolicyManager m_displayPolicyManager; @Inject private ActivityConfigManager m_activityConfigManager; public void process(Action action, Payload payload, Model model) { switch (action) { case DISPLAY_POLICY: String displayPoicy = payload.getContent(); if (!StringUtils.isEmpty(displayPoicy)) { model.setOpState(m_displayPolicyManager.insert(displayPoicy)); } else { model.setOpState(true); } model.setContent(m_displayPolicyManager.getHeartbeatDisplayPolicy().toString()); break; case ACTIVITY_CONFIG_UPDATE: String activityConfig = payload.getContent(); if (!StringUtils.isEmpty(activityConfig)) { model.setOpState(m_activityConfigManager.insert(activityConfig)); } else { model.setOpState(true); } model.setContent(m_activityConfigManager.getActivityConfig().toString()); break; default: throw new RuntimeException("Error action name " + action.getName()); } } }
apache-2.0
bozimmerman/CoffeeMud
com/planet_ink/coffee_mud/Commands/Rebuke.java
4105
package com.planet_ink.coffee_mud.Commands; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.CMProps.Str; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2004-2022 Bo Zimmerman 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. */ public class Rebuke extends StdCommand { public Rebuke() { } private final String[] access=I(new String[]{"REBUKE"}); @Override public String[] getAccessWords() { return access; } @Override public boolean execute(final MOB mob, final List<String> commands, final int metaFlags) throws java.io.IOException { if(commands.size()<2) { mob.tell(L("Rebuke whom?")); return false; } final String str=CMParms.combine(commands,1); MOB target=mob.location().fetchInhabitant(str); if((target==null)&&(mob.charStats().getWorshipCharID().length()>0) &&(CMLib.english().containsString(mob.charStats().getWorshipCharID(),str))) target=CMLib.map().getDeity(str); if((target==null)&&(mob.getLiegeID().length()>0) &&(CMLib.english().containsString(mob.getLiegeID(),str))) target=CMLib.players().getLoadPlayer(mob.getLiegeID()); if((target==null)&&(mob.numFollowers()>0)) target=mob.fetchFollower(str); if(target==null) { mob.tell(L("You don't see anybody called '@x1' or you aren't serving '@x2'.",CMParms.combine(commands,1),CMParms.combine(commands,1))); return false; } final String requiredMask = CMParms.getParmStr(CMProps.getVar(Str.DEITYPOLICY), "REQUIREDMASK", "").trim(); if((requiredMask.length()==0) ||(CMLib.masking().maskCheck(requiredMask, mob, true))) { final boolean allowedForDeity=!CMParms.getParmBool(CMProps.getVar(Str.DEITYPOLICY), "NOREBUKE", false); if((!allowedForDeity)&&(target instanceof Deity)) { mob.tell(L("You are not permitted to rebuke a deity.")); return false; } } CMMsg msg=null; msg=CMClass.getMsg(mob,target,null,CMMsg.MSG_REBUKE,L("<S-NAME> rebuke(s) @x1.",target.Name())); if(mob.location().okMessage(mob,msg)) mob.location().send(mob,msg); if((target.amFollowing()==mob)&&(target.location()!=null)) { final Room R=target.location(); msg=CMClass.getMsg(target,target.amFollowing(),null,CMMsg.MSG_NOFOLLOW,L("<S-NAME> stop(s) following <T-NAMESELF>.")); // no room OKaffects, since the damn leader may not be here. if(target.okMessage(mob,msg)) R.send(mob,msg); } return false; } @Override public double combatActionsCost(final MOB mob, final List<String> cmds) { return CMProps.getCommandCombatActionCost(ID()); } @Override public double actionsCost(final MOB mob, final List<String> cmds) { return CMProps.getCommandActionCost(ID()); } @Override public boolean canBeOrdered() { return false; } }
apache-2.0
gdtlf/msg
msg-platform/src/main/java/com/tlf/msg/platform/domain/ConfigExample.java
29255
package com.tlf.msg.platform.domain; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ConfigExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; protected Integer begin; protected Integer end; protected Integer start; protected Integer rows; public ConfigExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } public void setBegin(Integer begin) { this.begin = begin; } public Integer getBegin() { return begin; } public void setEnd(Integer end) { this.end = end; } public Integer getEnd() { return end; } public void setStart(Integer start) { this.start = start; } public Integer getStart() { return start; } public void setRows(Integer rows) { this.rows = rows; } public Integer getRows() { return rows; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andEntityOidIsNull() { addCriterion("ENTITY_OID is null"); return (Criteria) this; } public Criteria andEntityOidIsNotNull() { addCriterion("ENTITY_OID is not null"); return (Criteria) this; } public Criteria andEntityOidEqualTo(Long value) { addCriterion("ENTITY_OID =", value, "entityOid"); return (Criteria) this; } public Criteria andEntityOidNotEqualTo(Long value) { addCriterion("ENTITY_OID <>", value, "entityOid"); return (Criteria) this; } public Criteria andEntityOidGreaterThan(Long value) { addCriterion("ENTITY_OID >", value, "entityOid"); return (Criteria) this; } public Criteria andEntityOidGreaterThanOrEqualTo(Long value) { addCriterion("ENTITY_OID >=", value, "entityOid"); return (Criteria) this; } public Criteria andEntityOidLessThan(Long value) { addCriterion("ENTITY_OID <", value, "entityOid"); return (Criteria) this; } public Criteria andEntityOidLessThanOrEqualTo(Long value) { addCriterion("ENTITY_OID <=", value, "entityOid"); return (Criteria) this; } public Criteria andEntityOidIn(List<Long> values) { addCriterion("ENTITY_OID in", values, "entityOid"); return (Criteria) this; } public Criteria andEntityOidNotIn(List<Long> values) { addCriterion("ENTITY_OID not in", values, "entityOid"); return (Criteria) this; } public Criteria andEntityOidBetween(Long value1, Long value2) { addCriterion("ENTITY_OID between", value1, value2, "entityOid"); return (Criteria) this; } public Criteria andEntityOidNotBetween(Long value1, Long value2) { addCriterion("ENTITY_OID not between", value1, value2, "entityOid"); return (Criteria) this; } public Criteria andConfigCodeIsNull() { addCriterion("CONFIG_CODE is null"); return (Criteria) this; } public Criteria andConfigCodeIsNotNull() { addCriterion("CONFIG_CODE is not null"); return (Criteria) this; } public Criteria andConfigCodeEqualTo(String value) { addCriterion("CONFIG_CODE =", value, "configCode"); return (Criteria) this; } public Criteria andConfigCodeNotEqualTo(String value) { addCriterion("CONFIG_CODE <>", value, "configCode"); return (Criteria) this; } public Criteria andConfigCodeGreaterThan(String value) { addCriterion("CONFIG_CODE >", value, "configCode"); return (Criteria) this; } public Criteria andConfigCodeGreaterThanOrEqualTo(String value) { addCriterion("CONFIG_CODE >=", value, "configCode"); return (Criteria) this; } public Criteria andConfigCodeLessThan(String value) { addCriterion("CONFIG_CODE <", value, "configCode"); return (Criteria) this; } public Criteria andConfigCodeLessThanOrEqualTo(String value) { addCriterion("CONFIG_CODE <=", value, "configCode"); return (Criteria) this; } public Criteria andConfigCodeLike(String value) { addCriterion("CONFIG_CODE like", value, "configCode"); return (Criteria) this; } public Criteria andConfigCodeNotLike(String value) { addCriterion("CONFIG_CODE not like", value, "configCode"); return (Criteria) this; } public Criteria andConfigCodeIn(List<String> values) { addCriterion("CONFIG_CODE in", values, "configCode"); return (Criteria) this; } public Criteria andConfigCodeNotIn(List<String> values) { addCriterion("CONFIG_CODE not in", values, "configCode"); return (Criteria) this; } public Criteria andConfigCodeBetween(String value1, String value2) { addCriterion("CONFIG_CODE between", value1, value2, "configCode"); return (Criteria) this; } public Criteria andConfigCodeNotBetween(String value1, String value2) { addCriterion("CONFIG_CODE not between", value1, value2, "configCode"); return (Criteria) this; } public Criteria andConfigNameIsNull() { addCriterion("CONFIG_NAME is null"); return (Criteria) this; } public Criteria andConfigNameIsNotNull() { addCriterion("CONFIG_NAME is not null"); return (Criteria) this; } public Criteria andConfigNameEqualTo(String value) { addCriterion("CONFIG_NAME =", value, "configName"); return (Criteria) this; } public Criteria andConfigNameNotEqualTo(String value) { addCriterion("CONFIG_NAME <>", value, "configName"); return (Criteria) this; } public Criteria andConfigNameGreaterThan(String value) { addCriterion("CONFIG_NAME >", value, "configName"); return (Criteria) this; } public Criteria andConfigNameGreaterThanOrEqualTo(String value) { addCriterion("CONFIG_NAME >=", value, "configName"); return (Criteria) this; } public Criteria andConfigNameLessThan(String value) { addCriterion("CONFIG_NAME <", value, "configName"); return (Criteria) this; } public Criteria andConfigNameLessThanOrEqualTo(String value) { addCriterion("CONFIG_NAME <=", value, "configName"); return (Criteria) this; } public Criteria andConfigNameLike(String value) { addCriterion("CONFIG_NAME like", value, "configName"); return (Criteria) this; } public Criteria andConfigNameNotLike(String value) { addCriterion("CONFIG_NAME not like", value, "configName"); return (Criteria) this; } public Criteria andConfigNameIn(List<String> values) { addCriterion("CONFIG_NAME in", values, "configName"); return (Criteria) this; } public Criteria andConfigNameNotIn(List<String> values) { addCriterion("CONFIG_NAME not in", values, "configName"); return (Criteria) this; } public Criteria andConfigNameBetween(String value1, String value2) { addCriterion("CONFIG_NAME between", value1, value2, "configName"); return (Criteria) this; } public Criteria andConfigNameNotBetween(String value1, String value2) { addCriterion("CONFIG_NAME not between", value1, value2, "configName"); return (Criteria) this; } public Criteria andConfigValueIsNull() { addCriterion("CONFIG_VALUE is null"); return (Criteria) this; } public Criteria andConfigValueIsNotNull() { addCriterion("CONFIG_VALUE is not null"); return (Criteria) this; } public Criteria andConfigValueEqualTo(String value) { addCriterion("CONFIG_VALUE =", value, "configValue"); return (Criteria) this; } public Criteria andConfigValueNotEqualTo(String value) { addCriterion("CONFIG_VALUE <>", value, "configValue"); return (Criteria) this; } public Criteria andConfigValueGreaterThan(String value) { addCriterion("CONFIG_VALUE >", value, "configValue"); return (Criteria) this; } public Criteria andConfigValueGreaterThanOrEqualTo(String value) { addCriterion("CONFIG_VALUE >=", value, "configValue"); return (Criteria) this; } public Criteria andConfigValueLessThan(String value) { addCriterion("CONFIG_VALUE <", value, "configValue"); return (Criteria) this; } public Criteria andConfigValueLessThanOrEqualTo(String value) { addCriterion("CONFIG_VALUE <=", value, "configValue"); return (Criteria) this; } public Criteria andConfigValueLike(String value) { addCriterion("CONFIG_VALUE like", value, "configValue"); return (Criteria) this; } public Criteria andConfigValueNotLike(String value) { addCriterion("CONFIG_VALUE not like", value, "configValue"); return (Criteria) this; } public Criteria andConfigValueIn(List<String> values) { addCriterion("CONFIG_VALUE in", values, "configValue"); return (Criteria) this; } public Criteria andConfigValueNotIn(List<String> values) { addCriterion("CONFIG_VALUE not in", values, "configValue"); return (Criteria) this; } public Criteria andConfigValueBetween(String value1, String value2) { addCriterion("CONFIG_VALUE between", value1, value2, "configValue"); return (Criteria) this; } public Criteria andConfigValueNotBetween(String value1, String value2) { addCriterion("CONFIG_VALUE not between", value1, value2, "configValue"); return (Criteria) this; } public Criteria andStatusIsNull() { addCriterion("STATUS is null"); return (Criteria) this; } public Criteria andStatusIsNotNull() { addCriterion("STATUS is not null"); return (Criteria) this; } public Criteria andStatusEqualTo(String value) { addCriterion("STATUS =", value, "status"); return (Criteria) this; } public Criteria andStatusNotEqualTo(String value) { addCriterion("STATUS <>", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThan(String value) { addCriterion("STATUS >", value, "status"); return (Criteria) this; } public Criteria andStatusGreaterThanOrEqualTo(String value) { addCriterion("STATUS >=", value, "status"); return (Criteria) this; } public Criteria andStatusLessThan(String value) { addCriterion("STATUS <", value, "status"); return (Criteria) this; } public Criteria andStatusLessThanOrEqualTo(String value) { addCriterion("STATUS <=", value, "status"); return (Criteria) this; } public Criteria andStatusLike(String value) { addCriterion("STATUS like", value, "status"); return (Criteria) this; } public Criteria andStatusNotLike(String value) { addCriterion("STATUS not like", value, "status"); return (Criteria) this; } public Criteria andStatusIn(List<String> values) { addCriterion("STATUS in", values, "status"); return (Criteria) this; } public Criteria andStatusNotIn(List<String> values) { addCriterion("STATUS not in", values, "status"); return (Criteria) this; } public Criteria andStatusBetween(String value1, String value2) { addCriterion("STATUS between", value1, value2, "status"); return (Criteria) this; } public Criteria andStatusNotBetween(String value1, String value2) { addCriterion("STATUS not between", value1, value2, "status"); return (Criteria) this; } public Criteria andCreatedByIsNull() { addCriterion("CREATED_BY is null"); return (Criteria) this; } public Criteria andCreatedByIsNotNull() { addCriterion("CREATED_BY is not null"); return (Criteria) this; } public Criteria andCreatedByEqualTo(String value) { addCriterion("CREATED_BY =", value, "createdBy"); return (Criteria) this; } public Criteria andCreatedByNotEqualTo(String value) { addCriterion("CREATED_BY <>", value, "createdBy"); return (Criteria) this; } public Criteria andCreatedByGreaterThan(String value) { addCriterion("CREATED_BY >", value, "createdBy"); return (Criteria) this; } public Criteria andCreatedByGreaterThanOrEqualTo(String value) { addCriterion("CREATED_BY >=", value, "createdBy"); return (Criteria) this; } public Criteria andCreatedByLessThan(String value) { addCriterion("CREATED_BY <", value, "createdBy"); return (Criteria) this; } public Criteria andCreatedByLessThanOrEqualTo(String value) { addCriterion("CREATED_BY <=", value, "createdBy"); return (Criteria) this; } public Criteria andCreatedByLike(String value) { addCriterion("CREATED_BY like", value, "createdBy"); return (Criteria) this; } public Criteria andCreatedByNotLike(String value) { addCriterion("CREATED_BY not like", value, "createdBy"); return (Criteria) this; } public Criteria andCreatedByIn(List<String> values) { addCriterion("CREATED_BY in", values, "createdBy"); return (Criteria) this; } public Criteria andCreatedByNotIn(List<String> values) { addCriterion("CREATED_BY not in", values, "createdBy"); return (Criteria) this; } public Criteria andCreatedByBetween(String value1, String value2) { addCriterion("CREATED_BY between", value1, value2, "createdBy"); return (Criteria) this; } public Criteria andCreatedByNotBetween(String value1, String value2) { addCriterion("CREATED_BY not between", value1, value2, "createdBy"); return (Criteria) this; } public Criteria andCreatedDateIsNull() { addCriterion("CREATED_DATE is null"); return (Criteria) this; } public Criteria andCreatedDateIsNotNull() { addCriterion("CREATED_DATE is not null"); return (Criteria) this; } public Criteria andCreatedDateEqualTo(Date value) { addCriterion("CREATED_DATE =", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateNotEqualTo(Date value) { addCriterion("CREATED_DATE <>", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateGreaterThan(Date value) { addCriterion("CREATED_DATE >", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateGreaterThanOrEqualTo(Date value) { addCriterion("CREATED_DATE >=", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateLessThan(Date value) { addCriterion("CREATED_DATE <", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateLessThanOrEqualTo(Date value) { addCriterion("CREATED_DATE <=", value, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateIn(List<Date> values) { addCriterion("CREATED_DATE in", values, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateNotIn(List<Date> values) { addCriterion("CREATED_DATE not in", values, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateBetween(Date value1, Date value2) { addCriterion("CREATED_DATE between", value1, value2, "createdDate"); return (Criteria) this; } public Criteria andCreatedDateNotBetween(Date value1, Date value2) { addCriterion("CREATED_DATE not between", value1, value2, "createdDate"); return (Criteria) this; } public Criteria andLastUpdByIsNull() { addCriterion("LAST_UPD_BY is null"); return (Criteria) this; } public Criteria andLastUpdByIsNotNull() { addCriterion("LAST_UPD_BY is not null"); return (Criteria) this; } public Criteria andLastUpdByEqualTo(String value) { addCriterion("LAST_UPD_BY =", value, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByNotEqualTo(String value) { addCriterion("LAST_UPD_BY <>", value, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByGreaterThan(String value) { addCriterion("LAST_UPD_BY >", value, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByGreaterThanOrEqualTo(String value) { addCriterion("LAST_UPD_BY >=", value, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByLessThan(String value) { addCriterion("LAST_UPD_BY <", value, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByLessThanOrEqualTo(String value) { addCriterion("LAST_UPD_BY <=", value, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByLike(String value) { addCriterion("LAST_UPD_BY like", value, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByNotLike(String value) { addCriterion("LAST_UPD_BY not like", value, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByIn(List<String> values) { addCriterion("LAST_UPD_BY in", values, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByNotIn(List<String> values) { addCriterion("LAST_UPD_BY not in", values, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByBetween(String value1, String value2) { addCriterion("LAST_UPD_BY between", value1, value2, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdByNotBetween(String value1, String value2) { addCriterion("LAST_UPD_BY not between", value1, value2, "lastUpdBy"); return (Criteria) this; } public Criteria andLastUpdDateIsNull() { addCriterion("LAST_UPD_DATE is null"); return (Criteria) this; } public Criteria andLastUpdDateIsNotNull() { addCriterion("LAST_UPD_DATE is not null"); return (Criteria) this; } public Criteria andLastUpdDateEqualTo(Date value) { addCriterion("LAST_UPD_DATE =", value, "lastUpdDate"); return (Criteria) this; } public Criteria andLastUpdDateNotEqualTo(Date value) { addCriterion("LAST_UPD_DATE <>", value, "lastUpdDate"); return (Criteria) this; } public Criteria andLastUpdDateGreaterThan(Date value) { addCriterion("LAST_UPD_DATE >", value, "lastUpdDate"); return (Criteria) this; } public Criteria andLastUpdDateGreaterThanOrEqualTo(Date value) { addCriterion("LAST_UPD_DATE >=", value, "lastUpdDate"); return (Criteria) this; } public Criteria andLastUpdDateLessThan(Date value) { addCriterion("LAST_UPD_DATE <", value, "lastUpdDate"); return (Criteria) this; } public Criteria andLastUpdDateLessThanOrEqualTo(Date value) { addCriterion("LAST_UPD_DATE <=", value, "lastUpdDate"); return (Criteria) this; } public Criteria andLastUpdDateIn(List<Date> values) { addCriterion("LAST_UPD_DATE in", values, "lastUpdDate"); return (Criteria) this; } public Criteria andLastUpdDateNotIn(List<Date> values) { addCriterion("LAST_UPD_DATE not in", values, "lastUpdDate"); return (Criteria) this; } public Criteria andLastUpdDateBetween(Date value1, Date value2) { addCriterion("LAST_UPD_DATE between", value1, value2, "lastUpdDate"); return (Criteria) this; } public Criteria andLastUpdDateNotBetween(Date value1, Date value2) { addCriterion("LAST_UPD_DATE not between", value1, value2, "lastUpdDate"); return (Criteria) this; } public Criteria andIsNull(String filed) { addCriterion(filed + " is null"); return (Criteria) this; } public Criteria andIsNotNull(String filed) { addCriterion(filed + " is not null"); return (Criteria) this; } public Criteria andEqualTo(String filed, String value) { addCriterion(filed + " =", value, filed); return (Criteria) this; } public Criteria andNotEqualTo(String filed, String value) { addCriterion(filed + " <>", value, filed); return (Criteria) this; } public Criteria andGreaterThan(String filed, String value) { addCriterion(filed + " > ", value, filed); return (Criteria) this; } public Criteria andGreaterThanOrEqualTo(String filed, String value) { addCriterion(filed + " >=", value, filed); return (Criteria) this; } public Criteria andLessThan(String filed, String value) { addCriterion(filed + " <", value, filed); return (Criteria) this; } public Criteria andLessThanOrEqualTo(String filed, String value) { addCriterion(filed + " <=", value, filed); return (Criteria) this; } public Criteria andIn(String filed, String value) { addCriterion(filed + " in", value, filed); return (Criteria) this; } public Criteria andNotIn(String filed, String value) { addCriterion(filed + " not in", value, filed); return (Criteria) this; } public Criteria andBetween(String filed, String value1, String value2) { addCriterion(filed + " between", value1, value2, filed); return (Criteria) this; } public Criteria andNotBetween(String filed, String value1, String value2) { addCriterion(filed + " not between", value1, value2, filed); return (Criteria) this; } public Criteria andLike(String filed, String value) { addCriterion(filed + " like", value, filed); return (Criteria) this; } public Criteria andNotLike(String filed, String value) { addCriterion(filed + " not like", value, filed); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private final String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private final String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
apache-2.0
Egorand/android-aop-analytics
app/src/androidTest/java/me/egorand/cats/server/ImgurApiServerTest.java
2209
/* * Copyright 2015 - 2016 Egor Andreevici * * 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 me.egorand.cats.server; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import me.egorand.cats.R; import me.egorand.cats.data.ImgurResponse; import me.egorand.cats.data.ImgurTag; import me.egorand.cats.rest.ImgurApiClient; import me.egorand.cats.rest.ImgurAuthRequestInterceptor; import retrofit.RestAdapter; import static org.assertj.core.api.Assertions.assertThat; @RunWith(AndroidJUnit4.class) public class ImgurApiServerTest { private static final String TAG_NAME = "cats"; private ImgurApiClient imgurApiClient; @Before public void setUp() { String clientId = InstrumentationRegistry.getTargetContext().getString(R.string.imgur_client_id); imgurApiClient = new RestAdapter.Builder() .setEndpoint(ImgurApiClient.ENDPOINT) .setRequestInterceptor(new ImgurAuthRequestInterceptor(clientId)) .setLogLevel(RestAdapter.LogLevel.FULL) .build() .create(ImgurApiClient.class); } @Test public void shouldLoadProperTagData() { ImgurResponse<ImgurTag> response = imgurApiClient.getTag(TAG_NAME).toBlocking().first(); assertThat(response.isSuccess()).isTrue(); assertThat(response.getData()).isNotNull(); ImgurTag tagData = response.getData(); assertThat(tagData.getName()).isEqualTo(TAG_NAME); assertThat(tagData.getItems()).isNotEmpty(); } }
apache-2.0
pCloud/pcloud-sdk-java
java-core/src/main/java/com/pcloud/sdk/internal/networking/serialization/UnmodifiableListTypeFactory.java
1870
/* * Copyright (c) 2017 pCloud AG * * 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.pcloud.sdk.internal.networking.serialization; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.Collections; import java.util.List; public class UnmodifiableListTypeFactory implements TypeAdapterFactory { @Override public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> tokenType) { final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, tokenType); return new TypeAdapter<T>() { @Override public void write(JsonWriter out, T value) throws IOException { delegate.write(out, value); } @SuppressWarnings("unchecked") @Override public T read(JsonReader arg0) throws IOException { T t = delegate.read(arg0); if (List.class.isAssignableFrom(tokenType.getRawType())) { List<?> list = (List<?>) t; return (T) Collections.unmodifiableList(list); } return t; } }; } }
apache-2.0
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/jdbc/ResultStreamProvider.java
312
package net.snowflake.client.jdbc; import java.io.InputStream; // Defines how the underlying data stream is to be fetched; i.e. // allows large resultset data to come from a different source public interface ResultStreamProvider { InputStream getInputStream(ChunkDownloadContext context) throws Exception; }
apache-2.0
dianaui/dianaui-universal
core/src/main/java/com/dianaui/universal/core/client/ui/Divider.java
1638
/* * #%L * Diana UI Core * %% * Copyright (C) 2014 Diana UI * %% * 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. * #L% */ package com.dianaui.universal.core.client.ui; import com.dianaui.universal.core.client.ui.base.HasResponsiveness; import com.dianaui.universal.core.client.ui.base.helper.StyleHelper; import com.dianaui.universal.core.client.ui.constants.DeviceSize; import com.dianaui.universal.core.client.ui.constants.Styles; import com.google.gwt.dom.client.Document; import com.google.gwt.user.client.ui.Widget; /** * Divider used within {@link DropDownMenu} between {@link AnchorListItem} elements. * * @author Sven Jacobs * @author Joshua Godi */ public class Divider extends Widget implements HasResponsiveness { public Divider() { setElement(Document.get().createLIElement()); setStyleName(Styles.DIVIDER); } @Override public void setVisibleOn(final DeviceSize deviceSize) { StyleHelper.setVisibleOn(this, deviceSize); } @Override public void setHiddenOn(final DeviceSize deviceSize) { StyleHelper.setHiddenOn(this, deviceSize); } }
apache-2.0
jentfoo/aws-sdk-java
aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/transform/DescribeIndexRequestProtocolMarshaller.java
2606
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.iot.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.iot.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * DescribeIndexRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DescribeIndexRequestProtocolMarshaller implements Marshaller<Request<DescribeIndexRequest>, DescribeIndexRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON).requestUri("/indices/{indexName}") .httpMethodName(HttpMethodName.GET).hasExplicitPayloadMember(false).hasPayloadMembers(false).serviceName("AWSIot").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public DescribeIndexRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<DescribeIndexRequest> marshall(DescribeIndexRequest describeIndexRequest) { if (describeIndexRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<DescribeIndexRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, describeIndexRequest); protocolMarshaller.startMarshalling(); DescribeIndexRequestMarshaller.getInstance().marshall(describeIndexRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
pojosontheweb/woko
core/src/main/java/woko/util/pexpressions/ExpressionTreeWalker.java
862
/* * Copyright 2001-2012 Remi Vankeisbelck * * 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 woko.util.pexpressions; public class ExpressionTreeWalker extends ExpressionNodeWalker { public void walk(ExpressionTree tree) { onTree(tree); walk(tree.getRoot()); } public void onTree(ExpressionTree tree) { } }
apache-2.0
BruceZu/KeepTry
bow/2-technical-and-design/jdk17/src/main/java/datetime/BetaInvites.java
4253
// Copyright 2021 The KeepTry Open Source Project // // 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 datetime; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.text.ParseException; import java.util.*; /* Question comes from https://www.1point3acres.com/bbs/thread-796230-1-1.html Exercise Date and Time operation with JDK 17 Date year month day Time: hour minutes second, million second `DateTimeFormatter.ofPattern(String)` // `f` `new SimpleDateFormat( String)` // `sf` The String e.g.: "yyyy-MM-dd+HH:mm:ss" y year M month m minute H hour 24 h hour 12 s second Date d=sf.part(String); d.setSeconds(0); // can change value LocalDateTime dtime = LocalDateTime.parse(string, f); // used for compare and diff if (a.isBefore(b)) ... Duration.between(a, dtime).toSeconds()); Date d=new Date(long_timestamp) Instant inst = Instant.ofEpochMilli(long_timestamp); LocalDateTime t = LocalDateTime.ofInstant(inst, TimeZone.getDefault().toZoneId()); */ /* logic - input is in ascending order by timestamp, not 2 line have the same timestamp - log line format: epoch timestamp(in second),event_type,user_email E.g.: 1623834502,invite_requested,john@gmail.com - bolt: in same minute >= 5 req - use the fist timestamp for "invite_requested" to calculate the average time - no duplicated timestamp for "invite_send" and "invite_activated" calculate the average and verify the time of "invite_requested" <"invite_send" < "invite_activated" 1m2s,send,john 1m3s,req,john 1m5s,activated,john 1m6s,req,john 1m6s,req,john 1m6s,req,john 1m6s,req,john 1m6s,req,john - user can activate their beta invite once Stripe has sent it to them. */ public class BetaInvites { Set<String> bolts = new HashSet<>(); Map<String, Long> ave; // User: <Date without second, req counts> Map<String, Map<Date, Integer>> detect = new HashMap<>(); Map<String, Long[]> status = new HashMap<>(); public void process_invites(int N, String csvfilepath) throws IOException { try (BufferedReader fb = Files.newBufferedReader(Paths.get(csvfilepath))) { String line; while ((line = fb.readLine()) != null && N-- > 0) { parseLog(line); } System.out.println(handle()); } catch (ParseException e) { e.printStackTrace(); } } private void parseLog(String log) throws ParseException { String[] l = log.split(","); long t = Long.valueOf(l[0]); String eventType = l[1], userId = l[2]; if (bolts.contains(userId)) return; status.putIfAbsent(userId, new Long[] {null, null, null}); if (eventType == "invite_requested") { Date d = new Date(t); d.setSeconds(0); if (!detect.containsKey(userId)) { detect.put(userId, new HashMap<>()); detect.get(userId).put(d, 1); } else { Map<Date, Integer> count = detect.get(userId); count.put(d, count.getOrDefault(d, 0) + 1); if (count.get(d) >= 5) bolts.add(userId); } if (status.get(userId)[0] != null) status.get(userId)[0] = t; } else if (eventType == "invite_send") { status.get(userId)[1] = t; } else if (eventType == "invite_activated") { Long a = status.get(userId)[0], b = status.get(userId)[1]; if (a != null && b != null && a < b && b < t) ave.put(userId, t - a); } } public String handle() throws ParseException { Long sum = 0l, count = 0l; for (Map.Entry<String, Long> e : ave.entrySet()) { if (bolts.contains(e.getKey())) continue; sum += e.getValue(); count++; } return bolts.size() + " " + sum / count; } }
apache-2.0
equella/Equella
Source/Plugins/Core/com.equella.admin/src/com/tle/admin/cal/CalConfigPanel.java
14814
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * The Apereo Foundation 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 com.tle.admin.cal; import com.dytech.edge.exceptions.BannedFileException; import com.dytech.gui.TableLayout; import com.dytech.gui.workers.GlassSwingWorker; import com.tle.admin.Driver; import com.tle.admin.gui.i18n.I18nTextArea; import com.tle.admin.itemdefinition.AbstractExtensionConfigPanel; import com.tle.beans.entity.itemdef.ItemDefinition; import com.tle.common.adminconsole.FileUploader; import com.tle.common.adminconsole.RemoteAdminService; import com.tle.common.applet.client.ClientService; import com.tle.common.applet.gui.JGroup; import com.tle.common.i18n.LangUtils; import com.tle.i18n.BundleCache; import java.awt.BorderLayout; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipInputStream; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.filechooser.FileFilter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @SuppressWarnings("nls") public class CalConfigPanel extends AbstractExtensionConfigPanel { private static final long serialVersionUID = 1L; private static final Log LOGGER = LogFactory.getLog(CalConfigPanel.class); private static final String FOLDER = "cal/"; private static final String KEY_ACTIVATION_ERROR = "com.tle.cal-ActivationError"; private static final String KEY_INACTIVE_ERROR = "com.tle.cal-InActiveError"; private static final String KEY_HAS_AGREEMENT = "com.tle.cal-HasAgreement"; private static final String KEY_AGREEMENT_FILENAME = "com.tle.cal-AgreementFile"; private static final String KEY_HAS_RESTRICTIVE_VALIDATION = "com.tle.cal-restrictiveValidation"; private static final String KEY_HAS_PERCOURSE_VALIDATION = "come.tle.cal-perCourseValidation"; private static final String KEY_USE_CITATION_AS_NAME = "com.tle.cal-useCitationAsName"; private static final String KEY_PERCENTAGE_REQUIREMENT = "com.tle.cal-percentageRequirement"; private String stagingId; private final I18nTextArea activationError; private final I18nTextArea inactiveError; private JGroup agreementGroup; private JTextField agreementField; private JSpinner percentageField; private JCheckBox restrictiveValidation; private final JCheckBox useCitationAsName; private final JCheckBox perCourseValidation; private RemoteAdminService adminService; public CalConfigPanel() { JLabel actErrLabel = new JLabel(getString("activationerror")); JLabel inactErrLabel = new JLabel(getString("inactiveerror")); JLabel percentageLabel = new JLabel(getString("percentagerequirement")); JLabel percentageSign = new JLabel("%"); activationError = new I18nTextArea(BundleCache.getLanguages()); inactiveError = new I18nTextArea(BundleCache.getLanguages()); restrictiveValidation = new JCheckBox(getString("restrictiveValidation")); useCitationAsName = new JCheckBox(getString("usecitationasname")); perCourseValidation = new JCheckBox(getString("perCourseValidation")); percentageField = new JSpinner(new SpinnerNumberModel(10.0d, 0d, 100.0d, 1d)); initUploadPanel(); final int labelHeight = actErrLabel.getPreferredSize().height; final int checkBoxHeight = restrictiveValidation.getPreferredSize().height; final int agreementGroupHeight = agreementGroup.getPreferredSize().height; final int percentageFieldHeight = (int) Math.ceil(percentageField.getPreferredSize().getHeight()); final int fillRow = 3; final int oneCell = 1; int row = 0; final int[] rows = { checkBoxHeight, percentageFieldHeight, labelHeight, TableLayout.FILL, 10, labelHeight, TableLayout.FILL, checkBoxHeight, checkBoxHeight, checkBoxHeight, agreementGroupHeight }; final int[] cols = { 50, 50, TableLayout.FILL, }; setLayout(new TableLayout(rows, cols, 5, 5)); add(percentageLabel, new Rectangle(0, row++, fillRow, 1)); // percentage row add(percentageField, new Rectangle(0, row, oneCell, 1)); add(percentageSign, new Rectangle(1, row++, oneCell, 1)); // activation error add(actErrLabel, new Rectangle(0, row++, fillRow, 1)); add(activationError, new Rectangle(0, row++, fillRow, 1)); row = row + 1; add(inactErrLabel, new Rectangle(0, row++, fillRow, 1)); add(inactiveError, new Rectangle(0, row++, fillRow, 1)); add(restrictiveValidation, new Rectangle(0, row++, fillRow, 1)); add(perCourseValidation, new Rectangle(0, row++, fillRow, 1)); add(useCitationAsName, new Rectangle(0, row++, fillRow, 1)); add(agreementGroup, new Rectangle(0, row++, fillRow, 1)); } private void initUploadPanel() { JLabel titleLabel = new JLabel(getString("agreement.instructions")); // $NON-NLS-1$ final JButton upload = new JButton(getString("agreement.upload")); // $NON-NLS-1$ upload.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { uploadFile(); } }); final JButton remove = new JButton(getString("agreement.remove")); // $NON-NLS-1$ remove.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { removeFile(); } }); agreementField = new JTextField(); agreementField.setEditable(false); int rows[] = new int[] { TableLayout.PREFERRED, TableLayout.PREFERRED, }; int cols[] = new int[] { TableLayout.FILL, upload.getPreferredSize().width, remove.getPreferredSize().width }; JPanel uploadPanel = new JPanel(new TableLayout(rows, cols)); uploadPanel.add(titleLabel, new Rectangle(0, 0, 3, 1)); uploadPanel.add(agreementField, new Rectangle(0, 1, 1, 1)); uploadPanel.add(upload, new Rectangle(1, 1, 1, 1)); uploadPanel.add(remove, new Rectangle(2, 1, 1, 1)); restrictiveValidation = new JCheckBox(getString("restrictiveValidation")); agreementGroup = new JGroup(getString("cal.agreement.requires")); // $NON-NLS-1$ agreementGroup.setInnerLayout(new BorderLayout()); agreementGroup.addInner(uploadPanel); agreementGroup.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean isSelected = agreementGroup.isSelected(); agreementField.setEnabled(isSelected); upload.setEnabled(isSelected); remove.setEnabled(isSelected); if (!isSelected) { removeFile(); } } }); } @Override public void setClientService(ClientService clientService) { super.setClientService(clientService); adminService = clientService.getService(RemoteAdminService.class); } @Override public void load(String stagingId, ItemDefinition itemdef) { this.stagingId = stagingId; Map<String, String> attributes = itemdef.getAttributes(); activationError.load(LangUtils.getBundleFromXmlString(attributes.get(KEY_ACTIVATION_ERROR))); inactiveError.load(LangUtils.getBundleFromXmlString(attributes.get(KEY_INACTIVE_ERROR))); agreementGroup.setSelected(Boolean.valueOf(attributes.get(KEY_HAS_AGREEMENT))); agreementField.setText(attributes.get(KEY_AGREEMENT_FILENAME)); double percentage = 10; if (attributes.get(KEY_PERCENTAGE_REQUIREMENT) != null) { percentage = Double.valueOf(attributes.get(KEY_PERCENTAGE_REQUIREMENT)); } percentageField.setValue(new Double(percentage)); restrictiveValidation.setSelected( Boolean.valueOf(attributes.get(KEY_HAS_RESTRICTIVE_VALIDATION))); useCitationAsName.setSelected(Boolean.valueOf(attributes.get(KEY_USE_CITATION_AS_NAME))); perCourseValidation.setSelected(Boolean.valueOf(attributes.get(KEY_HAS_PERCOURSE_VALIDATION))); } @Override public void save(ItemDefinition itemdef) { itemdef.setAttribute( KEY_ACTIVATION_ERROR, LangUtils.getBundleAsXmlString(activationError.save())); itemdef.setAttribute(KEY_INACTIVE_ERROR, LangUtils.getBundleAsXmlString(inactiveError.save())); itemdef.setAttribute(KEY_HAS_AGREEMENT, Boolean.toString(agreementGroup.isSelected())); itemdef.setAttribute( KEY_HAS_RESTRICTIVE_VALIDATION, Boolean.toString(restrictiveValidation.isSelected())); itemdef.setAttribute( KEY_USE_CITATION_AS_NAME, Boolean.toString(useCitationAsName.isSelected())); itemdef.setAttribute( KEY_HAS_PERCOURSE_VALIDATION, Boolean.toString(perCourseValidation.isSelected())); itemdef.setAttribute(KEY_AGREEMENT_FILENAME, agreementField.getText()); itemdef.setAttribute(KEY_PERCENTAGE_REQUIREMENT, percentageField.getValue().toString()); } void removeFile() { GlassSwingWorker<?> worker = new GlassSwingWorker<Object>() { @Override public Object construct() { adminService.removeFile(stagingId, FOLDER); return null; } @Override public void finished() { agreementField.setText(""); // $NON-NLS-1$ } @Override public void exception() { Exception ex = getException(); Driver.displayError(getComponent(), "displayTemplate/readingXSLT", ex); // $NON-NLS-1$ LOGGER.error("Error opening XSLT or clearing staging", ex); } }; worker.setComponent(this); worker.start(); } void uploadFile() { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter( new FileFilter() { @Override public String getDescription() { return getString("agreement.filefilter"); // $NON-NLS-1$ } @Override public boolean accept(File f) { if (f.isDirectory()) { return true; } String name = f.toString().toLowerCase(); return name.endsWith(".zip") || name.endsWith(".htm") || name.endsWith(".html") // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ || name.endsWith(".xsl") || name.endsWith(".xslt"); // $NON-NLS-1$ //$NON-NLS-2$ } }); final int returnVal = chooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File selectedFile = chooser.getSelectedFile(); if (selectedFile.getName().toLowerCase().endsWith(".zip")) // $NON-NLS-1$ { doZipUpload(selectedFile); } else { doSimpleUpload(selectedFile); } } } private void doZipUpload(final File file) { UploadWorker worker = new UploadWorker(file) { @Override protected String construct(InputStream in) throws IOException { String agreementName = null; ZipEntry entry; ZipInputStream zin = new ZipInputStream(in); while ((entry = zin.getNextEntry()) != null) { if (!entry.isDirectory()) { String name = FOLDER + entry.getName(); if (name.endsWith(".htm") || name.endsWith(".html") // $NON-NLS-1$ //$NON-NLS-2$ || name.endsWith(".xsl") || name.endsWith(".xslt")) // $NON-NLS-1$ //$NON-NLS-2$ { agreementName = name; } FileUploader.upload(adminService, stagingId, name, zin); } zin.closeEntry(); } return agreementName; } }; worker.start(); } private void doSimpleUpload(final File file) { UploadWorker worker = new UploadWorker(file) { @Override public String construct(InputStream in) throws IOException { String name = FOLDER + file.getName(); FileUploader.upload(adminService, stagingId, name, in); return name; } }; worker.start(); } private abstract class UploadWorker extends GlassSwingWorker<String> { private final File file; public UploadWorker(File file) { this.file = file; setComponent(CalConfigPanel.this); } protected abstract String construct(InputStream in) throws IOException; @Override public final String construct() throws IOException { try (InputStream in = new BufferedInputStream(new FileInputStream(file))) { adminService.removeFile(stagingId, FOLDER); return construct(in); } } @Override public final void finished() { agreementField.setText(get()); } @Override public final void exception() { Exception ex = getException(); if (ex instanceof BannedFileException) { Driver.displayInformation( getComponent(), "File upload cancelled. File extension has been banned."); } else if (ex instanceof FileNotFoundException) { Driver.displayError(getComponent(), "displayTemplate/readingXSLT", ex); // $NON-NLS-1$ LOGGER.error("Error opening XSLT or clearing staging", ex); } else if (ex instanceof ZipException) { Driver.displayError(getComponent(), "displayTemplate/unzippingXSLT", ex); // $NON-NLS-1$ LOGGER.error("Error unzippig XSLT", ex); } else { Driver.displayError(getComponent(), "displayTemplate/uploadingXSLT", ex); // $NON-NLS-1$ LOGGER.error("Error uploading XSLT", ex); } } } }
apache-2.0
talsma-ict/umldoclet
src/plantuml-asl/src/net/sourceforge/plantuml/salt/factory/ElementFactoryButton.java
2277
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2020, Arnaud Roques * * Project Info: https://plantuml.com * * If you like this project or if you find it useful, you can support us at: * * https://plantuml.com/patreon (only 1$ per month!) * https://plantuml.com/paypal * * This file is part of PlantUML. * * 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. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.salt.factory; import net.sourceforge.plantuml.ISkinSimple; import net.sourceforge.plantuml.salt.DataSource; import net.sourceforge.plantuml.salt.Terminated; import net.sourceforge.plantuml.salt.element.Element; import net.sourceforge.plantuml.salt.element.ElementButton; import net.sourceforge.plantuml.ugraphic.UFont; public class ElementFactoryButton implements ElementFactory { final private DataSource dataSource; final private ISkinSimple spriteContainer; public ElementFactoryButton(DataSource dataSource, ISkinSimple spriteContainer) { this.dataSource = dataSource; this.spriteContainer = spriteContainer; } public Terminated<Element> create() { if (ready() == false) { throw new IllegalStateException(); } final Terminated<String> next = dataSource.next(); final String text = next.getElement(); final UFont font = UFont.byDefault(12); return new Terminated<Element>(new ElementButton(text.substring(1, text.length() - 1), font, spriteContainer), next.getTerminator()); } public boolean ready() { final String text = dataSource.peek(0).getElement(); return text.startsWith("[") && text.endsWith("]"); } }
apache-2.0
rvais/xmvn
xmvn-tools/xmvn-install/src/test/java/org/fedoraproject/xmvn/repository/impl/LayoutTest.java
3720
/*- * Copyright (c) 2012-2017 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fedoraproject.xmvn.repository.impl; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.nio.file.Path; import java.util.Properties; import org.junit.Before; import org.junit.Test; import org.fedoraproject.xmvn.artifact.Artifact; import org.fedoraproject.xmvn.artifact.DefaultArtifact; import org.fedoraproject.xmvn.repository.ArtifactContext; import org.fedoraproject.xmvn.repository.Repository; /** * @author Mikolaj Izdebski */ public class LayoutTest { private Repository mavenRepository; private Repository jppRepository; @Before public void setUp() throws Exception { mavenRepository = new MavenRepositoryFactory().getInstance( null, new Properties(), null ); jppRepository = new JppRepositoryFactory().getInstance( null, new Properties(), null ); assertNotNull( mavenRepository ); assertNotNull( jppRepository ); } private void testPaths( Repository repository, Artifact artifact, String expected ) { ArtifactContext context = new ArtifactContext( artifact ); Path repoPath = repository.getPrimaryArtifactPath( artifact, context, artifact.getGroupId() + "/" + artifact.getArtifactId() ); if ( expected == null ) { assertNull( repoPath ); } else { assertNotNull( repoPath ); assertNotNull( repoPath ); assertEquals( expected, repoPath.toString() ); } } /** * Test layout objects. * * @throws Exception */ @Test public void testLayouts() throws Exception { Artifact artifact = new DefaultArtifact( "an-example.artifact:used-FOR42.testing:ext-ens.ion:blah-1.2.3-foo" ); testPaths( mavenRepository, artifact, "an-example/artifact/used-FOR42.testing/blah-1.2.3-foo/used-FOR42.testing-blah-1.2.3-foo.ext-ens.ion" ); testPaths( mavenRepository, artifact.setVersion( "SYSTEM" ), null ); testPaths( jppRepository, artifact, "an-example.artifact/used-FOR42.testing-blah-1.2.3-foo.ext-ens.ion" ); testPaths( jppRepository, artifact.setVersion( "SYSTEM" ), "an-example.artifact/used-FOR42.testing.ext-ens.ion" ); } /** * Test is JPP prefixes in groupId are handled correctly. * * @throws Exception */ @Test public void testJppPrefixes() throws Exception { Artifact artifact1 = new DefaultArtifact( "JPP:testing:abc:1.2.3" ); Artifact artifact2 = new DefaultArtifact( "JPP/group:testing:abc:1.2.3" ); Artifact artifact3 = new DefaultArtifact( "JPP-group:testing:abc:1.2.3" ); testPaths( jppRepository, artifact1.setVersion( "SYSTEM" ), "testing.abc" ); testPaths( jppRepository, artifact2.setVersion( "SYSTEM" ), "group/testing.abc" ); testPaths( jppRepository, artifact3.setVersion( "SYSTEM" ), "JPP-group/testing.abc" ); } }
apache-2.0
mifos/1.5.x
application/src/main/java/org/mifos/accounts/productdefinition/business/service/ProductCategoryBusinessService.java
2741
/* * Copyright (c) 2005-2010 Grameen Foundation USA * All rights reserved. * * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.accounts.productdefinition.business.service; import java.util.List; import org.mifos.accounts.productdefinition.business.PrdCategoryStatusEntity; import org.mifos.accounts.productdefinition.business.ProductCategoryBO; import org.mifos.accounts.productdefinition.business.ProductTypeEntity; import org.mifos.accounts.productdefinition.persistence.ProductCategoryPersistence; import org.mifos.framework.business.BusinessObject; import org.mifos.framework.business.service.BusinessService; import org.mifos.framework.exceptions.PersistenceException; import org.mifos.framework.exceptions.ServiceException; import org.mifos.security.util.UserContext; public class ProductCategoryBusinessService implements BusinessService { @Override public BusinessObject getBusinessObject(UserContext userContext) { return null; } public List<ProductTypeEntity> getProductTypes() throws ServiceException { try { return new ProductCategoryPersistence().getProductTypes(); } catch (PersistenceException e) { throw new ServiceException(e); } } public ProductCategoryBO findByGlobalNum(String globalNum) throws ServiceException { try { return new ProductCategoryPersistence().findByGlobalNum(globalNum); } catch (PersistenceException e) { throw new ServiceException(e); } } public List<PrdCategoryStatusEntity> getProductCategoryStatusList() throws ServiceException { try { return new ProductCategoryPersistence().getProductCategoryStatusList(); } catch (PersistenceException e) { throw new ServiceException(e); } } public List<ProductCategoryBO> getAllCategories() throws ServiceException { try { return new ProductCategoryPersistence().getAllCategories(); } catch (PersistenceException e) { throw new ServiceException(e); } } }
apache-2.0
z123/datacollector
redis-lib/src/main/java/com/streamsets/pipeline/stage/destination/redis/RedisTargetConfig.java
3838
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.pipeline.stage.destination.redis; import com.streamsets.pipeline.api.ConfigDef; import com.streamsets.pipeline.api.ConfigDefBean; import com.streamsets.pipeline.api.ListBeanModel; import com.streamsets.pipeline.api.ValueChooserModel; import com.streamsets.pipeline.config.DataFormat; import com.streamsets.pipeline.lib.el.TimeEL; import com.streamsets.pipeline.stage.destination.lib.DataGeneratorFormatConfig; import java.util.List; public class RedisTargetConfig { public static final String REDIS_TARGET_CONFIG_PREFIX = "RedisTargetConfig."; @ConfigDef( required = true, type = ConfigDef.Type.STRING, label = "URI", description = "Use format redis://[:password@]host:port[/[database]]", displayPosition = 10, group = "REDIS" ) public String uri = "redis://:password@localhost:6379/0"; @ConfigDef( type = ConfigDef.Type.NUMBER, label = "Connection Timeout (sec)", defaultValue = "60", required = true, min = 1, displayPosition = 20, group = "REDIS" ) public int connectionTimeout = 60; @ConfigDef( type = ConfigDef.Type.NUMBER, label = "Retry Attempts", defaultValue = "0", required = true, min = 0, displayPosition = 21, group = "REDIS" ) public int maxRetries = 0; @ConfigDef( type = ConfigDef.Type.NUMBER, label = "Max Batch Wait Time", defaultValue = "${5 * SECONDS}", required = true, elDefs = {TimeEL.class}, evaluation = ConfigDef.Evaluation.IMPLICIT, displayPosition = 22, group = "REDIS" ) public long maxBatchWaitTime; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, label = "Mode", description = "Whether to write the data in batches as key-value pairs or to publish the data as messages", defaultValue = "BATCH", displayPosition = 30, group = "REDIS" ) @ValueChooserModel(ModeTypeChooserValues.class) public ModeType mode = ModeType.BATCH; @ConfigDef( required = false, type = ConfigDef.Type.MODEL, defaultValue = "", label = "Fields", description = "Key names, their values and storage type", displayPosition = 40, group = "REDIS", dependsOn = "mode", triggeredByValue = {"BATCH"} ) @ListBeanModel public List<RedisFieldMappingConfig> redisFieldMapping; @ConfigDef( required = true, type = ConfigDef.Type.MODEL, label = "Data Format", defaultValue = "JSON", displayPosition = 1, group = "DATA_FORMAT", dependsOn = "mode", triggeredByValue = {"PUBLISH"} ) @ValueChooserModel(ProducerDataFormatChooserValues.class) public DataFormat dataFormat = DataFormat.JSON; @ConfigDef( required = false, type = ConfigDef.Type.LIST, defaultValue = "[]", label = "Channel", description = "Channel to publish the messages to", displayPosition = 50, group = "REDIS", dependsOn = "mode", triggeredByValue = {"PUBLISH"} ) public List<String> channel; @ConfigDefBean(groups = "REDIS") public DataGeneratorFormatConfig dataFormatConfig = new DataGeneratorFormatConfig(); }
apache-2.0
testory/testory
test/java/org/testory/TestThenReturnedObject.java
3481
package org.testory; import static java.lang.String.format; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static org.testory.Testory.thenReturned; import static org.testory.Testory.when; import static org.testory.common.Throwables.printStackTrace; import static org.testory.testing.Closures.returning; import static org.testory.testing.Closures.throwing; import static org.testory.testing.Fakes.newObject; import static org.testory.testing.Fakes.newThrowable; import org.junit.Before; import org.junit.Test; public class TestThenReturnedObject { private String name; private Object object, otherObject; private Throwable throwable; @Before public void before() { name = "name"; object = newObject("object"); otherObject = newObject("otherObject"); throwable = newThrowable("throwable"); } @Test public void asserts_returning_equal_object() { when(returning(newObject(name))); thenReturned(newObject(name)); } @Test public void asserts_returning_same_object() { when(returning(object)); thenReturned(object); } @Test public void asserts_returning_equal_primitive() { when(returning(4)); thenReturned(4); } @Test public void asserts_returning_equal_null() { when(returning(null)); thenReturned((Object) null); } @Test public void fails_returning_not_equal_object() { when(returning(otherObject)); try { thenReturned(object); fail(); } catch (TestoryAssertionError e) { assertEquals( format("\n" + " expected returned\n" + " %s\n" + " but returned\n" + " %s\n", object, otherObject), e.getMessage()); } } @Test public void fails_returning_not_equal_primitive() { when(returning(5)); try { thenReturned(4); fail(); } catch (TestoryAssertionError e) { assertEquals("\n" + " expected returned\n" + " 4\n" + " but returned\n" + " 5\n", e.getMessage()); } } @Test public void fails_returning_object_instead_of_null() { when(returning(object)); try { thenReturned(null); fail(); } catch (TestoryAssertionError e) { assertEquals( format("\n" + " expected returned\n" + " null\n" + " but returned\n" + " %s\n", object), e.getMessage()); } } @Test public void fails_returning_null_instead_of_object() { when(returning(null)); try { thenReturned(object); fail(); } catch (TestoryAssertionError e) { assertEquals( format("\n" + " expected returned\n" + " %s\n" + " but returned\n" + " null\n", object), e.getMessage()); } } @Test public void fails_throwing() { when(throwing(throwable)); try { thenReturned(object); fail(); } catch (TestoryAssertionError e) { assertEquals( format("\n" + " expected returned\n" + " %s\n" + " but thrown\n" + " %s\n" + "\n" + "%s", object, throwable, printStackTrace(throwable)), e.getMessage()); } } }
apache-2.0
DiceHoldingsInc/orientdb
graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientElement.java
18826
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com) * * * * 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. * * * * For more information: http://www.orientechnologies.com * */ package com.tinkerpop.blueprints.impls.orient; import com.orientechnologies.common.collection.OMultiValue; import com.orientechnologies.common.util.OCallable; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.record.OIdentifiable; import com.orientechnologies.orient.core.db.record.ORecordOperation; import com.orientechnologies.orient.core.exception.ORecordNotFoundException; import com.orientechnologies.orient.core.exception.OSchemaException; import com.orientechnologies.orient.core.exception.OSerializationException; import com.orientechnologies.orient.core.id.ORID; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OSchema; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.record.impl.ORecordBytes; import com.orientechnologies.orient.core.serialization.OSerializableStream; import com.orientechnologies.orient.core.storage.OStorage; import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Element; import com.tinkerpop.blueprints.util.ElementHelper; import com.tinkerpop.blueprints.util.ExceptionFactory; import com.tinkerpop.blueprints.util.StringFactory; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Map; /** * Base Graph Element where OrientVertex and OrientEdge classes extends from. Labels are managed as OrientDB classes. * * @author Luca Garulli (http://www.orientechnologies.com) */ @SuppressWarnings("unchecked") public abstract class OrientElement implements Element, OSerializableStream, Externalizable, OIdentifiable { public static final String LABEL_FIELD_NAME = "label"; public static final Object DEF_ORIGINAL_ID_FIELDNAME = "origId"; private static final long serialVersionUID = 1L; // TODO: CAN REMOVE THIS REF IN FAVOR OF CONTEXT INSTANCE? protected transient OrientBaseGraph graph; protected transient OrientBaseGraph.Settings settings; protected OIdentifiable rawElement; protected OrientElement(final OrientBaseGraph rawGraph, final OIdentifiable iRawElement) { graph = rawGraph; rawElement = iRawElement; if (graph != null) settings = graph.settings; } public abstract String getLabel(); public abstract String getBaseClassName(); /** * (Blueprints Extension) Returns the element type in form of String between "Vertex" and "Edge". */ public abstract String getElementType(); /** * Removes the Element from the Graph. In case the element is a Vertex, all the incoming and outgoing edges are automatically * removed too. */ @Override public void remove() { checkIfAttached(); graph.setCurrentGraphInThreadLocal(); graph.autoStartTransaction(); final ORecordOperation oper = graph.getRawGraph().getTransaction().getRecordEntry(getIdentity()); if (oper != null && oper.type == ORecordOperation.DELETED) throw new IllegalStateException("The elements " + getIdentity() + " has already been deleted"); try { getRecord().load(); } catch (ORecordNotFoundException e) { throw new IllegalStateException("The elements " + getIdentity() + " has already been deleted"); } getRecord().delete(); } /** * (Blueprints Extension) Sets multiple properties in one shot against Vertices and Edges. This improves performance avoiding to * save the graph element at every property set. Example: * * <code> * vertex.setProperties( "name", "Jill", "age", 33, "city", "Rome", "born", "Victoria, TX" ); * </code> You can also pass a Map of values as first argument. In this case all the map entries will be set as element * properties: * * <code> * Map<String,Object> props = new HashMap<String,Object>(); * props.put("name", "Jill"); * props.put("age", 33); * props.put("city", "Rome"); * props.put("born", "Victoria, TX"); * vertex.setProperties(props); * </code> * * @param fields * Odd number of fields to set as repeating pairs of key, value, or if one parameter is received and it's a Map, the Map * entries are used as field key/value pairs. * @param <T> * @return */ public <T extends OrientElement> T setProperties(final Object... fields) { if (fields != null && fields.length > 0 && fields[0] != null) { if (!isDetached()) graph.autoStartTransaction(); if (fields.length == 1) { Object f = fields[0]; if (f instanceof Map<?, ?>) { for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) f).entrySet()) setPropertyInternal(this, (ODocument) rawElement.getRecord(), entry.getKey().toString(), entry.getValue()); } else throw new IllegalArgumentException( "Invalid fields: expecting a pairs of fields as String,Object or a single Map<String,Object>, but found: " + f); } else // SET THE FIELDS for (int i = 0; i < fields.length; i += 2) setPropertyInternal(this, (ODocument) rawElement.getRecord(), fields[i].toString(), fields[i + 1]); } return (T) this; } /** * Sets a Property value. * * @param key * Property name * @param value * Property value */ @Override public void setProperty(final String key, final Object value) { validateProperty(this, key, value); if (!isDetached()) graph.autoStartTransaction(); getRecord().field(key, value); if (!isDetached()) save(); } /** * Sets a Property value specifying a type. This is useful when you don't have a schema on this property but you want to force the * type. * * @param key * Property name * @param value * Property value * @param iType * Type to set */ public void setProperty(final String key, final Object value, final OType iType) { validateProperty(this, key, value); if (!isDetached()) graph.autoStartTransaction(); getRecord().field(key, value, iType); if (!isDetached()) save(); } /** * Removes a Property. * * @param key * Property name * @return Old value if any */ @Override public <T> T removeProperty(final String key) { if (!isDetached()) graph.autoStartTransaction(); final Object oldValue = getRecord().removeField(key); if (!isDetached()) save(); return (T) oldValue; } /** * Returns a Property value. * * @param key * Property name * @return Property value if any, otherwise NULL. */ @Override public <T> T getProperty(final String key) { if (key == null) return null; if (key.equals("_class")) return (T) getRecord().getSchemaClass().getName(); else if (key.equals("_version")) return (T) new Integer(getRecord().getVersion()); else if (key.equals("_rid")) return (T) rawElement.getIdentity().toString(); final Object fieldValue = getRecord().field(key); if (fieldValue instanceof OIdentifiable && !(((OIdentifiable) fieldValue).getRecord() instanceof ORecordBytes)) // CONVERT IT TO VERTEX/EDGE return (T) graph.getElement(fieldValue); else if (OMultiValue.isMultiValue(fieldValue) && OMultiValue.getFirstValue(fieldValue) instanceof OIdentifiable) { final OIdentifiable firstValue = (OIdentifiable) OMultiValue.getFirstValue(fieldValue); if (firstValue instanceof ODocument) { final ODocument document = (ODocument) firstValue; if (document.isEmbedded()) return (T) fieldValue; } // CONVERT IT TO ITERABLE<VERTEX/EDGE> return (T) new OrientElementIterable<OrientElement>(graph, OMultiValue.getMultiValueIterable(fieldValue)); } return (T) fieldValue; } /** * Returns the Element Id assuring to save it if it's transient yet. */ @Override public Object getId() { return getIdentity(); } /** * (Blueprints Extension) Saves current element. You don't need to call save() unless you're working against Temporary Vertices. */ public void save() { save(null); } /** * (Blueprints Extension) Saves current element to a particular cluster. You don't need to call save() unless you're working * against Temporary Vertices. * * @param iClusterName * Cluster name or null to use the default "E" */ public void save(final String iClusterName) { checkIfAttached(); graph.setCurrentGraphInThreadLocal(); if (rawElement instanceof ODocument) if (iClusterName != null) rawElement = ((ODocument) rawElement).save(iClusterName); else rawElement = ((ODocument) rawElement).save(); } public int hashCode() { return ((rawElement == null) ? 0 : rawElement.hashCode()); } /** * (Blueprints Extension) Serializes the Element as byte[] * * @throws OSerializationException */ @Override public byte[] toStream() throws OSerializationException { return rawElement.getIdentity().toString().getBytes(); } /** * (Blueprints Extension) Fills the Element from a byte[] * * @param stream * byte array representation of the object * @throws OSerializationException */ @Override public OSerializableStream fromStream(final byte[] stream) throws OSerializationException { final ODocument record = getRecord(); ((ORecordId) record.getIdentity()).fromString(new String(stream)); return this; } @Override public void writeExternal(final ObjectOutput out) throws IOException { out.writeObject(rawElement != null ? rawElement.getIdentity() : null); } @Override public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { rawElement = (OIdentifiable) in.readObject(); } /** * (Blueprints Extension) Locks current Element to prevent concurrent access. If lock is exclusive, then no concurrent threads can * read/write it. If the lock is shared, then concurrent threads can only read Element properties, but can't change them. Locks * can be freed by calling @unlock or when the current transaction is closed (committed or rollbacked). * * @see #lock(boolean) * @param iExclusive * True = Exclusive Lock, False = Shared Lock */ @Override public void lock(final boolean iExclusive) { ODatabaseRecordThreadLocal.INSTANCE.get().getTransaction() .lockRecord(this, iExclusive ? OStorage.LOCKING_STRATEGY.KEEP_EXCLUSIVE_LOCK : OStorage.LOCKING_STRATEGY.KEEP_SHARED_LOCK); } /** * (Blueprints Extension) Unlocks previous acquired @lock against the Element. * * @see #lock(boolean) */ @Override public void unlock() { ODatabaseRecordThreadLocal.INSTANCE.get().getTransaction().unlockRecord(this); } /** * (Blueprints Extension) Returns the record's identity. */ @Override public ORID getIdentity() { if (rawElement == null) return ORecordId.EMPTY_RECORD_ID; final ORID rid = rawElement.getIdentity(); if (!rid.isValid() && !isDetached()) { // SAVE THE RECORD TO OBTAIN A VALID RID graph.setCurrentGraphInThreadLocal(); graph.autoStartTransaction(); save(); } return rid; } /** * (Blueprints Extension) Returns the underlying record. */ @Override public ODocument getRecord() { if (rawElement instanceof ODocument) return (ODocument) rawElement; final ODocument doc = rawElement.getRecord(); if (doc == null) return null; // CHANGE THE RID -> DOCUMENT rawElement = doc; return doc; } /** * (Blueprints Extension) Removes the reference to the current graph instance to let working offline. To reattach it use @attach. * * @return Current object to allow chained calls. * @see #attach(OrientBaseGraph), #isDetached */ public OrientElement detach() { // EARLY UNMARSHALL FIELDS getRecord().setLazyLoad(false); getRecord().fieldNames(); // COPY GRAPH SETTINGS TO WORK OFFLINE settings = graph.settings.copy(); graph = null; return this; } /** * (Blueprints Extension) Replaces current graph instance with new one on @detach -ed elements. Use this method to pass elements * between graphs or to switch between Tx and NoTx instances. * * @param iNewGraph * The new Graph instance to use. * @return Current object to allow chained calls. * @see #detach(), #isDetached */ public OrientElement attach(final OrientBaseGraph iNewGraph) { if (iNewGraph == null) throw new IllegalArgumentException("Graph is null"); graph = iNewGraph; // LINK THE GRAPHS SETTINGS settings = graph.settings; return this; } /** * (Blueprints Extension) Tells if the current element has been @detach ed. * * @return True if detached, otherwise false * @see #attach(OrientBaseGraph), #detach */ public boolean isDetached() { return graph == null; } public boolean equals(final Object object) { return ElementHelper.areEqual(this, object); } public int compare(final OIdentifiable iFirst, final OIdentifiable iSecond) { if (iFirst == null || iSecond == null) return -1; return iFirst.compareTo(iSecond); } public int compareTo(final OIdentifiable iOther) { if (iOther == null) return 1; final ORID myRID = getIdentity(); final ORID otherRID = iOther.getIdentity(); if (myRID == null && otherRID == null) return 0; if (myRID == null) return -1; if (otherRID == null) return 1; return myRID.compareTo(otherRID); } /** * (Blueprints Extension) Returns the Graph instance associated to the current element. On @detach ed elements returns NULL. * */ public OrientBaseGraph getGraph() { return graph; } /** * (Blueprints Extension) Validates an Element property. * * @param element * Element instance * @param key * Property name * @param value * property value * @throws IllegalArgumentException */ public final void validateProperty(final Element element, final String key, final Object value) throws IllegalArgumentException { if (settings.standardElementConstraints && null == value) throw ExceptionFactory.propertyValueCanNotBeNull(); if (null == key) throw ExceptionFactory.propertyKeyCanNotBeNull(); if (settings.standardElementConstraints && key.equals(StringFactory.ID)) throw ExceptionFactory.propertyKeyIdIsReserved(); if (element instanceof Edge && key.equals(StringFactory.LABEL)) throw ExceptionFactory.propertyKeyLabelIsReservedForEdges(); if (key.isEmpty()) throw ExceptionFactory.propertyKeyCanNotBeEmpty(); } public void reload() { final ODocument rec = getRecord(); if (rec != null) rec.reload(null, true); } protected void copyTo(final OrientElement iCopy) { iCopy.graph = graph; iCopy.settings = settings; if (rawElement instanceof ODocument) { iCopy.rawElement = new ODocument().fromStream(((ODocument) rawElement).toStream()); } else if (rawElement instanceof ORID) iCopy.rawElement = ((ORID) rawElement).copy(); else throw new IllegalArgumentException("Cannot clone element " + rawElement); } protected void checkClass() { // FORCE EARLY UNMARSHALLING final ODocument doc = getRecord(); doc.deserializeFields(); final OClass cls = doc.getSchemaClass(); if (cls == null || !cls.isSubClassOf(getBaseClassName())) throw new IllegalArgumentException("The document received is not a " + getElementType() + ". Found class '" + cls + "'"); } /** * Check if a class already exists, otherwise create it at the fly. If a transaction is running commit changes, create the class * and begin a new transaction. * * @param className * Class's name */ protected String checkForClassInSchema(final String className) { if (className == null) return null; if (isDetached()) return className; final OSchema schema = graph.getRawGraph().getMetadata().getSchema(); if (!schema.existsClass(className)) { // CREATE A NEW CLASS AT THE FLY try { graph .executeOutsideTx(new OCallable<OClass, OrientBaseGraph>() { @Override public OClass call(final OrientBaseGraph g) { return schema.createClass(className, schema.getClass(getBaseClassName())); } }, "Committing the active transaction to create the new type '", className, "' as subclass of '", getBaseClassName(), "'. The transaction will be reopen right after that. To avoid this behavior create the classes outside the transaction"); } catch (OSchemaException e) { if (!schema.existsClass(className)) throw e; } } else { // CHECK THE CLASS INHERITANCE final OClass cls = schema.getClass(className); if (!cls.isSubClassOf(getBaseClassName())) throw new IllegalArgumentException("Class '" + className + "' is not an instance of " + getBaseClassName()); } return className; } protected void setPropertyInternal(final Element element, final ODocument doc, final String key, final Object value) { validateProperty(element, key, value); doc.field(key, value); } protected void setCurrentGraphInThreadLocal() { if (!isDetached()) graph.setCurrentGraphInThreadLocal(); } protected void checkIfAttached() { if (graph == null) throw new IllegalStateException("Graph element has been detached. Attach it before"); } }
apache-2.0
AlanJinTS/zstack
sdk/src/main/java/org/zstack/sdk/CreateMediaResult.java
277
package org.zstack.sdk; public class CreateMediaResult { public MediaInventory inventory; public void setInventory(MediaInventory inventory) { this.inventory = inventory; } public MediaInventory getInventory() { return this.inventory; } }
apache-2.0
MelvinWang/NewShare
NewShare/app/src/main/java/com/melvin/share/rx/RxOrderBus.java
342
package com.melvin.share.rx; import com.hwangjr.rxbus.Bus; /** * Author: Melvin * <p> * Data: 2017/4/6 * <p> * 描述:订单 */ public final class RxOrderBus { private static Bus mBus; public synchronized static Bus get() { if (mBus == null) { mBus = new Bus(); } return mBus; } }
apache-2.0
switchfly/switchfly-java
inputvalidation/src/main/java/com/switchfly/inputvalidation/PatternValidationStrategies.java
1776
/* * Copyright 2012 Switchfly * * 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.switchfly.inputvalidation; import com.switchfly.inputvalidation.canonicalizer.HtmlAndQueryStringCanonicalizer; import com.switchfly.inputvalidation.sanitizer.StripHtmlAndCleanPatternSanitizer; import com.switchfly.inputvalidation.sanitizer.StripHtmlSanitizer; import com.switchfly.inputvalidation.validator.PatternValidator; public class PatternValidationStrategies implements ValidationStrategies { private final ValidationStrategy<String> _cleanStrategy; private final ValidationStrategy<String> _validateStrategy; public PatternValidationStrategies(String acceptedPattern) { _cleanStrategy = new ValidationStrategy<String>(new HtmlAndQueryStringCanonicalizer(), null, new StripHtmlAndCleanPatternSanitizer(acceptedPattern)); _validateStrategy = new ValidationStrategy<String>(new HtmlAndQueryStringCanonicalizer(), new PatternValidator(acceptedPattern), new StripHtmlSanitizer()); } @Override public ValidationStrategy<String> cleanStrategy() { return _cleanStrategy; } @Override public ValidationStrategy<String> validateStrategy() { return _validateStrategy; } }
apache-2.0
TNG/JGiven
jgiven-junit/src/main/java/com/tngtech/jgiven/junit/DualScenarioTest.java
661
package com.tngtech.jgiven.junit; import com.tngtech.jgiven.base.DualScenarioTestBase; import com.tngtech.jgiven.impl.Scenario; import org.junit.ClassRule; import org.junit.Rule; public class DualScenarioTest <GIVEN_WHEN, THEN> extends DualScenarioTestBase<GIVEN_WHEN, THEN> { @ClassRule public static final JGivenClassRule writerRule = new JGivenClassRule(); @Rule public final JGivenMethodRule scenarioRule = new JGivenMethodRule( createScenario() ); @Override @SuppressWarnings("unchecked") public Scenario<GIVEN_WHEN, GIVEN_WHEN, THEN> getScenario() { return (Scenario<GIVEN_WHEN, GIVEN_WHEN, THEN>) scenarioRule.getScenario(); } }
apache-2.0
Alejandro-Frech/AnalisisAlgoritmos
src/org/jgrapht/experimental/permutation/CollectionPermutationIter.java
5089
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This program and the accompanying materials are dual-licensed under * either * * (a) the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation, or (at your option) any * later version. * * or (per the licensee's choosing) * * (b) the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation. */ /* ----------------- * CollectionPermutationIter.java * ----------------- * (C) Copyright 2005-2008, by Assaf Lehr and Contributors. * * Original Author: Assaf Lehr * Contributor(s): - * * $Id$ * * Changes * ------- */ package org.jgrapht.experimental.permutation; import java.util.*; /** * Given a container with elements (Collection,Enumeration,array) defines a * permutation iterator which returns, on each iteration, a differnt permutation * of the source container. You may choose a different container * type(Collection/Array/etc) for each next call. It will continue as if they * were the same iterator. * * @author Assaf * @since May 20, 2005 */ public class CollectionPermutationIter<E> { private ArrayPermutationsIter permOrder; private List<E> sourceArray; /** * change everry calculation.can be retrieved publicly */ private int [] currPermutationArray; /** * Note: the Set interface does not guarantee iteration order. This method * iterates on the set to get the initial order and after that the data will * be saved internally in another (ordered) container. So, remeber that the * Initial order can be different from the objectSet.toString() method. If * you want it to be the same, use a LinkedHashSet , or use the array * constructor. * * @param objectsSet */ public CollectionPermutationIter(Set<E> objectsSet) { this( new ArrayList<E>(objectsSet), new IntegerPermutationIter(objectsSet.size())); } /** * Uses a permArray like [1,1,1,2] where some of the permutations are not * relevant. Here there will be 4 permutations (only the '2' position is * important) * * @param objectsArray */ public CollectionPermutationIter(List<E> objectsArray) { this( objectsArray, new IntegerPermutationIter(objectsArray.size())); } public CollectionPermutationIter( List<E> objectsArray, ArrayPermutationsIter permuter) { this.permOrder = permuter; this.sourceArray = objectsArray; } public boolean hasNext() { return this.permOrder.hasNextPermutaions(); } /** * On first call, returns the source as an array; on any other call * thereafter, a new permutation * * @return null if we overflowed! the array otherwise */ public List<E> getNextArray() { List<E> permutationResult; // will hold the array result if (this.permOrder.hasNextPermutaions()) { this.currPermutationArray = this.permOrder.nextPermutation(); permutationResult = applyPermutation(); } else { permutationResult = null; } return permutationResult; } private List<E> applyPermutation() { ArrayList<E> output = new ArrayList<E>(sourceArray); // Example : this.sourceArray = ["A","B","C","D"] // perOrder: = [ 1 , 0 , 3 , 2 ] // result : = ["B","A","D","C"] for (int i = 0; i < output.size(); i++) { output.set( i, this.sourceArray.get(this.currPermutationArray[i])); } return output; } /** * Wrap result to a Set. * * @return null if we overflowed! the set otherwise */ public Set<E> getNextSet() { List<E> result = getNextArray(); if (result == null) { return null; } else // wrap in a SET { Set<E> resultSet = new LinkedHashSet<E>(result); return resultSet; } } public int [] getCurrentPermutationArray() { return this.currPermutationArray; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Permutation int[]="); sb.append(Arrays.toString(getCurrentPermutationArray())); List<E> permutationResult = applyPermutation(); sb.append("\nPermutationSet Source Object[]="); sb.append(this.sourceArray.toString()); sb.append("\nPermutationSet Result Object[]="); sb.append(permutationResult.toString()); return sb.toString(); } } // End CollectionPermutationIter.java
apache-2.0
code-orchestra/metaas-fork
src/test/java/uk/co/badgersinfoil/metaas/fixes/InterfaceMetodsSemicolonTest.java
1494
package uk.co.badgersinfoil.metaas.fixes; import junit.framework.TestCase; import uk.co.badgersinfoil.metaas.ActionScriptFactory; import uk.co.badgersinfoil.metaas.ActionScriptParser; import uk.co.badgersinfoil.metaas.dom.*; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; /** * This test checks if method declaration w/o semicolons works fine. * * @author Alexander Eliseyev */ public class InterfaceMetodsSemicolonTest extends TestCase { public void testIt() { ActionScriptFactory fact = new ActionScriptFactory(); ASCompilationUnit unit = loadSyntaxExample(fact); ASInterfaceType interfaceType = (ASInterfaceType) unit.getType(); List methods = interfaceType.getMethods(); assertEquals(4, methods.size()); int i = 0; for (Object methodObj : methods) { ASMethod method = (ASMethod) methodObj; print(method.getName()); assertEquals("$myFunc" + ++i, method.getName()); } } private static void print(String str) { System.out.println(str); } private ASCompilationUnit loadSyntaxExample(ActionScriptFactory fact) { InputStream in = getClass().getClassLoader().getResourceAsStream("InterfaceMetodsSemicolon.as"); ActionScriptParser parser = fact.newParser(); ASCompilationUnit unit = parser.parse(new InputStreamReader(in)); return unit; } }
apache-2.0
ontopia/ontopia
ontopia-engine/src/main/java/net/ontopia/topicmaps/utils/jtm/JSONToken.java
3297
//#! Ignore-License /* * Copyright 2007 - 2009 Lars Heuer (heuer[at]semagia.com) * * 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 net.ontopia.topicmaps.utils.jtm; /** * INTERNAL: Known token types for JTM 1.0. */ final class JSONToken { /** * Token types. */ public static final int START_OBJECT = 0, END_OBJECT = 1, START_ARRAY = 2, END_ARRAY = 4, VALUE_NULL = 5, KW_VERSION = 6, KW_ITEM_TYPE = 7, KW_TOPICS = 8, KW_ASSOCIATIONS = 9, KW_ROLES = 10, KW_OCCURRENCES = 11, KW_NAMES = 12, KW_VARIANTS = 13, KW_SCOPE = 14, KW_TYPE = 15, KW_PLAYER = 16, KW_VALUE = 17, KW_DATATYPE = 18, KW_REIFIER = 19, KW_SIDS = 20, KW_SLOS = 21, KW_IIDS = 22, KW_PARENT = 23, VALUE_STRING = 24, COLON = 25, COMMA = 26 ; /** * Returns a string representation of the provided token. * * @param type The token type. * @return A string representing the token. */ public static String nameOf(final int type) { switch (type) { case START_OBJECT: return "{"; case END_OBJECT: return "}"; case START_ARRAY: return "["; case END_ARRAY: return "]"; case COMMA: return ","; case COLON: return ":"; case VALUE_NULL: return "null"; case VALUE_STRING: return "<string>"; case KW_VERSION: return "version"; case KW_ITEM_TYPE: return "item_type"; case KW_TOPICS: return "topics"; case KW_ASSOCIATIONS: return "associations"; case KW_ROLES: return "roles"; case KW_OCCURRENCES: return "occurrences"; case KW_NAMES: return "names"; case KW_VARIANTS: return "variants"; case KW_SCOPE: return "scope"; case KW_TYPE: return "type"; case KW_PLAYER: return "player"; case KW_VALUE: return "value"; case KW_DATATYPE: return "datatype"; case KW_REIFIER: return "reifier"; case KW_SIDS: return "subject_identifiers"; case KW_SLOS: return "subject_locators"; case KW_IIDS: return "item_identifiers"; case KW_PARENT: return "parent"; } throw new IllegalArgumentException("Unknown token type:" + type); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-lightsail/src/main/java/com/amazonaws/services/lightsail/model/transform/CreateContainerServiceDeploymentResultJsonUnmarshaller.java
3075
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.lightsail.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.lightsail.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateContainerServiceDeploymentResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class CreateContainerServiceDeploymentResultJsonUnmarshaller implements Unmarshaller<CreateContainerServiceDeploymentResult, JsonUnmarshallerContext> { public CreateContainerServiceDeploymentResult unmarshall(JsonUnmarshallerContext context) throws Exception { CreateContainerServiceDeploymentResult createContainerServiceDeploymentResult = new CreateContainerServiceDeploymentResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return createContainerServiceDeploymentResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("containerService", targetDepth)) { context.nextToken(); createContainerServiceDeploymentResult.setContainerService(ContainerServiceJsonUnmarshaller.getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return createContainerServiceDeploymentResult; } private static CreateContainerServiceDeploymentResultJsonUnmarshaller instance; public static CreateContainerServiceDeploymentResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateContainerServiceDeploymentResultJsonUnmarshaller(); return instance; } }
apache-2.0
panga/arquillian-extension-switchyard
src/main/java/org/jboss/arquillian/extension/switchyard/container/SwitchYardInterceptor.java
5002
package org.jboss.arquillian.extension.switchyard.container; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; import javax.enterprise.context.ApplicationScoped; import javax.inject.Named; import javax.xml.namespace.QName; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.switchyard.Exchange; import org.switchyard.ExchangeHandler; import org.switchyard.ExchangeInterceptor; import org.switchyard.HandlerException; import org.switchyard.Service; import org.switchyard.ServiceDomain; import org.switchyard.ServiceReference; import org.switchyard.metadata.ServiceInterface; import org.switchyard.security.SecurityMetadata; @ApplicationScoped @Named public class SwitchYardInterceptor implements ExchangeInterceptor { private ServiceDomain serviceDomain; private final Set<ServiceActivator> activators = new HashSet<>(); private static final Logger LOG = LoggerFactory.getLogger(SwitchYardInterceptor.class); private void activateService(ServiceActivator activator) { unregisterService(activator); LOG.info("Registering mock service for {}", activator.getServiceName()); serviceDomain.registerService(activator.getServiceName(), activator.getServiceInterface(), activator.getServiceHandler()); serviceDomain.registerServiceReference(activator.getServiceName(), activator.getServiceInterface()); } private boolean unregisterService(ServiceActivator activator) { if (serviceDomain == null) { LOG.warn("Service domain is not defined yet"); return false; } final List<Service> services = serviceDomain.getServices(activator.getServiceName()); if (!services.isEmpty()) { LOG.info("Unregistering services for {}", activator.getServiceName()); for (Service service : services) { service.unregister(); } } final ServiceReference serviceReference = serviceDomain.getServiceReference(activator.getServiceName()); if (serviceReference != null) { LOG.info("Unregistering service reference for {}", activator.getServiceName()); serviceReference.unregister(); } return true; } synchronized void registerService(QName serviceName, ExchangeHandler serviceHandler, ServiceInterface serviceInterface) { final ServiceActivator activator = new ServiceActivator(serviceName, serviceHandler, serviceInterface); if (activators.contains(activator)) { activators.remove(activator); } activators.add(activator); if (serviceDomain != null) { activateService(activator); } } synchronized void unregisterAll() { for (ServiceActivator activator : activators) { unregisterService(activator); } activators.clear(); } @Override public void before(String target, Exchange exchange) throws HandlerException { if (serviceDomain == null) { synchronized (this) { serviceDomain = SecurityMetadata.getServiceDomain(exchange); LOG.info("SwithYard Service Domain found, starting to register mock services"); for (ServiceActivator activator : activators) { activateService(activator); } } } } @Override public void after(String target, Exchange exchange) throws HandlerException { // nop } @Override public List<String> getTargets() { return Arrays.asList(CONSUMER, PROVIDER); } private static class ServiceActivator { private final QName serviceName; private final ExchangeHandler serviceHandler; private final ServiceInterface serviceInterface; public ServiceActivator(QName serviceName, ExchangeHandler serviceHandler, ServiceInterface serviceInterface) { this.serviceName = serviceName; this.serviceHandler = serviceHandler; this.serviceInterface = serviceInterface; } public ExchangeHandler getServiceHandler() { return serviceHandler; } public QName getServiceName() { return serviceName; } public ServiceInterface getServiceInterface() { return serviceInterface; } @Override public int hashCode() { int hash = 3; hash = 97 * hash + Objects.hashCode(this.serviceName); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ServiceActivator other = (ServiceActivator) obj; return Objects.equals(this.serviceName, other.serviceName); } } }
apache-2.0
luowenzhen/coolWeather
app/src/main/java/com/coolweather/luowz/android/util/HttpUtil.java
432
package com.coolweather.luowz.android.util; import okhttp3.OkHttpClient; import okhttp3.Request; /** * Created by luowz on 2017/4/15. */ public class HttpUtil { public static void sendOkHttpRequest(String address, okhttp3.Callback callback) { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(address).build(); client.newCall(request).enqueue(callback); } }
apache-2.0
wuwen5/dubbo
dubbo-spring-boot/dubbo-spring-boot-actuator/src/main/java/org/apache/dubbo/spring/boot/actuate/endpoint/condition/CompatibleOnEnabledEndpointCondition.java
3256
/* * 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.dubbo.spring.boot.actuate.endpoint.condition; import org.apache.dubbo.common.logger.Logger; import org.apache.dubbo.common.logger.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.context.annotation.Conditional; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.util.ClassUtils; /** * {@link Conditional} that checks whether or not an endpoint is enabled, which is compatible with * org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnEnabledEndpointCondition * and org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition * * @see CompatibleConditionalOnEnabledEndpoint * @since 2.7.7 */ class CompatibleOnEnabledEndpointCondition implements Condition { private static final Logger LOGGER = LoggerFactory.getLogger(CompatibleOnEnabledEndpointCondition.class); // Spring Boot [2.0.0 , 2.2.x] static String CONDITION_CLASS_NAME_OLD = "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnEnabledEndpointCondition"; // Spring Boot 2.2.0 + static String CONDITION_CLASS_NAME_NEW = "org.springframework.boot.actuate.autoconfigure.endpoint.condition.OnAvailableEndpointCondition"; @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { ClassLoader classLoader = context.getClassLoader(); if (ClassUtils.isPresent(CONDITION_CLASS_NAME_OLD, classLoader)) { Class<?> cls = ClassUtils.resolveClassName(CONDITION_CLASS_NAME_OLD, classLoader); if (Condition.class.isAssignableFrom(cls)) { Condition condition = Condition.class.cast(BeanUtils.instantiateClass(cls)); return condition.matches(context, metadata); } } // Check by org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnAvailableEndpoint if (ClassUtils.isPresent(CONDITION_CLASS_NAME_NEW, classLoader)) { return true; } // No condition class found LOGGER.warn(String.format("No condition class found, Dubbo Health Endpoint [%s] will not expose", metadata)); return false; } }
apache-2.0
stori-es/stori_es
shared/src/main/java/org/consumersunion/stories/common/shared/service/datatransferobject/Documents.java
877
package org.consumersunion.stories.common.shared.service.datatransferobject; import java.util.List; import org.consumersunion.stories.common.shared.model.document.Document; import com.google.common.collect.Lists; import com.google.gwt.user.client.rpc.IsSerializable; public class Documents implements IsSerializable { private List<Document> documents; public Documents(List<Document> documents) { this.documents = documents; } public Documents() { this(Lists.<Document>newArrayList()); } public List<Document> getDocuments() { return documents; } public void setDocuments(List<Document> documents) { this.documents = documents; } public void addDocument(Document document) { documents.add(document); } public boolean hasDocuments() { return !documents.isEmpty(); } }
apache-2.0
florianerhard/gedi
GediCore/src/gedi/util/job/schedule/PetriNetScheduler.java
1032
/** * * Copyright 2017 Florian Erhard * * 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 gedi.util.job.schedule; import gedi.util.job.ExecutionContext; import java.util.concurrent.ExecutorService; import java.util.function.Consumer; public interface PetriNetScheduler extends Runnable { ExecutionContext getExecutionContext(); void addListener(PetriNetListener rg); void removeListener(PetriNetListener rg); void setFinishAction(Consumer<ExecutionContext> finishAction); }
apache-2.0
osbominix/java_gof_adapter
src/main/java/com/gof/designpattern/adapter/basis/MacBook.java
260
package com.gof.designpattern.adapter.basis; /** * Created by yl3 on 24.11.15. */ public class MacBook { private String name; public MacBook(String name) { this.name = name; } public String getName() { return name; } }
apache-2.0
java110/MicroCommunity
java110-bean/src/main/java/com/java110/dto/smallWeChat/SmallWeChatDto.java
3411
package com.java110.dto.smallWeChat; import com.java110.dto.PageDto; import com.java110.dto.smallWechatAttr.SmallWechatAttrDto; import java.io.Serializable; import java.util.Date; import java.util.List; /** * @ClassName FloorDto * @Description 小程序管理数据层封装 * @Author wuxw * @Date 2019/4/24 8:52 * @Version 1.0 * add by wuxw 2019/4/24 **/ public class SmallWeChatDto extends PageDto implements Serializable { public static final String WECHAT_TYPE_PUBLIC = "1100"; // 公众号 public static final String OBJ_TYPE_COMMUNITY = "1000";// 当前小区 private Date createTime; private String appId; private String name; private String appSecret; private String weChatId; private String storeId; private String payPassword; private String remarks; private String statusCd = "0"; private String objId; private String objType; private String mchId; private String objTypeName; private String weChatType; private List<SmallWechatAttrDto> smallWechatAttrs; public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAppSecret() { return appSecret; } public void setAppSecret(String appSecret) { this.appSecret = appSecret; } public String getWeChatId() { return weChatId; } public void setWeChatId(String weChatId) { this.weChatId = weChatId; } public String getStoreId() { return storeId; } public void setStoreId(String storeId) { this.storeId = storeId; } public String getPayPassword() { return payPassword; } public void setPayPassword(String payPassword) { this.payPassword = payPassword; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getStatusCd() { return statusCd; } public void setStatusCd(String statusCd) { this.statusCd = statusCd; } public String getObjId() { return objId; } public void setObjId(String objId) { this.objId = objId; } public String getObjType() { return objType; } public void setObjType(String objType) { this.objType = objType; } public String getMchId() { return mchId; } public void setMchId(String mchId) { this.mchId = mchId; } public String getObjTypeName() { return objTypeName; } public void setObjTypeName(String objTypeName) { this.objTypeName = objTypeName; } public String getWeChatType() { return weChatType; } public void setWeChatType(String weChatType) { this.weChatType = weChatType; } public List<SmallWechatAttrDto> getSmallWechatAttrs() { return smallWechatAttrs; } public void setSmallWechatAttrs(List<SmallWechatAttrDto> smallWechatAttrs) { this.smallWechatAttrs = smallWechatAttrs; } }
apache-2.0
utgenome/utgb
utgb-core/src/main/java/org/utgenome/format/fasta/CompactFASTAGenerator.java
4629
/*-------------------------------------------------------------------------- * Copyright 2009 utgenome.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *--------------------------------------------------------------------------*/ //-------------------------------------- // utgb-core Project // // CompactFASTAGenerator.java // Since: Feb 22, 2010 // // $URL$ // $Author$ //-------------------------------------- package org.utgenome.format.fasta; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.xerial.silk.SilkWriter; import org.xerial.util.FileType; import org.xerial.util.log.Logger; /** * * * @author leo * */ public class CompactFASTAGenerator { private static Logger _logger = Logger.getLogger(CompactFASTAGenerator.class); private CompactACGTWriter compressor; private SilkWriter indexOut; private String workDir = "target"; public int BUFFER_SIZE = 8 * 1024 * 1024; public CompactFASTAGenerator() { } public void setBuffferSize(int bufferSizeInMB) { BUFFER_SIZE = bufferSizeInMB * 1024 * 1024; } public void setWorkDir(String workDir) { this.workDir = workDir; } public void setWorkDir(File workDir) { this.workDir = workDir.getAbsolutePath(); } public String getWorkDir() { return workDir; } public void packFASTA(String fastaFilePath) throws IOException { packFASTA(fastaFilePath, new FileInputStream(fastaFilePath)); } public void packFASTA(URL fastaFile) throws IOException { packFASTA(fastaFile.getPath(), fastaFile.openStream()); } public void packFASTA(String fastaFilePrefix, InputStream in) throws IOException { File work = new File(workDir); if (!work.exists()) { _logger.info("create a directory: " + work); work.mkdirs(); } String fileName = new File(fastaFilePrefix).getName(); String baseName = fileName.endsWith(".fa") ? fileName : FileType.removeFileExt(fileName); // output files String pacSeqFile = baseName + CompactFASTA.PAC_FILE_SUFFIX; String pacNSeqFile = baseName + CompactFASTA.PAC_N_FILE_SUFFIX; String pacIndexFile = baseName + CompactFASTA.PAC_INDEX_FILE_SUFFIX; _logger.info("pac file: " + pacSeqFile); _logger.info("pac file for N: " + pacNSeqFile); _logger.info("pac index file: " + pacIndexFile); BufferedOutputStream pacSeqOut = new BufferedOutputStream(new FileOutputStream(new File(workDir, pacSeqFile)), BUFFER_SIZE); BufferedOutputStream pacNSeqOut = new BufferedOutputStream(new FileOutputStream(new File(workDir, pacNSeqFile)), BUFFER_SIZE); compressor = new CompactACGTWriter(pacSeqOut, pacNSeqOut); indexOut = new SilkWriter(new BufferedWriter(new FileWriter(new File(workDir, pacIndexFile)))); indexOut.preamble(); indexOut.schema("sequence").attribute("name").attribute("description").attribute("length").attribute("offset"); // load FASTA file (.fa, .fa.tar.gz, ...) packFASTA(new FASTAPullParser(fileName, in, BUFFER_SIZE)); compressor.close(); indexOut.close(); _logger.info("pack done."); } private void packFASTA(FASTAPullParser fastaParser) throws IOException { String description; while ((description = fastaParser.nextDescriptionLine()) != null) { String sequenceName = CompactFASTA.pickSequenceName(description); _logger.info(String.format("loading %s ...", sequenceName)); long start = compressor.getSequenceLength(); String seq = null; while ((seq = fastaParser.nextSequenceLine()) != null) { compressor.append(seq); } long end = compressor.getSequenceLength(); long sequenceLength = end - start; SilkWriter s = indexOut.node("sequence").attribute("name", sequenceName); s.leaf("description", description); s.leaf("length", Long.toString(sequenceLength)); s.leaf("offset", Long.toString(start)); } } }
apache-2.0
rhauch/modeshape
modeshape-jcr/src/test/java/org/modeshape/jcr/JcrTckSuites.java
3334
/* * ModeShape (http://www.modeshape.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.modeshape.jcr; import java.util.Enumeration; import org.apache.jackrabbit.test.JCRTestSuite; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestResult; import junit.framework.TestSuite; /** * Helper class which provides various JUnit 3.x {@link TestSuite} instances, which should be used when running any form of Tck tests, to be able * to shutdown the engine at the end of the run. * * This helper provides two types of suites: * - inline suites: which create an anonymous {@link TestSuite} instance and load some or all of the Tck tests in that instance * - default suite: returns the suites which are part of the Tck, by default (e.g. {@link JCRTestSuite}) * * @author Horia Chiorean */ public final class JcrTckSuites { public static JCRTestSuite defaultSuite() { return new JCRTestSuite() { @Override public void run( TestResult result ) { try { JTATestUtil.setJBossJTADefaultStoreLocations(); super.run(result); } finally { ModeShapeRepositoryStub.shutdownEngine(); JTATestUtil.clearJBossJTADefaultStoreLocation(); } } }; } public static TestSuite defaultSuiteInline() { return new TestSuite() { { for (Enumeration<Test> testsEnum = new JCRTestSuite().tests(); testsEnum.hasMoreElements(); ) { addTest(testsEnum.nextElement()); } } @Override public void run( TestResult result ) { try { JTATestUtil.setJBossJTADefaultStoreLocations(); super.run(result); } finally { ModeShapeRepositoryStub.shutdownEngine(); JTATestUtil.clearJBossJTADefaultStoreLocation(); } } }; } public static TestSuite someTestsInline( final Class<? extends TestCase>... classes ) { return new TestSuite() { { for (Class<? extends TestCase> testClass : classes) { addTestSuite(testClass); } } @Override public void run( TestResult result ) { try { JTATestUtil.setJBossJTADefaultStoreLocations(); super.run(result); } finally { ModeShapeRepositoryStub.shutdownEngine(); JTATestUtil.clearJBossJTADefaultStoreLocation(); } } }; } private JcrTckSuites() { } }
apache-2.0
wapache/wason
api/src/main/java/javax/json/stream/JsonParserFactory.java
4827
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2011-2013 Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can * obtain a copy of the License at * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html * or packager/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at packager/legal/LICENSE.txt. * * GPL Classpath Exception: * Oracle designates this particular file as subject to the "Classpath" * exception as provided by Oracle in the GPL Version 2 section of the License * file that accompanied this code. * * Modifications: * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyright [year] [name of copyright owner]" * * Contributor(s): * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ package javax.json.stream; import javax.json.JsonArray; import javax.json.JsonObject; import java.io.InputStream; import java.io.Reader; import java.nio.charset.Charset; import java.util.Map; /** * Factory for creating {@link JsonParser} instances. If a factory * instance is configured with a configuration, the configuration applies * to all parser instances created using that factory instance. * * <p> * The class {@link javax.json.Json Json} also provides methods to create * {@link JsonParser} instances, but using {@code JsonParserFactory} is * preferred when creating multiple parser instances as shown in the following * example: * * <pre> * <code> * JsonParserFactory factory = Json.createParserFactory(); * JsonParser parser1 = factory.createParser(...); * JsonParser parser2 = factory.createParser(...); * </code> * </pre> * * <p> All the methods in this class are safe for use by multiple concurrent * threads. * * @author Jitendra Kotamraju */ public interface JsonParserFactory { /** * Creates a JSON parser from a character stream. * * @param reader a i/o reader from which JSON is to be read */ JsonParser createParser(Reader reader); /** * Creates a JSON parser from the specified byte stream. * The character encoding of the stream is determined * as specified in <a href="http://tools.ietf.org/rfc/rfc4627.txt">RFC 4627</a>. * * @param in i/o stream from which JSON is to be read * @throws javax.json.JsonException if encoding cannot be determined * or i/o error (IOException would be cause of JsonException) */ JsonParser createParser(InputStream in); /** * Creates a JSON parser from the specified byte stream. * The bytes of the stream are decoded to characters using the * specified charset. * * @param in i/o stream from which JSON is to be read * @param charset a charset */ JsonParser createParser(InputStream in, Charset charset); /** * Creates a JSON parser from the specified JSON object. * * @param obj a JSON object */ JsonParser createParser(JsonObject obj); /** * Creates a JSON parser from the specified JSON array. * * @param array a JSON array */ JsonParser createParser(JsonArray array); /** * Returns a read-only map of supported provider specific configuration * properties that are used to configure the JSON parsers. * If there are any specified configuration properties that are not * supported by the provider, they won't be part of the returned map. * * @return a map of supported provider specific properties that are used * to configure the created parsers. The map may be empty but not null */ Map<String, ?> getConfigInUse(); }
apache-2.0
vadopolski/ignite
modules/core/src/main/java/org/apache/ignite/internal/pagemem/wal/record/delta/DataPageInsertFragmentRecord.java
2524
/* * 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.ignite.internal.pagemem.wal.record.delta; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.pagemem.PageMemory; import org.apache.ignite.internal.processors.cache.persistence.tree.io.DataPageIO; /** * Insert fragment to data page record. */ public class DataPageInsertFragmentRecord extends PageDeltaRecord { /** Link to the last entry fragment. */ private final long lastLink; /** Actual fragment data. */ private final byte[] payload; /** * @param grpId Cache group ID. * @param pageId Page ID. * @param payload Fragment payload. * @param lastLink Link to the last entry fragment. */ public DataPageInsertFragmentRecord( final int grpId, final long pageId, final byte[] payload, final long lastLink ) { super(grpId, pageId); this.lastLink = lastLink; this.payload = payload; } /** {@inheritDoc} */ @Override public void applyDelta(PageMemory pageMem, long pageAddr) throws IgniteCheckedException { DataPageIO io = DataPageIO.VERSIONS.forPage(pageAddr); io.addRowFragment(pageAddr, payload, lastLink, pageMem.pageSize()); } /** {@inheritDoc} */ @Override public RecordType type() { return RecordType.DATA_PAGE_INSERT_FRAGMENT_RECORD; } /** * @return Fragment payload size. */ public int payloadSize() { return payload.length; } /** * @return Fragment payload. */ public byte[] payload() { return payload; } /** * @return Link to the last entry fragment. */ public long lastLink() { return lastLink; } }
apache-2.0
cags12/android_page_curl
src/fi/harism/curl/CurlMesh.java
35478
/* Copyright 2011 Harri Smått 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 fi.harism.curl; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.RectF; import android.opengl.GLUtils; /** * Class implementing actual curl/page rendering. * * @author harism */ public class CurlMesh { // Flag for rendering some lines used for developing. Shows // curl position and one for the direction from the // position given. Comes handy once playing around with different // ways for following pointer. private static final boolean DRAW_CURL_POSITION = false; // Flag for drawing polygon outlines. Using this flag crashes on emulator // due to reason unknown to me. Leaving it here anyway as seeing polygon // outlines gives good insight how original rectangle is divided. private static final boolean DRAW_POLYGON_OUTLINES = false; // Flag for texture rendering. While this is likely something you // don't want to do it's been used for development purposes as texture // rendering is rather slow on emulator. private static final boolean DRAW_TEXTURE = true; // Flag for enabling shadow rendering. private static final boolean DRAW_SHADOW = true; // Colors for shadow. Inner one is the color drawn next to surface where // shadowed area starts and outer one is color shadow ends to. private static final float[] SHADOW_INNER_COLOR = { 0f, 0f, 0f, .5f }; private static final float[] SHADOW_OUTER_COLOR = { 0f, 0f, 0f, .0f }; // Alpha values for front and back facing texture. // CAGS: Modified to avoid transparency in landscape private static double BACKFACE_ALPHA = 1f; //private static final double BACKFACE_ALPHA = .2f; private static final double FRONTFACE_ALPHA = 1f; // Boolean for 'flipping' texture sideways. private boolean mFlipTexture = false; // CAGS: Method to change Alpha value landscape/portraid public static void setALPHA (double value){ BACKFACE_ALPHA = value; } // For testing purposes. private int mCurlPositionLinesCount; private FloatBuffer mCurlPositionLines; // Buffers for feeding rasterizer. private FloatBuffer mVertices; private FloatBuffer mTexCoords; private FloatBuffer mColors; private int mVerticesCountFront; private int mVerticesCountBack; private FloatBuffer mShadowColors; private FloatBuffer mShadowVertices; private int mDropShadowCount; private int mSelfShadowCount; // Maximum number of split lines used for creating a curl. private int mMaxCurlSplits; // Bounding rectangle for this mesh. mRectagle[0] = top-left corner, // mRectangle[1] = bottom-left, mRectangle[2] = top-right and mRectangle[3] // bottom-right. private Vertex[] mRectangle = new Vertex[4]; // One and only texture id. private int[] mTextureIds; private Bitmap mBitmap; private RectF mTextureRect = new RectF(); // CAGS : Added some new needed variables private Bitmap mBitmapB; private int mWidthAux; private boolean mNewTex = false; //public boolean mSwapSheet = false; // Let's avoid using 'new' as much as possible. Meaning we introduce arrays // once here and reuse them on runtime. Doesn't really have very much effect // but avoids some garbage collections from happening. private Array<Vertex> mTempVertices; private Array<Vertex> mIntersections; private Array<Vertex> mOutputVertices; private Array<Vertex> mRotatedVertices; private Array<Double> mScanLines; private Array<ShadowVertex> mTempShadowVertices; private Array<ShadowVertex> mSelfShadowVertices; private Array<ShadowVertex> mDropShadowVertices; /** * Constructor for mesh object. * * @param maxCurlSplits * Maximum number curl can be divided into. The bigger the value * the smoother curl will be. With the cost of having more * polygons for drawing. */ public CurlMesh(int maxCurlSplits) { // There really is no use for 0 splits. mMaxCurlSplits = maxCurlSplits < 1 ? 1 : maxCurlSplits; mScanLines = new Array<Double>(maxCurlSplits + 2); mOutputVertices = new Array<Vertex>(7); mRotatedVertices = new Array<Vertex>(4); mIntersections = new Array<Vertex>(2); mTempVertices = new Array<Vertex>(7 + 4); for (int i = 0; i < 7 + 4; ++i) { mTempVertices.add(new Vertex()); } if (DRAW_SHADOW) { mSelfShadowVertices = new Array<ShadowVertex>( (mMaxCurlSplits + 2) * 2); mDropShadowVertices = new Array<ShadowVertex>( (mMaxCurlSplits + 2) * 2); mTempShadowVertices = new Array<ShadowVertex>( (mMaxCurlSplits + 2) * 2); for (int i = 0; i < (mMaxCurlSplits + 2) * 2; ++i) { mTempShadowVertices.add(new ShadowVertex()); } } // Rectangle consists of 4 vertices. Index 0 = top-left, index 1 = // bottom-left, index 2 = top-right and index 3 = bottom-right. for (int i = 0; i < 4; ++i) { mRectangle[i] = new Vertex(); } // Set up shadow penumbra direction to each vertex. We do fake 'self // shadow' calculations based on this information. mRectangle[0].mPenumbraX = mRectangle[1].mPenumbraX = mRectangle[1].mPenumbraY = mRectangle[3].mPenumbraY = -1; mRectangle[0].mPenumbraY = mRectangle[2].mPenumbraX = mRectangle[2].mPenumbraY = mRectangle[3].mPenumbraX = 1; if (DRAW_CURL_POSITION) { mCurlPositionLinesCount = 3; ByteBuffer hvbb = ByteBuffer .allocateDirect(mCurlPositionLinesCount * 2 * 2 * 4); hvbb.order(ByteOrder.nativeOrder()); mCurlPositionLines = hvbb.asFloatBuffer(); mCurlPositionLines.position(0); } // There are 4 vertices from bounding rect, max 2 from adding split line // to two corners and curl consists of max mMaxCurlSplits lines each // outputting 2 vertices. int maxVerticesCount = 4 + 2 + (2 * mMaxCurlSplits); ByteBuffer vbb = ByteBuffer.allocateDirect(maxVerticesCount * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mVertices = vbb.asFloatBuffer(); mVertices.position(0); if (DRAW_TEXTURE) { ByteBuffer tbb = ByteBuffer .allocateDirect(maxVerticesCount * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexCoords = tbb.asFloatBuffer(); mTexCoords.position(0); } ByteBuffer cbb = ByteBuffer.allocateDirect(maxVerticesCount * 4 * 4); cbb.order(ByteOrder.nativeOrder()); mColors = cbb.asFloatBuffer(); mColors.position(0); if (DRAW_SHADOW) { int maxShadowVerticesCount = (mMaxCurlSplits + 2) * 2 * 2; ByteBuffer scbb = ByteBuffer .allocateDirect(maxShadowVerticesCount * 4 * 4); scbb.order(ByteOrder.nativeOrder()); mShadowColors = scbb.asFloatBuffer(); mShadowColors.position(0); ByteBuffer sibb = ByteBuffer .allocateDirect(maxShadowVerticesCount * 3 * 4); sibb.order(ByteOrder.nativeOrder()); mShadowVertices = sibb.asFloatBuffer(); mShadowVertices.position(0); mDropShadowCount = mSelfShadowCount = 0; } } /** * Sets curl for this mesh. * * @param curlPos * Position for curl 'center'. Can be any point on line collinear * to curl. * @param curlDir * Curl direction, should be normalized. * @param radius * Radius of curl. */ public synchronized void curl(PointF curlPos, PointF curlDir, double radius) { // First add some 'helper' lines used for development. if (DRAW_CURL_POSITION) { mCurlPositionLines.position(0); mCurlPositionLines.put(curlPos.x); mCurlPositionLines.put(curlPos.y - 1.0f); mCurlPositionLines.put(curlPos.x); mCurlPositionLines.put(curlPos.y + 1.0f); mCurlPositionLines.put(curlPos.x - 1.0f); mCurlPositionLines.put(curlPos.y); mCurlPositionLines.put(curlPos.x + 1.0f); mCurlPositionLines.put(curlPos.y); mCurlPositionLines.put(curlPos.x); mCurlPositionLines.put(curlPos.y); mCurlPositionLines.put(curlPos.x + curlDir.x * 2); mCurlPositionLines.put(curlPos.y + curlDir.y * 2); mCurlPositionLines.position(0); } // Actual 'curl' implementation starts here. mVertices.position(0); mColors.position(0); if (DRAW_TEXTURE) { mTexCoords.position(0); } // Calculate curl angle from direction. double curlAngle = Math.acos(curlDir.x); curlAngle = curlDir.y > 0 ? -curlAngle : curlAngle; // Initiate rotated rectangle which's is translated to curlPos and // rotated so that curl direction heads to right (1,0). Vertices are // ordered in ascending order based on x -coordinate at the same time. // And using y -coordinate in very rare case in which two vertices have // same x -coordinate. mTempVertices.addAll(mRotatedVertices); mRotatedVertices.clear(); for (int i = 0; i < 4; ++i) { Vertex v = mTempVertices.remove(0); v.set(mRectangle[i]); v.translate(-curlPos.x, -curlPos.y); v.rotateZ(-curlAngle); int j = 0; for (; j < mRotatedVertices.size(); ++j) { Vertex v2 = mRotatedVertices.get(j); if (v.mPosX > v2.mPosX) { break; } if (v.mPosX == v2.mPosX && v.mPosY > v2.mPosY) { break; } } mRotatedVertices.add(j, v); } // Rotated rectangle lines/vertex indices. We need to find bounding // lines for rotated rectangle. After sorting vertices according to // their x -coordinate we don't have to worry about vertices at indices // 0 and 1. But due to inaccuracy it's possible vertex 3 is not the // opposing corner from vertex 0. So we are calculating distance from // vertex 0 to vertices 2 and 3 - and altering line indices if needed. // Also vertices/lines are given in an order first one has x -coordinate // at least the latter one. This property is used in getIntersections to // see if there is an intersection. int lines[][] = { { 0, 1 }, { 0, 2 }, { 1, 3 }, { 2, 3 } }; { // TODO: There really has to be more 'easier' way of doing this - // not including extensive use of sqrt. Vertex v0 = mRotatedVertices.get(0); Vertex v2 = mRotatedVertices.get(2); Vertex v3 = mRotatedVertices.get(3); double dist2 = Math.sqrt((v0.mPosX - v2.mPosX) * (v0.mPosX - v2.mPosX) + (v0.mPosY - v2.mPosY) * (v0.mPosY - v2.mPosY)); double dist3 = Math.sqrt((v0.mPosX - v3.mPosX) * (v0.mPosX - v3.mPosX) + (v0.mPosY - v3.mPosY) * (v0.mPosY - v3.mPosY)); if (dist2 > dist3) { lines[1][1] = 3; lines[2][1] = 2; } } mVerticesCountFront = mVerticesCountBack = 0; if (DRAW_SHADOW) { mTempShadowVertices.addAll(mDropShadowVertices); mTempShadowVertices.addAll(mSelfShadowVertices); mDropShadowVertices.clear(); mSelfShadowVertices.clear(); } // Length of 'curl' curve. double curlLength = Math.PI * radius; // Calculate scan lines. // TODO: Revisit this code one day. There is room for optimization here. mScanLines.clear(); if (mMaxCurlSplits > 0) { mScanLines.add((double) 0); } for (int i = 1; i < mMaxCurlSplits; ++i) { mScanLines.add((-curlLength * i) / (mMaxCurlSplits - 1)); } // As mRotatedVertices is ordered regarding x -coordinate, adding // this scan line produces scan area picking up vertices which are // rotated completely. One could say 'until infinity'. mScanLines.add(mRotatedVertices.get(3).mPosX - 1); // Start from right most vertex. Pretty much the same as first scan area // is starting from 'infinity'. double scanXmax = mRotatedVertices.get(0).mPosX + 1; for (int i = 0; i < mScanLines.size(); ++i) { // Once we have scanXmin and scanXmax we have a scan area to start // working with. double scanXmin = mScanLines.get(i); // First iterate 'original' rectangle vertices within scan area. for (int j = 0; j < mRotatedVertices.size(); ++j) { Vertex v = mRotatedVertices.get(j); // Test if vertex lies within this scan area. // TODO: Frankly speaking, can't remember why equality check was // added to both ends. Guessing it was somehow related to case // where radius=0f, which, given current implementation, could // be handled much more effectively anyway. if (v.mPosX >= scanXmin && v.mPosX <= scanXmax) { // Pop out a vertex from temp vertices. Vertex n = mTempVertices.remove(0); n.set(v); // This is done solely for triangulation reasons. Given a // rotated rectangle it has max 2 vertices having // intersection. Array<Vertex> intersections = getIntersections( mRotatedVertices, lines, n.mPosX); // In a sense one could say we're adding vertices always in // two, positioned at the ends of intersecting line. And for // triangulation to work properly they are added based on y // -coordinate. And this if-else is doing it for us. if (intersections.size() == 1 && intersections.get(0).mPosY > v.mPosY) { // In case intersecting vertex is higher add it first. mOutputVertices.addAll(intersections); mOutputVertices.add(n); } else if (intersections.size() <= 1) { // Otherwise add original vertex first. mOutputVertices.add(n); mOutputVertices.addAll(intersections); } else { // There should never be more than 1 intersecting // vertex. But if it happens as a fallback simply skip // everything. mTempVertices.add(n); mTempVertices.addAll(intersections); } } } // Search for scan line intersections. Array<Vertex> intersections = getIntersections(mRotatedVertices, lines, scanXmin); // We expect to get 0 or 2 vertices. In rare cases there's only one // but in general given a scan line intersecting rectangle there // should be 2 intersecting vertices. if (intersections.size() == 2) { // There were two intersections, add them based on y // -coordinate, higher first, lower last. Vertex v1 = intersections.get(0); Vertex v2 = intersections.get(1); if (v1.mPosY < v2.mPosY) { mOutputVertices.add(v2); mOutputVertices.add(v1); } else { mOutputVertices.addAll(intersections); } } else if (intersections.size() != 0) { // This happens in a case in which there is a original vertex // exactly at scan line or something went very much wrong if // there are 3+ vertices. What ever the reason just return the // vertices to temp vertices for later use. In former case it // was handled already earlier once iterating through // mRotatedVertices, in latter case it's better to avoid doing // anything with them. mTempVertices.addAll(intersections); } // Add vertices found during this iteration to vertex etc buffers. while (mOutputVertices.size() > 0) { Vertex v = mOutputVertices.remove(0); mTempVertices.add(v); // Untouched vertices. if (i == 0) { v.mAlpha = mFlipTexture ? BACKFACE_ALPHA : FRONTFACE_ALPHA; mVerticesCountFront++; } // 'Completely' rotated vertices. else if (i == mScanLines.size() - 1 || curlLength == 0) { v.mPosX = -(curlLength + v.mPosX); v.mPosZ = 2 * radius; v.mPenumbraX = -v.mPenumbraX; v.mAlpha = mFlipTexture ? FRONTFACE_ALPHA : BACKFACE_ALPHA; mVerticesCountBack++; } // Vertex lies within 'curl'. else { // Even though it's not obvious from the if-else clause, // here v.mPosX is between [-curlLength, 0]. And we can do // calculations around a half cylinder. double rotY = Math.PI * (v.mPosX / curlLength); v.mPosX = radius * Math.sin(rotY); v.mPosZ = radius - (radius * Math.cos(rotY)); v.mPenumbraX *= Math.cos(rotY); // Map color multiplier to [.1f, 1f] range. v.mColor = .1f + .9f * Math.sqrt(Math.sin(rotY) + 1); if (v.mPosZ >= radius) { v.mAlpha = mFlipTexture ? FRONTFACE_ALPHA : BACKFACE_ALPHA; mVerticesCountBack++; } else { v.mAlpha = mFlipTexture ? BACKFACE_ALPHA : FRONTFACE_ALPHA; mVerticesCountFront++; } } // Move vertex back to 'world' coordinates. v.rotateZ(curlAngle); v.translate(curlPos.x, curlPos.y); addVertex(v); // Drop shadow is cast 'behind' the curl. if (DRAW_SHADOW && v.mPosZ > 0 && v.mPosZ <= radius) { ShadowVertex sv = mTempShadowVertices.remove(0); sv.mPosX = v.mPosX; sv.mPosY = v.mPosY; sv.mPosZ = v.mPosZ; sv.mPenumbraX = (v.mPosZ / 2) * -curlDir.x; sv.mPenumbraY = (v.mPosZ / 2) * -curlDir.y; sv.mPenumbraColor = v.mPosZ / radius; int idx = (mDropShadowVertices.size() + 1) / 2; mDropShadowVertices.add(idx, sv); } // Self shadow is cast partly over mesh. if (DRAW_SHADOW && v.mPosZ > radius) { ShadowVertex sv = mTempShadowVertices.remove(0); sv.mPosX = v.mPosX; sv.mPosY = v.mPosY; sv.mPosZ = v.mPosZ; sv.mPenumbraX = ((v.mPosZ - radius) / 3) * v.mPenumbraX; sv.mPenumbraY = ((v.mPosZ - radius) / 3) * v.mPenumbraY; sv.mPenumbraColor = (v.mPosZ - radius) / (2 * radius); int idx = (mSelfShadowVertices.size() + 1) / 2; mSelfShadowVertices.add(idx, sv); } } // Switch scanXmin as scanXmax for next iteration. scanXmax = scanXmin; } mVertices.position(0); mColors.position(0); if (DRAW_TEXTURE) { mTexCoords.position(0); } // Add shadow Vertices. if (DRAW_SHADOW) { mShadowColors.position(0); mShadowVertices.position(0); mDropShadowCount = 0; for (int i = 0; i < mDropShadowVertices.size(); ++i) { ShadowVertex sv = mDropShadowVertices.get(i); mShadowVertices.put((float) sv.mPosX); mShadowVertices.put((float) sv.mPosY); mShadowVertices.put((float) sv.mPosZ); mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX)); mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY)); mShadowVertices.put((float) sv.mPosZ); for (int j = 0; j < 4; ++j) { double color = SHADOW_OUTER_COLOR[j] + (SHADOW_INNER_COLOR[j] - SHADOW_OUTER_COLOR[j]) * sv.mPenumbraColor; mShadowColors.put((float) color); } mShadowColors.put(SHADOW_OUTER_COLOR); mDropShadowCount += 2; } mSelfShadowCount = 0; for (int i = 0; i < mSelfShadowVertices.size(); ++i) { ShadowVertex sv = mSelfShadowVertices.get(i); mShadowVertices.put((float) sv.mPosX); mShadowVertices.put((float) sv.mPosY); mShadowVertices.put((float) sv.mPosZ); mShadowVertices.put((float) (sv.mPosX + sv.mPenumbraX)); mShadowVertices.put((float) (sv.mPosY + sv.mPenumbraY)); mShadowVertices.put((float) sv.mPosZ); for (int j = 0; j < 4; ++j) { double color = SHADOW_OUTER_COLOR[j] + (SHADOW_INNER_COLOR[j] - SHADOW_OUTER_COLOR[j]) * sv.mPenumbraColor; mShadowColors.put((float) color); } mShadowColors.put(SHADOW_OUTER_COLOR); mSelfShadowCount += 2; } mShadowColors.position(0); mShadowVertices.position(0); } } /** * Draws our mesh. */ public synchronized void draw(GL10 gl) { // First allocate texture if there is not one yet. if (DRAW_TEXTURE && mTextureIds == null) { // Generate texture. mTextureIds = new int[2]; gl.glGenTextures(2, mTextureIds, 0); // Set texture attributes. gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); //CAGS: Back Texture gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[1]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); } // If mBitmap != null we have a new texture. if (DRAW_TEXTURE && mNewTex) { gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0); //mBitmap.recycle(); //mBitmap = null; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[1]); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmapB, 0); //mBitmapB.recycle(); //mBitmapB = null; mNewTex = false; } if (DRAW_TEXTURE) { gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]); } /* CAGS: Invert the textures if mSwapSheet == true -> Not acomplished due * to not figured out where to put again swapSheet = false and avoid a bad behaivor * of the curled page if (DRAW_TEXTURE) { if (!mSwapSheet){ gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]); }else{ gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[1]); } }*/ // Some 'global' settings. gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); // TODO: Drop shadow drawing is done temporarily here to hide some // problems with its calculation. if (DRAW_SHADOW) { gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_FLOAT, 0, mShadowColors); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mShadowVertices); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mDropShadowCount); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); gl.glDisable(GL10.GL_BLEND); } // Enable texture coordinates. if (DRAW_TEXTURE) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoords); } gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices); // Enable color array. gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_FLOAT, 0, mColors); // Draw blank / 'white' front facing vertices. gl.glDisable(GL10.GL_TEXTURE_2D); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront); // Draw front facing texture. // TODO: Decide whether it's really needed to have alpha blending for // front facing texture. If not, GL_BLEND isn't needed, possibly // increasing performance. The heck, is it needed at all? if (DRAW_TEXTURE) { gl.glEnable(GL10.GL_BLEND); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, mVerticesCountFront); gl.glDisable(GL10.GL_TEXTURE_2D); gl.glDisable(GL10.GL_BLEND); } if (DRAW_TEXTURE) { gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[1]); } /* CAGS: Invert the textures if mSwapSheet == true -> Not acomplished due * to not figured out where to put again swapSheet = false and avoid a bad behaivor * of the curled page if (!mSwapSheet){ gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[1]); }else{ gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureIds[0]); //mSwapSheet=false; } }*/ int backStartIdx = Math.max(0, mVerticesCountFront - 2); int backCount = mVerticesCountFront + mVerticesCountBack - backStartIdx; // Draw blank / 'white' back facing vertices. gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, backStartIdx, backCount); // Draw back facing texture. if (DRAW_TEXTURE) { gl.glEnable(GL10.GL_BLEND); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, backStartIdx, backCount); gl.glDisable(GL10.GL_TEXTURE_2D); gl.glDisable(GL10.GL_BLEND); } // Disable textures and color array. gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); if (DRAW_POLYGON_OUTLINES) { gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glLineWidth(1.0f); gl.glColor4f(0.5f, 0.5f, 1.0f, 1.0f); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertices); gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, mVerticesCountFront); gl.glDisable(GL10.GL_BLEND); } if (DRAW_CURL_POSITION) { gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glLineWidth(1.0f); gl.glColor4f(1.0f, 0.5f, 0.5f, 1.0f); gl.glVertexPointer(2, GL10.GL_FLOAT, 0, mCurlPositionLines); gl.glDrawArrays(GL10.GL_LINES, 0, mCurlPositionLinesCount * 2); gl.glDisable(GL10.GL_BLEND); } if (DRAW_SHADOW) { gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_FLOAT, 0, mShadowColors); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mShadowVertices); gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, mDropShadowCount, mSelfShadowCount); gl.glDisableClientState(GL10.GL_COLOR_ARRAY); gl.glDisable(GL10.GL_BLEND); } gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } /** * Resets mesh to 'initial' state. Meaning this mesh will draw a plain * textured rectangle after call to this method. */ public synchronized void reset() { mVertices.position(0); mColors.position(0); if (DRAW_TEXTURE) { mTexCoords.position(0); } for (int i = 0; i < 4; ++i) { addVertex(mRectangle[i]); } mVerticesCountFront = 4; mVerticesCountBack = 0; mVertices.position(0); mColors.position(0); if (DRAW_TEXTURE) { mTexCoords.position(0); } mDropShadowCount = mSelfShadowCount = 0; } /** * Resets allocated texture id forcing creation of new one. After calling * this method you most likely want to set bitmap too as it's lost. This * method should be called only once e.g GL context is re-created as this * method does not release previous texture id, only makes sure new one is * requested on next render. */ public synchronized void resetTexture() { mTextureIds = null; } /** * Sets new texture for this mesh. */ public synchronized void setBitmap(Bitmap bitmap, Bitmap bitmapB) { if (DRAW_TEXTURE) { // Bitmap original size. int w = bitmap.getWidth(); int h = bitmap.getHeight(); // Bitmap size expanded to next power of two. This is done due to // the requirement on many devices, texture width and height should // be power of two. int newW = getNextHighestPO2(w); int newH = getNextHighestPO2(h); //Recycle the previous bitmap if it still exists. if(mBitmap != null){ mBitmap.recycle(); mBitmap = null; } if(mBitmapB != null){ mBitmapB.recycle(); mBitmapB = null; } // TODO: Is there another way to create a bigger Bitmap and copy // original Bitmap to it more efficiently? Immutable bitmap anyone? mBitmap = Bitmap.createBitmap(newW, newH, bitmap.getConfig()); Canvas c = new Canvas(mBitmap); c.drawBitmap(bitmap, 0, 0, null); //Recycle the now unused bitmap bitmap.recycle(); bitmap = null; if (bitmapB != null){ // Bitmap original size. int w2 = bitmapB.getWidth(); int h2 = bitmapB.getHeight(); // Bitmap size expanded to next power of two. This is done due to // the requirement on many devices, texture width and height should // be power of two. int newW2 = getNextHighestPO2(w2); int newH2 = getNextHighestPO2(h2); // TODO: Is there another way to create a bigger Bitmap and copy // original Bitmap to it more efficiently? Immutable bitmap anyone? mBitmapB= Bitmap.createBitmap(newW2, newH2, bitmapB.getConfig()); Canvas c2 = new Canvas(mBitmapB); //CAGS: Flip Back facing Bitmap Matrix flipHorizontalMatrix = new Matrix(); flipHorizontalMatrix.setScale(-1,1); flipHorizontalMatrix.postTranslate(w2,0); c2.drawBitmap(bitmapB, flipHorizontalMatrix, null); //Recycle the now unused bitmap bitmapB.recycle(); bitmapB = null; } else { mBitmapB = mBitmap; } //CAGS: Store w2 for later flip mWidthAux = w; mNewTex = true; // Calculate final texture coordinates. float texX = (float) w / newW; float texY = (float) h / newH; mTextureRect.set(0f, 0f, texX, texY); if (mFlipTexture) { setTexCoords(texX, 0f, 0f, texY); } else { setTexCoords(0f, 0f, texX, texY); } } } /** * Swap Front and Back Sheets/Textures. */ /*CAGS: This method depends on keeping the mBitmaps objects, I supose it consume more memory due to keep those bitmaps in memory.*/ // TODO: Optimize the swap of textures without keeping the mBitmaps // in memory, see draw() method for a reference on how I was trying to do it public void swapSheet (){ Bitmap aux; aux = mBitmap; mBitmap= Bitmap.createBitmap(mBitmapB); Canvas c = new Canvas(mBitmap); //Flip Matrix Matrix flipHorizontalMatrix = new Matrix(); flipHorizontalMatrix.setScale(-1,1); flipHorizontalMatrix.postTranslate(mWidthAux,0); c.drawBitmap(mBitmap, flipHorizontalMatrix, null); mBitmapB= Bitmap.createBitmap(aux); Canvas c2 = new Canvas(mBitmapB); c2.drawBitmap(mBitmapB, flipHorizontalMatrix, null); mNewTex = true; } /** * If true, flips texture sideways. */ public synchronized void setFlipTexture(boolean flipTexture) { mFlipTexture = flipTexture; if (mFlipTexture) { setTexCoords(mTextureRect.right, mTextureRect.top, mTextureRect.left, mTextureRect.bottom); } else { setTexCoords(mTextureRect.left, mTextureRect.top, mTextureRect.right, mTextureRect.bottom); } for (int i = 0; i < 4; ++i) { mRectangle[i].mAlpha = mFlipTexture ? BACKFACE_ALPHA : FRONTFACE_ALPHA; } } /** * Update mesh bounds. */ public void setRect(RectF r) { mRectangle[0].mPosX = r.left; mRectangle[0].mPosY = r.top; mRectangle[1].mPosX = r.left; mRectangle[1].mPosY = r.bottom; mRectangle[2].mPosX = r.right; mRectangle[2].mPosY = r.top; mRectangle[3].mPosX = r.right; mRectangle[3].mPosY = r.bottom; } /** * Adds vertex to buffers. */ private void addVertex(Vertex vertex) { mVertices.put((float) vertex.mPosX); mVertices.put((float) vertex.mPosY); mVertices.put((float) vertex.mPosZ); mColors.put((float) vertex.mColor); mColors.put((float) vertex.mColor); mColors.put((float) vertex.mColor); mColors.put((float) vertex.mAlpha); if (DRAW_TEXTURE) { mTexCoords.put((float) vertex.mTexX); mTexCoords.put((float) vertex.mTexY); } } /** * Calculates intersections for given scan line. */ private Array<Vertex> getIntersections(Array<Vertex> vertices, int[][] lineIndices, double scanX) { mIntersections.clear(); // Iterate through rectangle lines each re-presented as a pair of // vertices. for (int j = 0; j < lineIndices.length; j++) { Vertex v1 = vertices.get(lineIndices[j][0]); Vertex v2 = vertices.get(lineIndices[j][1]); // Here we expect that v1.mPosX >= v2.mPosX and wont do intersection // test the opposite way. if (v1.mPosX > scanX && v2.mPosX < scanX) { // There is an intersection, calculate coefficient telling 'how // far' scanX is from v2. double c = (scanX - v2.mPosX) / (v1.mPosX - v2.mPosX); Vertex n = mTempVertices.remove(0); n.set(v2); n.mPosX = scanX; n.mPosY += (v1.mPosY - v2.mPosY) * c; if (DRAW_TEXTURE) { n.mTexX += (v1.mTexX - v2.mTexX) * c; n.mTexY += (v1.mTexY - v2.mTexY) * c; } if (DRAW_SHADOW) { n.mPenumbraX += (v1.mPenumbraX - v2.mPenumbraX) * c; n.mPenumbraY += (v1.mPenumbraY - v2.mPenumbraY) * c; } mIntersections.add(n); } } return mIntersections; } /** * Calculates the next highest power of two for a given integer. */ private int getNextHighestPO2(int n) { n -= 1; n = n | (n >> 1); n = n | (n >> 2); n = n | (n >> 4); n = n | (n >> 8); n = n | (n >> 16); n = n | (n >> 32); return n + 1; } /** * Sets texture coordinates to mRectangle vertices. */ private synchronized void setTexCoords(float left, float top, float right, float bottom) { mRectangle[0].mTexX = left; mRectangle[0].mTexY = top; mRectangle[1].mTexX = left; mRectangle[1].mTexY = bottom; mRectangle[2].mTexX = right; mRectangle[2].mTexY = top; mRectangle[3].mTexX = right; mRectangle[3].mTexY = bottom; } /** * Simple fixed size array implementation. */ private class Array<T> { private Object[] mArray; private int mSize; private int mCapacity; public Array(int capacity) { mCapacity = capacity; mArray = new Object[capacity]; } public void add(int index, T item) { if (index < 0 || index > mSize || mSize >= mCapacity) { throw new IndexOutOfBoundsException(); } for (int i = mSize; i > index; --i) { mArray[i] = mArray[i - 1]; } mArray[index] = item; ++mSize; } public void add(T item) { if (mSize >= mCapacity) { throw new IndexOutOfBoundsException(); } mArray[mSize++] = item; } public void addAll(Array<T> array) { if (mSize + array.size() > mCapacity) { throw new IndexOutOfBoundsException(); } for (int i = 0; i < array.size(); ++i) { mArray[mSize++] = array.get(i); } } public void clear() { mSize = 0; } @SuppressWarnings("unchecked") public T get(int index) { if (index < 0 || index >= mSize) { throw new IndexOutOfBoundsException(); } return (T) mArray[index]; } @SuppressWarnings("unchecked") public T remove(int index) { if (index < 0 || index >= mSize) { throw new IndexOutOfBoundsException(); } T item = (T) mArray[index]; for (int i = index; i < mSize - 1; ++i) { mArray[i] = mArray[i + 1]; } --mSize; return item; } public int size() { return mSize; } } /** * Holder for shadow vertex information. */ private class ShadowVertex { public double mPosX; public double mPosY; public double mPosZ; public double mPenumbraX; public double mPenumbraY; public double mPenumbraColor; } /** * Holder for vertex information. */ private class Vertex { public double mPosX; public double mPosY; public double mPosZ; public double mTexX; public double mTexY; public double mPenumbraX; public double mPenumbraY; public double mColor; public double mAlpha; public Vertex() { mPosX = mPosY = mPosZ = mTexX = mTexY = 0; mColor = mAlpha = 1; } public void rotateZ(double theta) { double cos = Math.cos(theta); double sin = Math.sin(theta); double x = mPosX * cos + mPosY * sin; double y = mPosX * -sin + mPosY * cos; mPosX = x; mPosY = y; double px = mPenumbraX * cos + mPenumbraY * sin; double py = mPenumbraX * -sin + mPenumbraY * cos; mPenumbraX = px; mPenumbraY = py; } public void set(Vertex vertex) { mPosX = vertex.mPosX; mPosY = vertex.mPosY; mPosZ = vertex.mPosZ; mTexX = vertex.mTexX; mTexY = vertex.mTexY; mPenumbraX = vertex.mPenumbraX; mPenumbraY = vertex.mPenumbraY; mColor = vertex.mColor; mAlpha = vertex.mAlpha; } public void translate(double dx, double dy) { mPosX += dx; mPosY += dy; } } }
apache-2.0
rocye/wx-idk
src/test/java/org/wx/common/Config.java
2241
package org.wx.common; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; public class Config { private static ResourceBundle resources = null; private static Map propertyMap = new HashMap(); private static void getBundle() { if (resources == null) resources = ResourceBundle.getBundle("application", Locale.getDefault()); } public static String getAttribute(String name) { String value = (String) propertyMap.get(name); if (value == null) { getBundle(); if (resources != null) { try { value = resources.getString(name); } catch (MissingResourceException exception) { return null; } } } return value; } public static Map getAttributesMap(String name) { Map map = (Map) propertyMap.get(name); if (map == null) { getBundle(); try { String keyStr = resources.getString(name); String[] keys = (String[]) null; if (keyStr != null) { keys = keyStr.split(","); } map = new HashMap(); if (keys != null) { for (int i = 0; i < keys.length; i++) { String value = resources .getString(name + "." + keys[i]); map.put(keys[i], value); } } propertyMap.put(name, map); } catch (MissingResourceException exception) { return null; } } return map; } public static Set getAttributesSet(String name) { Set set = (Set) propertyMap.get(name); if (set == null) { set = new HashSet(); getBundle(); try { String value = resources.getString(name); String[] ips = (String[]) null; if (value != null) { ips = value.split(","); } if (ips != null) { for (int i = 0; i < ips.length; i++) { set.add(ips[i]); } } propertyMap.put(name, set); } catch (MissingResourceException exception) { return null; } } return set; } public static void remove() { resources = null; propertyMap.clear(); } public static void main(String[] args) { System.out.println(getAttribute("sessionOperator.class.name")); } }
apache-2.0
ixufeng/ECollege
dao/src/main/java/com/xf/college/dao/CourseDao.java
180
package com.xf.college.dao; import com.xf.college.model.Course; /** * Created by xufeng on 2017/4/23. */ public interface CourseDao extends BaseDao<Course,String> { }
apache-2.0
samini/gort-public
Source/GortGUIv2/Gort/database/src/org/cmuchimps/gort/modules/database/Installer.java
1134
/* Copyright 2014 Shahriyar Amini Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.cmuchimps.gort.modules.database; import org.cmuchimps.gort.api.gort.GortDatabaseServiceFactory; import org.openide.modules.ModuleInstall; public class Installer extends ModuleInstall { @Override public void restored() { GortDatabaseServiceFactory gdsf = GortDatabaseServiceFactory.getDefault(); if (gdsf.createGortUser()) { System.out.println("Created gort database user."); } else { System.out.println("Assuming gort database user exists."); } } }
apache-2.0
jajakobyly/rustidea
tests/org/rustidea/lexer/RsLexerTest.java
9280
/* * Copyright 2015 Marek Kaput * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rustidea.lexer; import com.intellij.lexer.Lexer; import org.jetbrains.annotations.NotNull; import static com.intellij.psi.TokenType.WHITE_SPACE; import static org.rustidea.psi.types.RsTokenTypes.*; public class RsLexerTest extends IRsLexerTestCase { // Tests prefixed with "testRust" are based on Rust's test suite // https://github.com/rust-lang/rust/blob/405c616eaf4e58a8bed67924c364c8e9c83b2581/src/libsyntax/parse/lexer/mod.rs public void testUnfinishedCharacters() { MultiTest test = new MultiTest() .test("'", CHAR_LIT) .test("''", CHAR_LIT) .test("'\\", CHAR_LIT); doTest(test); } public void testUnfinishedStrings() { MultiTest test = new MultiTest() .test("\"", STRING_LIT) .test("\"a", STRING_LIT) .test("\"\\", STRING_LIT); doTest(test); } public void testUnfinishedCharAndLifetimeConflicts() { MultiTest test = new MultiTest() .test("'", CHAR_LIT) .test("'a", PRIM_IDENT) .test("'1", CHAR_LIT) .test("'aaaa", PRIM_IDENT) .test("'a'", CHAR_LIT); doTest(test); } public void testRawStringWithTooManyHashes() { CompositeTest test = new CompositeTest( "r###\"foo\"####") .test("r###\"foo\"###", RAW_STRING_LIT) .test("#", OP_HASH); doTest(test); } public void testRawStringWithTooManyHashes2() { CompositeTest test = new CompositeTest( "r###\"foo\"######") .test("r###\"foo\"###", RAW_STRING_LIT) .test("#", OP_HASH) .test("#", OP_HASH) .test("#", OP_HASH); doTest(test); } public void testRawStringWithTooManyHashes3() { CompositeTest test = new CompositeTest( "r\"foo\"###") .test("r\"foo\"", RAW_STRING_LIT) .test("#", OP_HASH) .test("#", OP_HASH) .test("#", OP_HASH); doTest(test); } public void testRawStringWithTooManyHashesAndSuffix() { CompositeTest test = new CompositeTest( "r\"foo\"###suffix") .test("r\"foo\"", RAW_STRING_LIT) .test("#", OP_HASH) .test("#", OP_HASH) .test("#", OP_HASH) .test("suffix", IDENTIFIER); doTest(test); } public void testRawStringWithTooFewHashesAtEOF() { MultiTest test = new MultiTest() .test("r###\"foo", RAW_STRING_LIT) .test("r###\"foo\"", RAW_STRING_LIT) .test("r###\"foo\"##", RAW_STRING_LIT); doTest(test); } // https://github.com/rust-lang/rust/issues/7048 public void testFlipTable() { CompositeTest test = new CompositeTest( "fn _\u256f\u00b0\u25a1\u00b0\u256f\ufe35\u253b\u2501\u253b() {}") .test("fn", KW_FN) .test(" ", WHITE_SPACE) .test("_", OP_UNDERSCORE) .test("\u256f", BAD_CHARACTER) .test("\u00b0", BAD_CHARACTER) .test("\u25a1", BAD_CHARACTER) .test("\u00b0", BAD_CHARACTER) .test("\u256f", BAD_CHARACTER) .test("\ufe35", BAD_CHARACTER) .test("\u253b", BAD_CHARACTER) .test("\u2501", BAD_CHARACTER) .test("\u253b", BAD_CHARACTER) .test("(", OP_LPAREN) .test(")", OP_RPAREN) .test(" ", WHITE_SPACE) .test("{", OP_LBRACE) .test("}", OP_RBRACE); doTest(test); } public void testMultilineLineDoc() { CompositeTest test = new CompositeTest( "/// foo", "/// bar", "/// baz") .test("/// foo\n/// bar\n/// baz", LINE_DOC); doTest(test); } public void testMultilineLineDoc2() { CompositeTest test = new CompositeTest( "//! foo", "//! bar", "//! baz") .test("//! foo\n//! bar\n//! baz", LINE_INNER_DOC); doTest(test); } public void testMultilineLineDoc3() { CompositeTest test = new CompositeTest( "//! foo", "//! bar", "/// foo", "/// bar") .test("//! foo\n//! bar", LINE_INNER_DOC).test("\n", WHITE_SPACE) .test("/// foo\n/// bar", LINE_DOC); doTest(test); } public void testMultilineLineDoc4() { CompositeTest test = new CompositeTest( "// foo", "/// foo", "/// bar", "// bar") .test("// foo", LINE_COMMENT).test("\n", WHITE_SPACE) .test("/// foo\n/// bar", LINE_DOC).test("\n", WHITE_SPACE) .test("// bar", LINE_COMMENT); doTest(test); } public void testMultilineLineDoc5() { CompositeTest test = new CompositeTest( "/// foo", "// foo", "/// bar", "// bar") .test("/// foo", LINE_DOC).test("\n", WHITE_SPACE) .test("// foo", LINE_COMMENT).test("\n", WHITE_SPACE) .test("/// bar", LINE_DOC).test("\n", WHITE_SPACE) .test("// bar", LINE_COMMENT); doTest(test); } public void testMultilineLineDoc6() { CompositeTest test = new CompositeTest( "/// foo", "///", "/// bar", "// bar") .test("/// foo\n///\n/// bar", LINE_DOC).test("\n", WHITE_SPACE) .test("// bar", LINE_COMMENT); doTest(test); } public void testMultilineLineDoc7() { CompositeTest test = new CompositeTest( "///////", "/// foo", "///////", "/// bar", "///////", "") .test("///////\n/// foo\n///////\n/// bar\n///////", LINE_DOC).test("\n", WHITE_SPACE); doTest(test); } public void testRust1() { CompositeTest test = new CompositeTest( "/* my source file */ ", "fn main() { println!(\"zebra\"); }", "") .test("/* my source file */", BLOCK_COMMENT) .test(" \n", WHITE_SPACE) .test("fn", KW_FN) .test(" ", WHITE_SPACE) .test("main", IDENTIFIER) .test("(", OP_LPAREN) .test(")", OP_RPAREN) .test(" ", WHITE_SPACE) .test("{", OP_LBRACE) .test(" ", WHITE_SPACE) .test("println", IDENTIFIER) .test("!", OP_BANG) .test("(", OP_LPAREN) .test("\"zebra\"", STRING_LIT) .test(")", OP_RPAREN) .test(";", OP_SEMICOLON) .test(" ", WHITE_SPACE) .test("}", OP_RBRACE).test("\n", WHITE_SPACE); doTest(test); } public void testRustCharacters() { MultiTest test = new MultiTest() .test("'a'", CHAR_LIT) .test("' '", CHAR_LIT) .test("'\\n'", CHAR_LIT); doTest(test); } public void testRustLifetimeName() { doTest("'abc", PRIM_IDENT); } public void testRustRawString() { doTest("r###\"\"a\\b\12\"\"###", RAW_STRING_LIT); } public void testRustLiteralSuffixes() { MultiTest test = new MultiTest() .test("'a'", CHAR_LIT) .test("b'a'", BYTE_LIT) .test("\"a\"", STRING_LIT) .test("b\"a\"", BYTE_STRING_LIT) .test("1234", INT_LIT) .test("0b101", INT_LIT) .test("0xABC", INT_LIT) .test("1.0", FLOAT_LIT) .test("1.0e10", FLOAT_LIT) .test("2us", INT_LIT) .test("r###\"raw\"###suffix", RAW_STRING_LIT) .test("br###\"raw\"###suffix", RAW_BYTE_STRING_LIT); doTest(test); } public void testRustLineDocComments() { MultiTest test = new MultiTest() .test("///", LINE_DOC) .test("/// blah", LINE_DOC) .test("////", LINE_COMMENT); doTest(test); } public void testRustNestedBlockComments() { CompositeTest test = new CompositeTest("/* /* */ */'a'") .test("/* /* */ */", BLOCK_COMMENT) .test("'a'", CHAR_LIT); doTest(test); } public void testRustCrlfComments() { CompositeTest test = new CompositeTest("// test\r\n/// test\r\n") .test("// test", LINE_COMMENT).test("\r\n", WHITE_SPACE) .test("/// test", LINE_DOC).test("\r\n", WHITE_SPACE); doTest(test); } @NotNull @Override protected Lexer createLexer() { return new RsLexer(); } }
apache-2.0
KAMP-Research/KAMP
bundles/Toometa/toometa.pcmarchoptions.edit/src/pcmarchoptions/provider/PCM_OnlySingleInstantiationItemProvider.java
3732
/** */ package pcmarchoptions.provider; import archoptions.provider.OnlySingleInstantiationItemProvider; import java.util.Collection; import java.util.List; import org.eclipse.emf.common.notify.AdapterFactory; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor; import pcmarchoptions.PCM_OnlySingleInstantiation; import pcmarchoptions.PcmarchoptionsPackage; /** * This is the item provider adapter for a {@link pcmarchoptions.PCM_OnlySingleInstantiation} object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public class PCM_OnlySingleInstantiationItemProvider extends OnlySingleInstantiationItemProvider { /** * This constructs an instance from a factory and a notifier. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public PCM_OnlySingleInstantiationItemProvider(AdapterFactory adapterFactory) { super(adapterFactory); } /** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); addAssemblyContextsPropertyDescriptor(object); } return itemPropertyDescriptors; } /** * This adds a property descriptor for the Assembly Contexts feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected void addAssemblyContextsPropertyDescriptor(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString("_UI_PCM_OnlySingleInstantiation_assemblyContexts_feature"), getString("_UI_PropertyDescriptor_description", "_UI_PCM_OnlySingleInstantiation_assemblyContexts_feature", "_UI_PCM_OnlySingleInstantiation_type"), PcmarchoptionsPackage.Literals.PCM_ONLY_SINGLE_INSTANTIATION__ASSEMBLY_CONTEXTS, true, false, true, null, null, null)); } /** * This returns PCM_OnlySingleInstantiation.gif. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object getImage(Object object) { return overlayImage(object, getResourceLocator().getImage("full/obj16/PCM_OnlySingleInstantiation")); } /** * This returns the label text for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getText(Object object) { String label = ((PCM_OnlySingleInstantiation)object).getDescription(); return label == null || label.length() == 0 ? getString("_UI_PCM_OnlySingleInstantiation_type") : getString("_UI_PCM_OnlySingleInstantiation_type") + " " + label; } /** * This handles model notifications by calling {@link #updateChildren} to update any cached * children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void notifyChanged(Notification notification) { updateChildren(notification); super.notifyChanged(notification); } /** * This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children * that can be created under this object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } }
apache-2.0
dmmcerlean/cloud-bigtable-client
bigtable-grpc-interface/src/main/java/com/google/cloud/bigtable/grpc/BigtableGrpcClientOptions.java
3194
/* * Copyright 2014 Google Inc. All Rights Reserved. * * 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.cloud.bigtable.grpc; import java.util.concurrent.TimeUnit; /** * Options controlling behavior of the BigtableGrpcClient. */ public class BigtableGrpcClientOptions { /** * Builder for BigtableGrpcClientOptions. */ public static class Builder { private int streamingBufferSize = BigtableGrpcClient.SCANNER_BUFFER_SIZE; // We can timeout when reading large cells with a low value here. With a 10MB // cell limit, 60 seconds allows our connection to drop to ~170kbyte/s. A 10 second // timeout requires 1Mbyte/s private int readPartialRowTimeoutMillis = (int) TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS); private RetryOptions.Builder streamingRetryOptionsBuilder = new RetryOptions.Builder(); /** * Set the maximum number of messages to buffer when scanning. */ public Builder setStreamingBufferSize(int streamingBufferSize) { this.streamingBufferSize = streamingBufferSize; return this; } public Builder setReadPartialRowTimeoutMillis(int timeout) { this.readPartialRowTimeoutMillis = timeout; return this; } /** * A builder for streaming readRows RetryOptions. */ public RetryOptions.Builder getStreamingRetryOptionsBuilder() { return streamingRetryOptionsBuilder; } /** * Construct a new BigtableGrpcClientOptions object. */ public BigtableGrpcClientOptions build() { return new BigtableGrpcClientOptions( streamingBufferSize, readPartialRowTimeoutMillis, streamingRetryOptionsBuilder.build()); } } private final int streamingBufferSize; private final int readPartialRowTimeoutMillis; private final RetryOptions streamingRetryOptions; public BigtableGrpcClientOptions( int streamingBufferSize, int readPartialRowTimeoutMillis, RetryOptions streamingRetryOptions) { this.streamingBufferSize = streamingBufferSize; this.readPartialRowTimeoutMillis = readPartialRowTimeoutMillis; this.streamingRetryOptions = streamingRetryOptions; } /** * The maximum number of messages to buffer when scanning. */ public int getStreamingBufferSize() { return streamingBufferSize; } /** * A timeout for reading individual ReadRowsResponse messages from a stream. */ public int getReadPartialRowTimeoutMillis() { return readPartialRowTimeoutMillis; } /** * Streaming readRows RetryOptions. */ public RetryOptions getStreamingRetryOptions() { return streamingRetryOptions; } }
apache-2.0
nagyist/marketcetera
photon/photon/plugins/org.marketcetera.photon.marketdata/src/main/java/org/marketcetera/photon/internal/marketdata/MarketDataManager.java
10465
package org.marketcetera.photon.internal.marketdata; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.management.AttributeChangeNotification; import javax.management.NotificationEmitter; import org.eclipse.core.runtime.ListenerList; import org.eclipse.core.runtime.Platform; import org.marketcetera.marketdata.AbstractMarketDataModule; import org.marketcetera.marketdata.AbstractMarketDataModuleMXBean; import org.marketcetera.marketdata.Capability; import org.marketcetera.marketdata.FeedStatus; import org.marketcetera.module.ModuleException; import org.marketcetera.module.ModuleManager; import org.marketcetera.module.ModuleURN; import org.marketcetera.photon.internal.marketdata.MarketDataFeed.FeedStatusEvent; import org.marketcetera.photon.marketdata.IFeedStatusChangedListener; import org.marketcetera.photon.marketdata.IMarketData; import org.marketcetera.photon.marketdata.IMarketDataFeed; import org.marketcetera.photon.marketdata.IMarketDataManager; import org.marketcetera.photon.marketdata.MarketDataConstants; import org.marketcetera.photon.marketdata.IFeedStatusChangedListener.IFeedStatusEvent; import org.marketcetera.util.misc.ClassVersion; import com.google.inject.Inject; /* $License$ */ /** * Internal implementation of {@link IMarketDataManager}. * * <h4>Market Data Module Abstraction</h4> * * This class discovers available market data modules that follow the following * conventions: * <ol> * <li>Have a module provider type of "mdata"</li> * <li>Are singleton modules</li> * <li>Implement the {@link AbstractMarketDataModuleMXBean} interface</li> * <li>Implement the {@link NotificationEmitter} interface</li> * </ol> * Modules that don't adhere to these conventions will not be supported. * Additionally, although it is not validated, the module must send * {@link AttributeChangeNotification attribute change notifications} for the * "FeedStatus" attribute when the feed's status changes in order for this class * to function properly. Typically, all market data modules will extend * {@link AbstractMarketDataModule}, which provides much of the needed * functionality. * <p> * Each market data module is proxied by a {@link MarketDataFeed} instance that * handles the interactions with the underlying modules. * * <h4>Active Feed Management</h4> * * The current market data UI paradigm associates all market data display with a * single feed. This class supports this model by maintaining an active feed and * delegating all requests to that feed. It also has an internal * {@link IFeedStatusChangedListener} that listens to feed status changes on all * its feeds and directs notifications from the active feed to listeners * registered with this class. * * @author <a href="mailto:will@marketcetera.com">Will Horn</a> * @version $Id: MarketDataManager.java 16154 2012-07-14 16:34:05Z colin $ * @since 1.0.0 */ @ClassVersion("$Id: MarketDataManager.java 16154 2012-07-14 16:34:05Z colin $") public final class MarketDataManager implements IMarketDataManager { private static final String USER_MSG_CATEGORY = org.marketcetera.core.Messages.USER_MSG_CATEGORY; private final ModuleManager mModuleManager; private final ListenerList mActiveFeedListeners = new ListenerList(); private final AtomicBoolean mReconnecting = new AtomicBoolean(false); private final AtomicReference<Map<String, MarketDataFeed>> mFeeds = new AtomicReference<Map<String, MarketDataFeed>>(); private volatile MarketDataFeed mActiveFeed; private final IFeedStatusChangedListener mFeedStatusChangesListener = new IFeedStatusChangedListener() { @Override public void feedStatusChanged(final IFeedStatusEvent event) { if (event.getSource() == mActiveFeed) { notifyListeners(event); } } }; private final MarketData mMarketData; /** * Constructor. * * @param moduleManager * the module manager to use * @param marketData * the MarketData instance */ @Inject public MarketDataManager(final ModuleManager moduleManager, final MarketData marketData) { mModuleManager = moduleManager; mMarketData = marketData; } /* * Lazy initialization. This is necessary since the module manager is not * guaranteed to be fully initialized when this object is constructed in the * bundle activator. */ private Map<String, MarketDataFeed> getFeeds() { Map<String, MarketDataFeed> feeds = mFeeds.get(); if (feeds != null) { return feeds; } feeds = new HashMap<String, MarketDataFeed>(); List<ModuleURN> providers = mModuleManager.getProviders(); for (ModuleURN providerURN : providers) { if (providerURN.providerType().equals( MarketDataFeed.MARKET_DATA_PROVIDER_TYPE)) { try { MarketDataFeed feed = new MarketDataFeed(providerURN); feed .addFeedStatusChangedListener(mFeedStatusChangesListener); feeds.put(providerURN.toString(), feed); } catch (Exception e) { Messages.MARKET_DATA_MANAGER_IGNORING_PROVIDER.warn(this, e, providerURN); } } } if (mFeeds.compareAndSet(null, feeds)) { return feeds; } return mFeeds.get(); } @Override public IMarketData getMarketData() { return mMarketData; } @Override public Collection<? extends IMarketDataFeed> getProviders() { return Collections.unmodifiableCollection(getFeeds().values()); } @Override public void reconnectFeed() { reconnectFeed(getDefaultActiveFeed()); } /** * Private implementation method, only public for testing purposes. * <p> * TODO: Refactor for better encapsulation */ public void reconnectFeed(final String providerId) { if (!mReconnecting.compareAndSet(false, true)) { return; } try { synchronized (this) { final MarketDataFeed oldFeed = mActiveFeed; mActiveFeed = getFeeds().get(providerId); if (mActiveFeed == null && oldFeed == null) { // mReconnecting is reset in the finally block return; } if (mActiveFeed != null) { try { if (!mModuleManager.getModuleInfo(mActiveFeed.getURN()) .getState().isStarted()) { mModuleManager.start(mActiveFeed.getURN()); } else { mActiveFeed.reconnect(); } } catch (ModuleException e) { // TODO: May be better to propagate the exception so // there can be dialog boxes, etc Messages.MARKET_DATA_MANAGER_FEED_START_FAILED.error( USER_MSG_CATEGORY, mActiveFeed.getName()); } catch (UnsupportedOperationException e) { // TODO: May be better to propagate the exception so // there can be dialog boxes, etc Messages.MARKET_DATA_MANAGER_FEED_RECONNECT_FAILED .error(USER_MSG_CATEGORY, e, mActiveFeed .getName()); } } mMarketData.setSourceFeed(mActiveFeed); final FeedStatusEvent event; final FeedStatus oldStatus = oldFeed == null ? FeedStatus.OFFLINE : oldFeed.getStatus(); if (mActiveFeed == null) { event = oldFeed.createFeedStatusEvent(oldStatus, FeedStatus.OFFLINE); } else { event = mActiveFeed.createFeedStatusEvent(oldStatus, mActiveFeed.getStatus()); } notifyListeners(event); } } finally { mReconnecting.set(false); } } @Override public void addActiveFeedStatusChangedListener( final IFeedStatusChangedListener listener) { mActiveFeedListeners.add(listener); } @Override public void removeActiveFeedStatusChangedListener( final IFeedStatusChangedListener listener) { mActiveFeedListeners.remove(listener); } private void notifyListeners(final IFeedStatusEvent event) { Object[] listeners = mActiveFeedListeners.getListeners(); for (Object object : listeners) { ((IFeedStatusChangedListener) object).feedStatusChanged(event); } } /** * Returns the default active feed to use (saved in plug-in preferences). * * @return returns the default active feed */ private String getDefaultActiveFeed() { return Platform.getPreferencesService().getString( MarketDataConstants.PLUGIN_ID, MarketDataConstants.DEFAULT_ACTIVE_MARKETDATA_PROVIDER, "", //$NON-NLS-1$ null); } @Override public String getActiveFeedName() { IMarketDataFeed feed = mActiveFeed; return feed == null ? null : feed.getName(); } @Override public FeedStatus getActiveFeedStatus() { MarketDataFeed feed = mActiveFeed; return feed == null ? FeedStatus.OFFLINE : feed.getStatus(); } @Override public Set<Capability> getActiveFeedCapabilities() { Set<Capability> emptySet = Collections.emptySet(); IMarketDataFeed feed = mActiveFeed; return feed == null ? emptySet : feed.getCapabilities(); } }
apache-2.0
simplegeo/hadoop-pig
src/org/apache/pig/newplan/logical/expression/DereferenceExpression.java
6495
/* * 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.pig.newplan.logical.expression; import java.util.ArrayList; import java.util.List; import org.apache.pig.data.DataType; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.newplan.Operator; import org.apache.pig.newplan.OperatorPlan; import org.apache.pig.newplan.PlanVisitor; import org.apache.pig.newplan.logical.relational.LogicalSchema; import org.apache.pig.newplan.logical.relational.LogicalSchema.LogicalFieldSchema; /** * * This is a special case Expression and violates some of the rules of an * Expression. * Violation: * It has multiple Uids ( though not tracked there can be multiple uids * for this expression ) * * This is a special operator which handles the case described below * Tuple( a:int, b:bag{ b_a:int, b_b:float } ) --> * BagDereference ( 0 ) --> project( 0, 1 ) --> bag{ b_a:float } * * * * i.e. First input ( 0 ), second column ( 1 ) and first column of the bag. * */ public class DereferenceExpression extends ColumnExpression { private List<Integer> columns;// The column in the input bag which the project references. // Count is zero based. public DereferenceExpression(OperatorPlan plan, int colNum) { super( "Dereference", plan ); columns = new ArrayList<Integer>(); columns.add(colNum); plan.add(this); } public DereferenceExpression(OperatorPlan plan, List<Integer> columnNums) { super( "Dereference", plan ); columns = new ArrayList<Integer>(); columns.addAll(columnNums); plan.add(this); } /** * @link org.apache.pig.newplan.Operator#accept(org.apache.pig.newplan.PlanVisitor) */ @Override public void accept(PlanVisitor v) throws FrontendException { if (!(v instanceof LogicalExpressionVisitor)) { throw new FrontendException("Expected LogicalExpressionVisitor", 2222); } ((LogicalExpressionVisitor)v).visit(this); } public List<Integer> getBagColumns() { return columns; } public void setBagColumns(List<Integer> columns) { this.columns = columns; } @Override public boolean isEqual(Operator other) throws FrontendException { if (other != null && other instanceof DereferenceExpression) { DereferenceExpression po = (DereferenceExpression)other; if( po.columns.size() != columns.size() ) { return false; } return po.columns.containsAll(columns) && getReferredExpression().isEqual(po.getReferredExpression()); } else { return false; } } public LogicalExpression getReferredExpression() throws FrontendException { if( plan.getSuccessors(this).size() < 1 ) { throw new FrontendException("Could not find a related project Expression for Dereference", 2228); } return (LogicalExpression) plan.getSuccessors(this).get(0); } public String toString() { StringBuilder msg = new StringBuilder(); msg.append("(Name: " + name + " Type: "); if (fieldSchema!=null) msg.append(DataType.findTypeName(fieldSchema.type)); else msg.append("null"); msg.append(" Uid: "); if (fieldSchema!=null) msg.append(fieldSchema.uid); else msg.append("null"); msg.append(" Column:" + columns); msg.append(")"); return msg.toString(); } @Override public LogicalSchema.LogicalFieldSchema getFieldSchema() throws FrontendException { if (fieldSchema!=null) return fieldSchema; LogicalExpression successor = (LogicalExpression)plan.getSuccessors(this).get(0); LogicalFieldSchema predFS = successor.getFieldSchema(); if (predFS!=null) { if (columns.size()>1 || predFS.type==DataType.BAG) { LogicalSchema innerSchema = null; if (predFS.schema!=null) { innerSchema = new LogicalSchema(); LogicalSchema realSchema; if (predFS.schema.isTwoLevelAccessRequired()) { realSchema = predFS.schema.getField(0).schema; } else { realSchema = predFS.schema; } if (realSchema!=null) { for (int column:columns) { innerSchema.addField(realSchema.getField(column)); } } } fieldSchema = new LogicalSchema.LogicalFieldSchema(null, innerSchema, predFS.type, LogicalExpression.getNextUid()); } else { // Dereference a field out of a tuple if (predFS.schema!=null) fieldSchema = predFS.schema.getField(columns.get(0)); } } return fieldSchema; } @Override public LogicalExpression deepCopy(LogicalExpressionPlan lgExpPlan) throws FrontendException { List<Integer> columnsCopy = new ArrayList<Integer>(this.getBagColumns()); LogicalExpression copy = new DereferenceExpression( lgExpPlan, columnsCopy); // Only one input is expected. LogicalExpression input = (LogicalExpression) plan.getSuccessors( this ).get( 0 ); LogicalExpression inputCopy = input.deepCopy( lgExpPlan ); lgExpPlan.add( inputCopy ); lgExpPlan.connect( copy, inputCopy ); return copy; } }
apache-2.0
tensorchen/DesignPattern
src/cn/com/chenyixiao/designpattern/observer/zoo/Zoo.java
2866
package cn.com.chenyixiao.designpattern.observer.zoo; import java.util.ArrayList; import java.util.List; /** * 动物园类, 相当于观察者模式中的Subject, 负责存储动物园中的所有动物, 并在新动物加入时通知所有已注册的监听器. * @author 尘一笑 * 这个类比前面两个都复杂,其包含两个list,一个用来存储动物园中所有动物,另一个用来存储所有的监听器, * 鉴于animals和listener集合存储的对象都很简单,本文选择了ArrayList来存储。 * 存储监听器的具体数据结构要视问题而定,比如对于这里的动物园问题,如果监听器有优先级,那就应该选择其他的数据结构,或者重写监听器的register算法。 * 注册和移除的实现都是简单的委托方式:各个监听器作为参数从监听者的监听列表增加或者移除。 notify函数的实现与观察者模式的标准格式稍微偏离,它包括输入参数:新增加的animal,这样一来notify函数就可以把新增加的animal引用传递给监听器了。 用streams API的forEach函数遍历监听器,对每个监听器执行theonAnimalAdded函数。 在addAnimal函数中,新增的animal对象和监听器各自添加到对应list。 如果不考虑通知过程的复杂性,这一逻辑应包含在方便调用的方法中,只需要传入指向新增animal对象的引用即可, 这就是通知监听器的逻辑实现封装在notifyAnimalAddedListeners函数中的原因,这一点在addAnimal的实现中也提到过。 除了notify函数的逻辑问题,需要强调一下对notify函数可见性的争议问题。在经典的观察者模型中, 如GoF在设计模式一书中第301页所说,notify函数是public型的,然而尽管在经典模式中用到,这并不意味着必须是public的。 选择可见性应该基于应用,例如本文的动物园的例子,notify函数是protected类型,并不要求每个对象都可以发起一个注册观察者的通知,只需保证对象能从父类继承该功能即可。 当然,也并非完全如此,需要弄清楚哪些类可以激活notify函数,然后再由此确定函数的可见性。 */ public class Zoo { List<Animal> animals = new ArrayList<>(); List<AnimalAddedListener> animalAddedListeners = new ArrayList<>(); public void AddAnimal(Animal animal) { this.animals.add(animal); this.notifyAnimalAddedListeners(animal); } public void registerAnimalAddedListener(AnimalAddedListener listener) { this.animalAddedListeners.add(listener); } public void unregisterAnimalAddedListener(AnimalAddedListener listener) { this.animalAddedListeners.remove(listener); } protected void notifyAnimalAddedListeners(Animal animal) { this.animalAddedListeners.forEach(listener -> listener.onAnimalAdded(animal)); } }
apache-2.0
dingyifly/medical
src/main/java/com/medical/common/supcan/common/fonts/Font.java
2712
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.medical.common.supcan.common.fonts; import com.medical.common.supcan.annotation.common.fonts.SupFont; import com.medical.common.utils.ObjectUtils; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamAsAttribute; /** * 硕正TreeList Properties * @author WangZhen * @version 2013-11-04 */ @XStreamAlias("Font") public class Font { /** * 字体名称 微软雅黑 宋体 */ @XStreamAsAttribute private String faceName; /** * 字符集 134 */ @XStreamAsAttribute private String charSet; /** * Height(或size)是字体的尺寸,单位是字体的逻辑单位,通常采用小于0的数字, * 如果大于0,则高度不包含文字的内部行距(internal-leading)。 * 常用的尺寸是-8, -9, -10, -11, -12, -14, -16, -18, -20, -22, -24, -26, -28, -36, -48, -72; */ @XStreamAsAttribute private String height; /** * 字体加粗 weight=400/700 对应 非粗体/粗体; */ @XStreamAsAttribute private String weight; /** * 字体宽度 */ @XStreamAsAttribute private String width; /** * 字体斜体 */ @XStreamAsAttribute private String italic; /** * 字体下划线 */ @XStreamAsAttribute private String underline; public Font() { } public Font(SupFont supFont) { this(); ObjectUtils.annotationToObject(supFont, this); } public Font(String faceName) { this(); this.faceName = faceName; } public Font(String faceName, String charSet, String height) { this(faceName); this.charSet = charSet; this.height = height; } public Font(String faceName, String charSet, String height, String weight) { this(faceName, charSet, height); this.weight = weight; } public String getFaceName() { return faceName; } public void setFaceName(String faceName) { this.faceName = faceName; } public String getCharSet() { return charSet; } public void setCharSet(String charSet) { this.charSet = charSet; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } public String getItalic() { return italic; } public void setItalic(String italic) { this.italic = italic; } public String getUnderline() { return underline; } public void setUnderline(String underline) { this.underline = underline; } }
apache-2.0
angcyo/RLibrary
websocket/src/main/java/com/neovisionaries/ws/client/PongSender.java
1073
/* * Copyright (C) 2015-2016 Neo Visionaries Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.neovisionaries.ws.client; class PongSender extends PeriodicalFrameSender { private static final String TIMER_NAME = "PongSender"; public PongSender(WebSocket webSocket, PayloadGenerator generator) { super(webSocket, TIMER_NAME, generator); } @Override protected WebSocketFrame createFrame(byte[] payload) { return WebSocketFrame.createPongFrame(payload); } }
apache-2.0
PlanetWaves/clockworkengine
trunk/jme3-terrain/src/main/java/com/jme3/terrain/heightmap/AbstractHeightMap.java
16437
/* * Copyright (c) 2009-2012 jMonkeyEngine * 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 'jMonkeyEngine' 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 OWNER 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 com.jme3.terrain.heightmap; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * <code>AbstractHeightMap</code> provides a base implementation of height * data for terrain rendering. The loading of the data is dependent on the * subclass. The abstract implementation provides a means to retrieve the height * data and to save it. * * It is the general contract that any subclass provide a means of editing * required attributes and calling <code>load</code> again to recreate a * heightfield with these new parameters. * * @author Mark Powell * @version $Id: AbstractHeightMap.java 4133 2009-03-19 20:40:11Z blaine.dev $ */ public abstract class AbstractHeightMap implements HeightMap { private static final Logger logger = Logger.getLogger(AbstractHeightMap.class.getName()); /** Height data information. */ protected float[] heightData = null; /** The size of the height map's width. */ protected int size = 0; /** Allows scaling the Y height of the map. */ protected float heightScale = 1.0f; /** The filter is used to erode the terrain. */ protected float filter = 0.5f; /** The range used to normalize terrain */ public static float NORMALIZE_RANGE = 255f; /** * <code>unloadHeightMap</code> clears the data of the height map. This * insures it is ready for reloading. */ public void unloadHeightMap() { heightData = null; } /** * <code>setHeightScale</code> sets the scale of the height values. * Typically, the height is a little too extreme and should be scaled to a * smaller value (i.e. 0.25), to produce cleaner slopes. * * @param scale * the scale to multiply height values by. */ public void setHeightScale(float scale) { heightScale = scale; } /** * <code>setHeightAtPoint</code> sets the height value for a given * coordinate. It is recommended that the height value be within the 0 - 255 * range. * * @param height * the new height for the coordinate. * @param x * the x (east/west) coordinate. * @param z * the z (north/south) coordinate. */ public void setHeightAtPoint(float height, int x, int z) { heightData[x + (z * size)] = height; } /** * <code>setSize</code> sets the size of the terrain where the area is * size x size. * * @param size * the new size of the terrain. * @throws Exception * * @throws JmeException * if the size is less than or equal to zero. */ public void setSize(int size) throws Exception { if (size <= 0) { throw new Exception("size must be greater than zero."); } this.size = size; } /** * <code>setFilter</code> sets the erosion value for the filter. This * value must be between 0 and 1, where 0.2 - 0.4 produces arguably the best * results. * * @param filter * the erosion value. * @throws Exception * @throws JmeException * if filter is less than 0 or greater than 1. */ public void setMagnificationFilter(float filter) throws Exception { if (filter < 0 || filter >= 1) { throw new Exception("filter must be between 0 and 1"); } this.filter = filter; } /** * <code>getTrueHeightAtPoint</code> returns the non-scaled value at the * point provided. * * @param x * the x (east/west) coordinate. * @param z * the z (north/south) coordinate. * @return the value at (x,z). */ public float getTrueHeightAtPoint(int x, int z) { //logger.fine( heightData[x + (z*size)]); return heightData[x + (z * size)]; } /** * <code>getScaledHeightAtPoint</code> returns the scaled value at the * point provided. * * @param x * the x (east/west) coordinate. * @param z * the z (north/south) coordinate. * @return the scaled value at (x, z). */ public float getScaledHeightAtPoint(int x, int z) { return ((heightData[x + (z * size)]) * heightScale); } /** * <code>getInterpolatedHeight</code> returns the height of a point that * does not fall directly on the height posts. * * @param x * the x coordinate of the point. * @param z * the y coordinate of the point. * @return the interpolated height at this point. */ public float getInterpolatedHeight(float x, float z) { float low, highX, highZ; float intX, intZ; float interpolation; low = getScaledHeightAtPoint((int) x, (int) z); if (x + 1 >= size) { return low; } highX = getScaledHeightAtPoint((int) x + 1, (int) z); interpolation = x - (int) x; intX = ((highX - low) * interpolation) + low; if (z + 1 >= size) { return low; } highZ = getScaledHeightAtPoint((int) x, (int) z + 1); interpolation = z - (int) z; intZ = ((highZ - low) * interpolation) + low; return ((intX + intZ) / 2); } /** * <code>getHeightMap</code> returns the entire grid of height data. * * @return the grid of height data. */ public float[] getHeightMap() { return heightData; } /** * Build a new array of height data with the scaled values. * @return */ public float[] getScaledHeightMap() { float[] hm = new float[heightData.length]; for (int i=0; i<heightData.length; i++) { hm[i] = heightScale * heightData[i]; } return hm; } /** * <code>getSize</code> returns the size of one side the height map. Where * the area of the height map is size x size. * * @return the size of a single side. */ public int getSize() { return size; } /** * <code>save</code> will save the heightmap data into a new RAW file * denoted by the supplied filename. * * @param filename * the file name to save the current data as. * @return true if the save was successful, false otherwise. * @throws Exception * * @throws JmeException * if filename is null. */ public boolean save(String filename) throws Exception { if (null == filename) { throw new Exception("Filename must not be null"); } //open the streams and send the height data to the file. FileOutputStream fos = null; DataOutputStream dos = null; try { fos = new FileOutputStream(filename); dos = new DataOutputStream(fos); for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { dos.write((int) heightData[j + (i * size)]); } } fos.close(); dos.close(); } catch (FileNotFoundException e) { logger.log(Level.WARNING, "Error opening file {0}", filename); return false; } catch (IOException e) { logger.log(Level.WARNING, "Error writing to file {0}", filename); return false; } finally { if (fos != null) { fos.close(); } if (dos != null) { dos.close(); } } logger.log(Level.FINE, "Saved terrain to {0}", filename); return true; } /** * <code>normalizeTerrain</code> takes the current terrain data and * converts it to values between 0 and <code>value</code>. * * @param value * the value to normalize to. */ public void normalizeTerrain(float value) { float currentMin, currentMax; float height; currentMin = heightData[0]; currentMax = heightData[0]; //find the min/max values of the height fTemptemptempBuffer for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (heightData[i + j * size] > currentMax) { currentMax = heightData[i + j * size]; } else if (heightData[i + j * size] < currentMin) { currentMin = heightData[i + j * size]; } } } //find the range of the altitude if (currentMax <= currentMin) { return; } height = currentMax - currentMin; //scale the values to a range of 0-255 for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { heightData[i + j * size] = ((heightData[i + j * size] - currentMin) / height) * value; } } } /** * Find the minimum and maximum height values. * @return a float array with two value: min height, max height */ public float[] findMinMaxHeights() { float[] minmax = new float[2]; float currentMin, currentMax; currentMin = heightData[0]; currentMax = heightData[0]; for (int i = 0; i < heightData.length; i++) { if (heightData[i] > currentMax) { currentMax = heightData[i]; } else if (heightData[i] < currentMin) { currentMin = heightData[i]; } } minmax[0] = currentMin; minmax[1] = currentMax; return minmax; } /** * <code>erodeTerrain</code> is a convenience method that applies the FIR * filter to a given height map. This simulates water errosion. * * @see setFilter */ public void erodeTerrain() { //erode left to right float v; for (int i = 0; i < size; i++) { v = heightData[i]; for (int j = 1; j < size; j++) { heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size]; v = heightData[i + j * size]; } } //erode right to left for (int i = size - 1; i >= 0; i--) { v = heightData[i]; for (int j = 0; j < size; j++) { heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size]; v = heightData[i + j * size]; //erodeBand(tempBuffer[size * i + size - 1], -1); } } //erode top to bottom for (int i = 0; i < size; i++) { v = heightData[i]; for (int j = 0; j < size; j++) { heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size]; v = heightData[i + j * size]; } } //erode from bottom to top for (int i = size - 1; i >= 0; i--) { v = heightData[i]; for (int j = 0; j < size; j++) { heightData[i + j * size] = filter * v + (1 - filter) * heightData[i + j * size]; v = heightData[i + j * size]; } } } /** * Flattens out the valleys. The flatten algorithm makes the valleys more * prominent while keeping the hills mostly intact. This effect is based on * what happens when values below one are squared. The terrain will be * normalized between 0 and 1 for this function to work. * * @param flattening * the power of flattening applied, 1 means none */ public void flatten(byte flattening) { // If flattening is one we can skip the calculations // since it wouldn't change anything. (e.g. 2 power 1 = 2) if (flattening <= 1) { return; } float[] minmax = findMinMaxHeights(); normalizeTerrain(1f); for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { float flat = 1.0f; float original = heightData[x + y * size]; // Flatten as many times as desired; for (int i = 0; i < flattening; i++) { flat *= original; } heightData[x + y * size] = flat; } } // re-normalize back to its oraginal height range float height = minmax[1] - minmax[0]; normalizeTerrain(height); } /** * Smooth the terrain. For each node, its 8 neighbors heights * are averaged and will participate in the node new height * by a factor <code>np</code> between 0 and 1 * * You must first load() the heightmap data before this will have any effect. * * @param np * The factor to what extend the neighbors average has an influence. * Value of 0 will ignore neighbors (no smoothing) * Value of 1 will ignore the node old height. */ public void smooth(float np) { smooth(np, 1); } /** * Smooth the terrain. For each node, its X(determined by radius) neighbors heights * are averaged and will participate in the node new height * by a factor <code>np</code> between 0 and 1 * * You must first load() the heightmap data before this will have any effect. * * @param np * The factor to what extend the neighbors average has an influence. * Value of 0 will ignore neighbors (no smoothing) * Value of 1 will ignore the node old height. */ public void smooth(float np, int radius) { if (np < 0 || np > 1) { return; } if (radius == 0) radius = 1; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { int neighNumber = 0; float neighAverage = 0; for (int rx = -radius; rx <= radius; rx++) { for (int ry = -radius; ry <= radius; ry++) { if (x+rx < 0 || x+rx >= size) { continue; } if (y+ry < 0 || y+ry >= size) { continue; } neighNumber++; neighAverage += heightData[(x+rx) + (y+ry) * size]; } } neighAverage /= neighNumber; float cp = 1 - np; heightData[x + y * size] = neighAverage * np + heightData[x + y * size] * cp; } } } }
apache-2.0
typetools/commons-bcel
src/main/java/org/apache/bcel/generic/ElementValuePairGen.java
3607
/* * 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.bcel.generic; import java.io.DataOutputStream; import java.io.IOException; import org.apache.bcel.classfile.ConstantUtf8; import org.apache.bcel.classfile.ElementValue; import org.apache.bcel.classfile.ElementValuePair; import org.checkerframework.dataflow.qual.Pure; /** * @since 6.0 */ public class ElementValuePairGen { private int nameIdx; private final ElementValueGen value; private final ConstantPoolGen constantPoolGen; public ElementValuePairGen(final ElementValuePair nvp, final ConstantPoolGen cpool, final boolean copyPoolEntries) { this.constantPoolGen = cpool; // J5ASSERT: // Could assert nvp.getNameString() points to the same thing as // constantPoolGen.getConstant(nvp.getNameIndex()) // if // (!nvp.getNameString().equals(((ConstantUtf8)constantPoolGen.getConstant(nvp.getNameIndex())).getBytes())) // { // throw new IllegalArgumentException("envp buggered"); // } if (copyPoolEntries) { nameIdx = cpool.addUtf8(nvp.getNameString()); } else { nameIdx = nvp.getNameIndex(); } value = ElementValueGen.copy(nvp.getValue(), cpool, copyPoolEntries); } /** * Retrieve an immutable version of this ElementNameValuePairGen */ public ElementValuePair getElementNameValuePair() { final ElementValue immutableValue = value.getElementValue(); return new ElementValuePair(nameIdx, immutableValue, constantPoolGen .getConstantPool()); } protected ElementValuePairGen(final int idx, final ElementValueGen value, final ConstantPoolGen cpool) { this.nameIdx = idx; this.value = value; this.constantPoolGen = cpool; } public ElementValuePairGen(final String name, final ElementValueGen value, final ConstantPoolGen cpool) { this.nameIdx = cpool.addUtf8(name); this.value = value; this.constantPoolGen = cpool; } protected void dump(final DataOutputStream dos) throws IOException { dos.writeShort(nameIdx); // u2 name of the element value.dump(dos); } @Pure public int getNameIndex() { return nameIdx; } public final String getNameString() { // ConstantString cu8 = (ConstantString)constantPoolGen.getConstant(nameIdx); return ((ConstantUtf8) constantPoolGen.getConstant(nameIdx)).getBytes(); } public final ElementValueGen getValue() { return value; } @Override public String toString() { return "ElementValuePair:[" + getNameString() + "=" + value.stringifyValue() + "]"; } }
apache-2.0
ulfjack/bazel
src/test/java/com/google/devtools/build/lib/rules/objc/AppleStaticLibraryTest.java
28965
// Copyright 2017 The Bazel Authors. All rights reserved. // // 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.devtools.build.lib.rules.objc; import static com.google.common.truth.Truth.assertThat; import static com.google.devtools.build.lib.actions.util.ActionsTestUtil.getFirstArtifactEndingWith; import static com.google.devtools.build.lib.rules.objc.ObjcRuleClasses.LIPO; import static org.junit.Assert.assertThrows; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.devtools.build.lib.actions.Action; import com.google.devtools.build.lib.actions.Artifact; import com.google.devtools.build.lib.actions.CommandAction; import com.google.devtools.build.lib.analysis.ConfiguredTarget; import com.google.devtools.build.lib.analysis.actions.SymlinkAction; import com.google.devtools.build.lib.packages.util.MockObjcSupport; import com.google.devtools.build.lib.packages.util.MockProtoSupport; import com.google.devtools.build.lib.rules.apple.AppleConfiguration.ConfigurationDistinguisher; import com.google.devtools.build.lib.testutil.Scratch; import com.google.devtools.build.lib.testutil.TestConstants; import java.io.IOException; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Test case for apple_static_library. */ @RunWith(JUnit4.class) public class AppleStaticLibraryTest extends ObjcRuleTestCase { static final RuleType RULE_TYPE = new RuleType("apple_static_library") { @Override Iterable<String> requiredAttributes(Scratch scratch, String packageDir, Set<String> alreadyAdded) throws IOException { ImmutableList.Builder<String> attributes = new ImmutableList.Builder<>(); if (!alreadyAdded.contains("deps")) { String depPackageDir = packageDir + "_defaultDep"; scratch.file(depPackageDir + "/a.m"); scratch.file(depPackageDir + "/private.h"); scratch.file(depPackageDir + "/BUILD", "objc_library(name = 'lib_dep', srcs = ['a.m', 'private.h'])"); attributes.add("deps = ['//" + depPackageDir + ":" + "lib_dep']"); } if (!alreadyAdded.contains("platform_type")) { attributes.add("platform_type = 'ios'"); } return attributes.build(); } }; @Before public void setUp() throws Exception { MockProtoSupport.setupWorkspace(scratch); invalidatePackages(); } @Test public void testMandatoryMinimumOsVersionUnset() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'watchos'"); useConfiguration("--experimental_apple_mandatory_minimum_version"); reporter.removeHandler(failFastHandler); getConfiguredTarget("//x:x"); assertContainsEvent("must be explicitly specified"); } @Test public void testMandatoryMinimumOsVersionSet() throws Exception { RULE_TYPE.scratchTarget(scratch, "minimum_os_version", "'8.0'", "platform_type", "'watchos'"); useConfiguration("--experimental_apple_mandatory_minimum_version"); getConfiguredTarget("//x:x"); } @Test public void testUnknownPlatformType() throws Exception { checkError( "package", "test", String.format(MultiArchSplitTransitionProvider.UNSUPPORTED_PLATFORM_TYPE_ERROR_FORMAT, "meow_meow_os"), "apple_static_library(name = 'test', platform_type = 'meow_meow_os')"); } @Test public void testSymlinkInsteadOfLipoSingleArch() throws Exception { RULE_TYPE.scratchTarget(scratch); SymlinkAction action = (SymlinkAction) lipoLibAction("//x:x"); CommandAction linkAction = linkLibAction("//x:x"); assertThat(action.getInputs().toList()) .containsExactly(Iterables.getOnlyElement(linkAction.getOutputs())); } @Test public void testNoSrcs() throws Exception { scratch.file("package/BUILD", "apple_static_library(", " name = 'test',", " deps = [':objcLib'],", " platform_type = 'ios',", ")", "objc_library(name = 'objcLib', srcs = [ 'b.m' ])"); useConfiguration("--xcode_version=5.8"); CommandAction action = linkLibAction("//package:test"); assertThat(Artifact.toRootRelativePaths(action.getInputs())).contains("package/libobjcLib.a"); } @Test public void testLipoAction() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'ios'"); useConfiguration("--ios_multi_cpus=i386,x86_64"); CommandAction action = (CommandAction) lipoLibAction("//x:x"); String i386Lib = configurationBin("i386", ConfigurationDistinguisher.APPLEBIN_IOS) + "x/x-fl.a"; String x8664Lib = configurationBin("x86_64", ConfigurationDistinguisher.APPLEBIN_IOS) + "x/x-fl.a"; assertThat(Artifact.asExecPaths(action.getInputs())) .containsExactly( i386Lib, x8664Lib, MOCK_XCRUNWRAPPER_PATH, MOCK_XCRUNWRAPPER_EXECUTABLE_PATH); assertThat(action.getArguments()) .containsExactly( MOCK_XCRUNWRAPPER_EXECUTABLE_PATH, LIPO, "-create", i386Lib, x8664Lib, "-o", execPathEndingWith(action.getOutputs(), "x_lipo.a")) .inOrder(); assertThat(Artifact.toRootRelativePaths(action.getOutputs())) .containsExactly("x/x_lipo.a"); assertRequiresDarwin(action); } @Test public void testWatchSimulatorDepCompile() throws Exception { scratch.file( "package/BUILD", "apple_static_library(", " name = 'test',", " deps = [':objcLib'],", " platform_type = 'watchos'", ")", "objc_library(name = 'objcLib', srcs = [ 'a.m' ])"); Action lipoAction = lipoLibAction("//package:test"); String i386Bin = configurationBin("i386", ConfigurationDistinguisher.APPLEBIN_WATCHOS) + "package/test-fl.a"; Artifact libArtifact = getFirstArtifactEndingWith(lipoAction.getInputs(), i386Bin); CommandAction linkAction = (CommandAction) getGeneratingAction(libArtifact); CommandAction objcLibCompileAction = (CommandAction) getGeneratingAction(getFirstArtifactEndingWith(linkAction.getInputs(), "libobjcLib.a")); assertAppleSdkPlatformEnv(objcLibCompileAction, "WatchSimulator"); assertThat(objcLibCompileAction.getArguments()).containsAtLeast("-arch_only", "i386").inOrder(); } @Test public void testMultiarchCcDep() throws Exception { scratch.file( "package/BUILD", "apple_static_library(name = 'test',", " deps = [ ':cclib' ],", " platform_type = 'ios')", "cc_library(name = 'cclib', srcs = ['dep.c'])"); useConfiguration( "--ios_multi_cpus=i386,x86_64", "--crosstool_top=//tools/osx/crosstool:crosstool"); CommandAction action = (CommandAction) lipoLibAction("//package:test"); String i386Prefix = configurationBin("i386", ConfigurationDistinguisher.APPLEBIN_IOS); String x8664Prefix = configurationBin("x86_64", ConfigurationDistinguisher.APPLEBIN_IOS); CommandAction i386BinAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(action.getInputs(), i386Prefix + "package/test-fl.a")); CommandAction x8664BinAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(action.getInputs(), x8664Prefix + "package/test-fl.a")); assertThat(Artifact.asExecPaths(i386BinAction.getInputs())) .contains(i386Prefix + "package/libcclib.a"); assertThat(Artifact.asExecPaths(x8664BinAction.getInputs())) .contains(x8664Prefix + "package/libcclib.a"); } @Test public void testWatchSimulatorLipoAction() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'watchos'"); // Tests that ios_multi_cpus and ios_cpu are completely ignored. useConfiguration("--ios_multi_cpus=x86_64", "--ios_cpu=x86_64", "--watchos_cpus=i386,armv7k"); CommandAction action = (CommandAction) lipoLibAction("//x:x"); String i386Bin = configurationBin("i386", ConfigurationDistinguisher.APPLEBIN_WATCHOS) + "x/x-fl.a"; String armv7kBin = configurationBin("armv7k", ConfigurationDistinguisher.APPLEBIN_WATCHOS) + "x/x-fl.a"; assertThat(Artifact.asExecPaths(action.getInputs())) .containsExactly( i386Bin, armv7kBin, MOCK_XCRUNWRAPPER_PATH, MOCK_XCRUNWRAPPER_EXECUTABLE_PATH); assertContainsSublist(action.getArguments(), ImmutableList.of( MOCK_XCRUNWRAPPER_EXECUTABLE_PATH, LIPO, "-create")); assertThat(action.getArguments()).containsAtLeast(armv7kBin, i386Bin); assertContainsSublist(action.getArguments(), ImmutableList.of( "-o", execPathEndingWith(action.getOutputs(), "x_lipo.a"))); assertThat(Artifact.toRootRelativePaths(action.getOutputs())) .containsExactly("x/x_lipo.a"); assertAppleSdkPlatformEnv(action, "WatchOS"); assertRequiresDarwin(action); } @Test public void testProtoDeps() throws Exception { MockObjcSupport.setupObjcProtoLibrary(scratch); scratch.file("x/filter_a.pbascii"); scratch.file("x/filter_b.pbascii"); scratch.file( "protos/BUILD", TestConstants.LOAD_PROTO_LIBRARY, "load('//objc_proto_library:objc_proto_library.bzl', 'objc_proto_library')", "proto_library(", " name = 'protos_main',", " srcs = ['data_a.proto', 'data_b.proto'],", ")", "proto_library(", " name = 'protos_low_level',", " srcs = ['data_b.proto'],", ")", "objc_proto_library(", " name = 'objc_protos_main',", " portable_proto_filters = ['filter_a.pbascii'],", " deps = [':protos_main'],", ")", "objc_proto_library(", " name = 'objc_protos_low_level',", " portable_proto_filters = ['filter_b.pbascii'],", " deps = [':protos_low_level'],", ")"); scratch.file( "libs/BUILD", "objc_library(", " name = 'main_lib',", " srcs = ['a.m'],", " deps = ['//protos:objc_protos_main',]", ")", "objc_library(", " name = 'apple_low_level_lib',", " srcs = ['a.m'],", " deps = ['//protos:objc_protos_low_level',]", ")"); RULE_TYPE.scratchTarget( scratch, "deps", "['//libs:main_lib']", "avoid_deps", "['//libs:apple_low_level_lib']"); CommandAction linkAction = linkLibAction("//x:x"); Iterable<Artifact> linkActionInputs = linkAction.getInputs().toList(); ImmutableList.Builder<Artifact> objects = ImmutableList.builder(); for (Artifact binActionArtifact : linkActionInputs) { if (binActionArtifact.getRootRelativePath().getPathString().endsWith(".a")) { CommandAction subLinkAction = (CommandAction) getGeneratingAction(binActionArtifact); for (Artifact linkActionArtifact : subLinkAction.getInputs().toList()) { if (linkActionArtifact.getRootRelativePath().getPathString().endsWith(".o")) { objects.add(linkActionArtifact); } } } } ImmutableList<Artifact> objectFiles = objects.build(); assertThat(getFirstArtifactEndingWith(objectFiles, "DataA.pbobjc.o")).isNotNull(); assertThat(getFirstArtifactEndingWith(objectFiles, "DataB.pbobjc.o")).isNull(); } @Test public void testMinimumOs() throws Exception { RULE_TYPE.scratchTarget(scratch, "deps", "['//package:objcLib']", "minimum_os_version", "'5.4'"); scratch.file("package/BUILD", "objc_library(name = 'objcLib', srcs = [ 'b.m' ])"); useConfiguration("--xcode_version=5.8"); CommandAction linkAction = linkLibAction("//x:x"); CommandAction objcLibArchiveAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(linkAction.getInputs(), "libobjcLib.a")); CommandAction objcLibCompileAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(objcLibArchiveAction.getInputs(), "b.o")); String compileArgs = Joiner.on(" ").join(objcLibCompileAction.getArguments()); assertThat(compileArgs).contains("-mios-simulator-version-min=5.4"); } @Test public void testMinimumOs_watchos() throws Exception { RULE_TYPE.scratchTarget(scratch, "deps", "['//package:objcLib']", "platform_type", "'watchos'", "minimum_os_version", "'5.4'"); scratch.file("package/BUILD", "objc_library(name = 'objcLib', srcs = [ 'b.m' ])"); useConfiguration("--xcode_version=5.8"); CommandAction linkAction = linkLibAction("//x:x"); CommandAction objcLibArchiveAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(linkAction.getInputs(), "libobjcLib.a")); CommandAction objcLibCompileAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(objcLibArchiveAction.getInputs(), "b.o")); String compileArgs = Joiner.on(" ").join(objcLibCompileAction.getArguments()); assertThat(compileArgs).contains("-mwatchos-simulator-version-min=5.4"); } @Test public void testMinimumOs_invalid_nonVersion() throws Exception { checkMinimumOs_invalid_nonVersion(RULE_TYPE); } @Test public void testMinimumOs_invalid_containsAlphabetic() throws Exception { checkMinimumOs_invalid_containsAlphabetic(RULE_TYPE); } @Test public void testMinimumOs_invalid_tooManyComponents() throws Exception { checkMinimumOs_invalid_tooManyComponents(RULE_TYPE); } @Test public void testAppleSdkVersionEnv() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'ios'"); CommandAction action = linkLibAction("//x:x"); assertAppleSdkVersionEnv(action); } @Test public void testNonDefaultAppleSdkVersionEnv() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'ios'"); useConfiguration("--ios_sdk_version=8.1"); CommandAction action = linkLibAction("//x:x"); assertAppleSdkVersionEnv(action, "8.1"); } @Test public void testAppleSdkDefaultPlatformEnv() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'ios'"); CommandAction action = linkLibAction("//x:x"); assertAppleSdkPlatformEnv(action, "iPhoneSimulator"); } @Test public void testAppleSdkIphoneosPlatformEnv() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'ios'"); useConfiguration("--apple_platform_type=ios", "--cpu=ios_arm64"); CommandAction action = linkLibAction("//x:x"); assertAppleSdkPlatformEnv(action, "iPhoneOS"); } @Test public void testAppleSdkWatchsimulatorPlatformEnv() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'watchos'"); useConfiguration("--watchos_cpus=i386"); Action lipoAction = lipoLibAction("//x:x"); String i386Lib = configurationBin("i386", ConfigurationDistinguisher.APPLEBIN_WATCHOS) + "x/x-fl.a"; Artifact binArtifact = getFirstArtifactEndingWith(lipoAction.getInputs(), i386Lib); CommandAction linkAction = (CommandAction) getGeneratingAction(binArtifact); assertAppleSdkPlatformEnv(linkAction, "WatchSimulator"); } @Test public void testAppleSdkWatchosPlatformEnv() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'watchos'"); useConfiguration("--watchos_cpus=armv7k"); Action lipoAction = lipoLibAction("//x:x"); String armv7kLib = configurationBin("armv7k", ConfigurationDistinguisher.APPLEBIN_WATCHOS) + "x/x-fl.a"; Artifact libArtifact = getFirstArtifactEndingWith(lipoAction.getInputs(), armv7kLib); CommandAction linkAction = (CommandAction) getGeneratingAction(libArtifact); assertAppleSdkPlatformEnv(linkAction, "WatchOS"); } @Test public void testXcodeVersionEnv() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'ios'"); useConfiguration("--xcode_version=5.8"); CommandAction action = linkLibAction("//x:x"); assertXcodeVersionEnv(action, "5.8"); } @Test public void testWatchSimulatorLinkAction() throws Exception { scratch.file( "package/BUILD", "apple_static_library(", " name = 'test',", " deps = [':objcLib'],", " platform_type = 'watchos'", ")", "objc_library(name = 'objcLib', srcs = [ 'b.m' ])"); // Tests that ios_multi_cpus and ios_cpu are completely ignored. useConfiguration("--ios_multi_cpus=x86_64", "--ios_cpu=x86_64", "--watchos_cpus=i386"); Action lipoAction = lipoLibAction("//package:test"); String i386Bin = configurationBin("i386", ConfigurationDistinguisher.APPLEBIN_WATCHOS) + "package/test-fl.a"; Artifact binArtifact = getFirstArtifactEndingWith(lipoAction.getInputs(), i386Bin); CommandAction linkAction = (CommandAction) getGeneratingAction(binArtifact); assertAppleSdkPlatformEnv(linkAction, "WatchSimulator"); assertThat(normalizeBashArgs(linkAction.getArguments())) .containsAtLeast("-arch_only", "i386") .inOrder(); } @Test public void testAppleStaticLibraryInfo() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'ios'"); ConfiguredTarget binTarget = getConfiguredTarget("//x:x"); AppleStaticLibraryInfo provider = binTarget.get(AppleStaticLibraryInfo.STARLARK_CONSTRUCTOR); assertThat(provider).isNotNull(); assertThat(provider.getMultiArchArchive()).isNotNull(); assertThat(provider.getDepsObjcProvider()).isNotNull(); assertThat(provider.getMultiArchArchive()) .isEqualTo( provider .getDepsObjcProvider() .get(ObjcProvider.MULTI_ARCH_LINKED_ARCHIVES) .getSingleton()); } @Test public void testMinimumOsDifferentTargets() throws Exception { checkMinimumOsDifferentTargets(RULE_TYPE, "_lipo.a", "-fl.a"); } @Test public void testAvoidDepsObjects() throws Exception { scratch.file("package/BUILD", "apple_static_library(", " name = 'test',", " deps = [':objcLib'],", " avoid_deps = [':avoidLib'],", " platform_type = 'ios',", ")", "objc_library(name = 'objcLib', srcs = [ 'b.m' ], deps = [':avoidLib', ':baseLib'])", "objc_library(name = 'baseLib', srcs = [ 'base.m' ])", "objc_library(name = 'avoidLib', srcs = [ 'c.m' ])"); CommandAction action = linkLibAction("//package:test"); assertThat(Artifact.toRootRelativePaths(action.getInputs())) .containsAtLeast("package/libobjcLib.a", "package/libbaseLib.a"); assertThat(Artifact.toRootRelativePaths(action.getInputs())).doesNotContain( "package/libavoidLib.a"); } @Test // Tests that if there is a cc_library in avoid_deps, all of its dependencies are // transitively avoided, even if it is not present in deps. public void testAvoidDepsObjects_avoidViaCcLibrary() throws Exception { scratch.file("package/BUILD", "apple_static_library(", " name = 'test',", " deps = [':objcLib'],", " avoid_deps = [':avoidCclib'],", " platform_type = 'ios',", ")", "cc_library(name = 'avoidCclib', srcs = ['cclib.c'], deps = [':avoidLib'])", "objc_library(name = 'objcLib', srcs = [ 'b.m' ], deps = [':avoidLib'])", "objc_library(name = 'avoidLib', srcs = [ 'c.m' ])"); CommandAction action = linkLibAction("//package:test"); assertThat(Artifact.toRootRelativePaths(action.getInputs())).contains( "package/libobjcLib.a"); assertThat(Artifact.toRootRelativePaths(action.getInputs())).doesNotContain( "package/libavoidCcLib.a"); } @Test // Tests that if there is a cc_library in avoid_deps, and it is present in deps, it will // be avoided, as well as its transitive dependencies. public void testAvoidDepsObjects_avoidCcLibrary() throws Exception { scratch.file("package/BUILD", "apple_static_library(", " name = 'test',", " deps = [':objcLib', ':avoidCclib'],", " avoid_deps = [':avoidCclib'],", " platform_type = 'ios',", ")", "cc_library(name = 'avoidCclib', srcs = ['cclib.c'], deps = [':avoidLib'])", "objc_library(name = 'objcLib', srcs = [ 'b.m' ])", "objc_library(name = 'avoidLib', srcs = [ 'c.m' ])"); CommandAction action = linkLibAction("//package:test"); assertThat(Artifact.toRootRelativePaths(action.getInputs())).contains( "package/libobjcLib.a"); assertThat(Artifact.toRootRelativePaths(action.getInputs())).doesNotContain( "package/libavoidCcLib.a"); } @Test public void testFeatureFlags_offByDefault() throws Exception { useConfiguration("--enforce_transitive_configs_for_config_feature_flag"); scratchFeatureFlagTestLib(); scratch.file( "test/BUILD", "apple_static_library(", " name = 'static_lib',", " deps = ['//lib:objcLib'],", " platform_type = 'ios',", " transitive_configs = ['//lib:flag1', '//lib:flag2'],", ")"); CommandAction linkAction = linkLibAction("//test:static_lib"); CommandAction objcLibArchiveAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(linkAction.getInputs(), "libobjcLib.a")); CommandAction flag1offCompileAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(objcLibArchiveAction.getInputs(), "flag1off.o")); CommandAction flag2offCompileAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(objcLibArchiveAction.getInputs(), "flag2off.o")); String compileArgs1 = Joiner.on(" ").join(flag1offCompileAction.getArguments()); String compileArgs2 = Joiner.on(" ").join(flag2offCompileAction.getArguments()); assertThat(compileArgs1).contains("FLAG_1_OFF"); assertThat(compileArgs1).contains("FLAG_2_OFF"); assertThat(compileArgs2).contains("FLAG_1_OFF"); assertThat(compileArgs2).contains("FLAG_2_OFF"); } @Test public void testFeatureFlags_oneFlagOn() throws Exception { useConfiguration("--enforce_transitive_configs_for_config_feature_flag"); scratchFeatureFlagTestLib(); scratch.file( "test/BUILD", "apple_static_library(", " name = 'static_lib',", " deps = ['//lib:objcLib'],", " platform_type = 'ios',", " feature_flags = {", " '//lib:flag2': 'on',", " },", " transitive_configs = ['//lib:flag1', '//lib:flag2'],", ")"); CommandAction linkAction = linkLibAction("//test:static_lib"); CommandAction objcLibArchiveAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(linkAction.getInputs(), "libobjcLib.a")); CommandAction flag1offCompileAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(objcLibArchiveAction.getInputs(), "flag1off.o")); CommandAction flag2onCompileAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(objcLibArchiveAction.getInputs(), "flag2on.o")); String compileArgs1 = Joiner.on(" ").join(flag1offCompileAction.getArguments()); String compileArgs2 = Joiner.on(" ").join(flag2onCompileAction.getArguments()); assertThat(compileArgs1).contains("FLAG_1_OFF"); assertThat(compileArgs1).contains("FLAG_2_ON"); assertThat(compileArgs2).contains("FLAG_1_OFF"); assertThat(compileArgs2).contains("FLAG_2_ON"); } @Test public void testFeatureFlags_allFlagsOn() throws Exception { useConfiguration("--enforce_transitive_configs_for_config_feature_flag"); scratchFeatureFlagTestLib(); scratch.file( "test/BUILD", "apple_static_library(", " name = 'static_lib',", " deps = ['//lib:objcLib'],", " platform_type = 'ios',", " feature_flags = {", " '//lib:flag1': 'on',", " '//lib:flag2': 'on',", " },", " transitive_configs = ['//lib:flag1', '//lib:flag2'],", ")"); CommandAction linkAction = linkLibAction("//test:static_lib"); CommandAction objcLibArchiveAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(linkAction.getInputs(), "libobjcLib.a")); CommandAction flag1onCompileAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(objcLibArchiveAction.getInputs(), "flag1on.o")); CommandAction flag2onCompileAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(objcLibArchiveAction.getInputs(), "flag2on.o")); String compileArgs1 = Joiner.on(" ").join(flag1onCompileAction.getArguments()); String compileArgs2 = Joiner.on(" ").join(flag2onCompileAction.getArguments()); assertThat(compileArgs1).contains("FLAG_1_ON"); assertThat(compileArgs1).contains("FLAG_2_ON"); assertThat(compileArgs2).contains("FLAG_1_ON"); assertThat(compileArgs2).contains("FLAG_2_ON"); } @Test public void testAppleStaticLibraryProvider() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'ios'"); scratch.file("examples/rule/BUILD"); scratch.file( "examples/rule/apple_rules.bzl", "def starlark_static_lib_impl(ctx):", " dep_provider = ctx.attr.proxy[apple_common.AppleStaticLibrary]", " my_provider = apple_common.AppleStaticLibrary(archive = dep_provider.archive,", " objc = dep_provider.objc)", " return [my_provider]", "", "starlark_static_lib = rule(", " implementation = starlark_static_lib_impl,", " attrs = {'proxy': attr.label()},", ")"); scratch.file( "examples/apple_starlark/BUILD", "package(default_visibility = ['//visibility:public'])", "load('//examples/rule:apple_rules.bzl', 'starlark_static_lib')", "starlark_static_lib(", " name='my_target',", " proxy='//x:x'", ")"); ConfiguredTarget binTarget = getConfiguredTarget("//examples/apple_starlark:my_target"); AppleStaticLibraryInfo provider = binTarget.get(AppleStaticLibraryInfo.STARLARK_CONSTRUCTOR); assertThat(provider).isNotNull(); assertThat(provider.getMultiArchArchive()).isNotNull(); assertThat(provider.getDepsObjcProvider()).isNotNull(); assertThat(provider.getMultiArchArchive()) .isEqualTo( provider .getDepsObjcProvider() .get(ObjcProvider.MULTI_ARCH_LINKED_ARCHIVES) .getSingleton()); } @Test public void testAppleStaticLibraryProvider_invalidArgs() throws Exception { RULE_TYPE.scratchTarget(scratch, "platform_type", "'ios'"); scratch.file("examples/rule/BUILD"); scratch.file( "examples/rule/apple_rules.bzl", "def starlark_static_lib_impl(ctx):", " dep_provider = ctx.attr.proxy[apple_common.AppleStaticLibrary]", " my_provider = apple_common.AppleStaticLibrary(archive = dep_provider.archive,", " objc = dep_provider.objc, foo = 'bar')", " return [my_provider]", "", "starlark_static_lib = rule(", " implementation = starlark_static_lib_impl,", " attrs = {'proxy': attr.label()},", ")"); scratch.file( "examples/apple_starlark/BUILD", "package(default_visibility = ['//visibility:public'])", "load('//examples/rule:apple_rules.bzl', 'starlark_static_lib')", "starlark_static_lib(", " name='my_target',", " proxy='//x:x'", ")"); AssertionError expected = assertThrows( AssertionError.class, () -> getConfiguredTarget("//examples/apple_starlark:my_target")); assertThat(expected).hasMessageThat().contains("unexpected keyword argument 'foo'"); } @Test public void testProtoBundlingWithTargetsWithNoDeps() throws Exception { checkProtoBundlingWithTargetsWithNoDeps(RULE_TYPE); } @Test public void testProtoBundlingDoesNotHappen() throws Exception { useConfiguration("--noenable_apple_binary_native_protos"); checkProtoBundlingDoesNotHappen(RULE_TYPE); } }
apache-2.0
DIA-NZ/webcurator
wct-core/src/test/java/org/webcurator/ui/target/controller/LogReaderControllerTest.java
17452
package org.webcurator.ui.target.controller; import static org.junit.Assert.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.validation.BindException; import org.springframework.web.servlet.ModelAndView; import org.webcurator.test.*; import org.webcurator.ui.common.Constants; import org.webcurator.ui.target.command.LogReaderCommand; import org.webcurator.core.harvester.coordinator.*; import org.webcurator.core.scheduler.*; import org.webcurator.domain.model.core.*; public class LogReaderControllerTest extends BaseWCTTest<LogReaderController>{ private TargetInstanceManager tim = null; private HarvestCoordinator hc = null; public LogReaderControllerTest() { super(LogReaderController.class, "src/test/java/org/webcurator/ui/target/controller/LogReaderControllerTest.xml"); } public void setUp() throws Exception { super.setUp(); tim = new MockTargetInstanceManager(testFile); hc = new MockHarvestCoordinator(); } private int countReturnedLines(String[] result) { assertNotNull(result); assertTrue(result.length == 2); if(result[0].equals("")) { return 0; } else { String[] lines = result[0].split("\n"); return lines.length; } } @Test public final void testHandleHead() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_HEAD); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 700); assertEquals(result[0].substring(0,3), "1. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTail() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TAIL); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 700); assertEquals(result[0].substring(0,6), "4602. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleFromLine() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_FROM_LINE); aCmd.setFilter("5000"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 302); assertEquals(result[0].substring(0,6), "5000. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp1() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("2008-06-18T06:25:29"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 4); assertEquals(result[0].substring(0,6), "5298. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp2() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("2008-06-18"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 700); assertEquals(result[0].substring(0,3), "1. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp3() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("18/06/2008 06:25:29"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 4); assertEquals(result[0].substring(0,6), "5298. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp4() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("18/06/2008"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 700); assertEquals(result[0].substring(0,3), "1. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp5() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("20080618062529"); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 4); assertEquals(result[0].substring(0,6), "5298. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleTimestamp6() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilterType(LogReaderCommand.VALUE_TIMESTAMP); aCmd.setFilter("bad format"); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 0); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertNotNull((String)mav.getModel().get(Constants.MESSAGE_TEXT)); assertTrue(((String)mav.getModel().get(Constants.MESSAGE_TEXT)).equals("bad format is not a valid date/time format")); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleRegexMatch() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilter(".*.http://us.geocities.com/everardus.geo/protrudilogo.jpg.*"); aCmd.setFilterType(LogReaderCommand.VALUE_REGEX_MATCH); aCmd.setShowLineNumbers(false); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 1); assertFalse("1. ".equals(result[0].substring(0,3))); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleRegexMatchLineNumbers() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilter(".*.http://us.geocities.com/everardus.geo/protrudilogo.jpg.*"); aCmd.setFilterType(LogReaderCommand.VALUE_REGEX_MATCH); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 1); assertEquals(result[0].substring(0,6), "5280. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleRegexContain() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("crawl.log"); aCmd.setFilter(".*.http://us.geocities.com/everardus.geo/protrudilogo.jpg.*"); aCmd.setFilterType(LogReaderCommand.VALUE_REGEX_CONTAIN); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 22); assertEquals(result[0].substring(0,6), "5280. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testHandleRegexIndent() { try { testInstance.setTargetInstanceManager(tim); testInstance.setHarvestCoordinator(hc); HttpServletRequest aReq = new MockHttpServletRequest(); HttpServletResponse aResp = new MockHttpServletResponse(); LogReaderCommand aCmd = new LogReaderCommand(); TargetInstance ti = tim.getTargetInstance(5000L); aCmd.setTargetInstanceOid(ti.getOid()); aCmd.setLogFileName("local-errors.log"); aCmd.setFilter(".*SocketTimeoutException.*"); aCmd.setFilterType(LogReaderCommand.VALUE_REGEX_INDENT); aCmd.setShowLineNumbers(true); BindException aErrors = new BindException(aCmd, "LogReaderCommand"); ModelAndView mav = testInstance.handle(aReq, aResp, aCmd, aErrors); assertTrue(mav != null); assertNotNull((String[])mav.getModel().get(LogReaderCommand.MDL_LINES)); String[] result = (String[])mav.getModel().get(LogReaderCommand.MDL_LINES); assertTrue(countReturnedLines(result) == 24); assertEquals(result[0].substring(0,4), "21. "); assertTrue(Constants.VIEW_LOG_READER.equals(mav.getViewName())); assertFalse(aErrors.hasErrors()); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testSetHarvestCoordinator() { try { testInstance.setHarvestCoordinator(hc); } catch(Exception e) { fail(e.getMessage()); } } @Test public final void testSetTargetInstanceManager() { try { testInstance.setTargetInstanceManager(tim); } catch(Exception e) { fail(e.getMessage()); } } }
apache-2.0
BMambaYe/SkinExpert
app/src/main/java/com/zhanghao/skinexpert/fragments/ProductSearchFragment.java
4994
package com.zhanghao.skinexpert.fragments; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import com.zhanghao.skinexpert.Activity.ProductLibraryActivity; import com.zhanghao.skinexpert.R; import com.zhanghao.skinexpert.adapter.ProductSearchAdapter; import com.zhanghao.skinexpert.beans.HotSearchWordBean; import com.zhanghao.skinexpert.utils.NetWorkRequest; import com.zhanghao.skinexpert.utils.SQLiteHelper; import java.util.ArrayList; import java.util.List; /** * A simple {@link Fragment} subclass. */ public class ProductSearchFragment extends Fragment implements NetWorkRequest.RequestCallBack { private ListView listView; private List<HotSearchWordBean.DataBean.ListBean> list; private ProductSearchAdapter adapter; private SQLiteDatabase db; private int titleNumber = -1; public ProductSearchFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_product_search, container, false); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { listView = ((ListView) view.findViewById(R.id.lv_product_search)); list = new ArrayList<>(); adapter = new ProductSearchAdapter(getActivity(), list); listView.setAdapter(adapter); initSQLite(); listView.setOnItemClickListener(itemClickListener); initData(); } private void initSQLite() { SQLiteHelper helper = new SQLiteHelper(getActivity()); db = helper.getReadableDatabase(); } private void initData() { NetWorkRequest.getProductHotSearchWords(getActivity(), this); } @Override public void success(Object result) { list.clear(); HotSearchWordBean searchWords = (HotSearchWordBean) result; if (searchWords.getData().getList() != null && searchWords.getData().getList().size() > 0) { HotSearchWordBean.DataBean.ListBean titleBean = new HotSearchWordBean.DataBean.ListBean(); titleBean.setContent("title"); list.add(titleBean); for (HotSearchWordBean.DataBean.ListBean bean : searchWords.getData().getList()) { list.add(bean); } Cursor cursor = db.rawQuery("select * from " + SQLiteHelper.table_search_history, null); List<HotSearchWordBean.DataBean.ListBean> listData = new ArrayList<>(); while (cursor.moveToNext()) { HotSearchWordBean.DataBean.ListBean bean = new HotSearchWordBean.DataBean.ListBean(); bean.setId(cursor.getInt(cursor.getColumnIndex("search_id"))); bean.setContent(cursor.getString(cursor.getColumnIndex("search"))); listData.add(bean); } if (listData.size() > 0) { list.add(titleBean); titleNumber = list.size() - 1; for (int i = listData.size() - 1; i >= 0; i--) { list.add(listData.get(i)); } } } adapter.notifyDataSetChanged(); } @Override public void fail(String result) { Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show(); } AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (position != 0 && position != titleNumber && list != null & list.size() > 0) { int searchId = list.get(position).getId(); String searchName = list.get(position).getContent(); saveSearchData(searchId, searchName); Intent intent = new Intent(getActivity(), ProductLibraryActivity.class); intent.putExtra("search", searchName); startActivity(intent); getActivity().finish(); } } }; private void saveSearchData(int searchId, String searchName) { if (!"".equals(searchName) && searchName != null) { db.delete(SQLiteHelper.table_search_history, "search_id=?", new String[]{searchId + ""}); ContentValues contentValues = new ContentValues(); contentValues.put("search_id", searchId); contentValues.put("search", searchName); db.insert(SQLiteHelper.table_search_history, null, contentValues); } } }
apache-2.0
benwazza/hammer
src/core/hammer/compile/CompilationException.java
889
/* * Copyright 2008-2009 Ben Warren * * 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 hammer.compile; import hammer.core.HammerException; public final class CompilationException extends HammerException { private static final long serialVersionUID = -3632851465321970602L; public CompilationException() { super("Could not compile classes"); } }
apache-2.0
googleapis/java-recommendations-ai
proto-google-cloud-recommendations-ai-v1beta1/src/main/java/com/google/cloud/recommendationengine/v1beta1/ProductDetail.java
55477
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/recommendationengine/v1beta1/user_event.proto package com.google.cloud.recommendationengine.v1beta1; /** * * * <pre> * Detailed product information associated with a user event. * </pre> * * Protobuf type {@code google.cloud.recommendationengine.v1beta1.ProductDetail} */ public final class ProductDetail extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.recommendationengine.v1beta1.ProductDetail) ProductDetailOrBuilder { private static final long serialVersionUID = 0L; // Use ProductDetail.newBuilder() to construct. private ProductDetail(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ProductDetail() { id_ = ""; currencyCode_ = ""; stockState_ = 0; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ProductDetail(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ProductDetail( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); id_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); currencyCode_ = s; break; } case 29: { originalPrice_ = input.readFloat(); break; } case 37: { displayPrice_ = input.readFloat(); break; } case 40: { int rawValue = input.readEnum(); stockState_ = rawValue; break; } case 48: { quantity_ = input.readInt32(); break; } case 56: { availableQuantity_ = input.readInt32(); break; } case 66: { com.google.cloud.recommendationengine.v1beta1.FeatureMap.Builder subBuilder = null; if (itemAttributes_ != null) { subBuilder = itemAttributes_.toBuilder(); } itemAttributes_ = input.readMessage( com.google.cloud.recommendationengine.v1beta1.FeatureMap.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(itemAttributes_); itemAttributes_ = subBuilder.buildPartial(); } break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.recommendationengine.v1beta1.UserEventOuterClass .internal_static_google_cloud_recommendationengine_v1beta1_ProductDetail_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.recommendationengine.v1beta1.UserEventOuterClass .internal_static_google_cloud_recommendationengine_v1beta1_ProductDetail_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.recommendationengine.v1beta1.ProductDetail.class, com.google.cloud.recommendationengine.v1beta1.ProductDetail.Builder.class); } public static final int ID_FIELD_NUMBER = 1; private volatile java.lang.Object id_; /** * * * <pre> * Required. Catalog item ID. UTF-8 encoded string with a length limit of 128 * characters. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The id. */ @java.lang.Override public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } } /** * * * <pre> * Required. Catalog item ID. UTF-8 encoded string with a length limit of 128 * characters. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CURRENCY_CODE_FIELD_NUMBER = 2; private volatile java.lang.Object currencyCode_; /** * * * <pre> * Optional. Currency code for price/costs. Use three-character ISO-4217 * code. Required only if originalPrice or displayPrice is set. * </pre> * * <code>string currency_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The currencyCode. */ @java.lang.Override public java.lang.String getCurrencyCode() { java.lang.Object ref = currencyCode_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); currencyCode_ = s; return s; } } /** * * * <pre> * Optional. Currency code for price/costs. Use three-character ISO-4217 * code. Required only if originalPrice or displayPrice is set. * </pre> * * <code>string currency_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for currencyCode. */ @java.lang.Override public com.google.protobuf.ByteString getCurrencyCodeBytes() { java.lang.Object ref = currencyCode_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); currencyCode_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int ORIGINAL_PRICE_FIELD_NUMBER = 3; private float originalPrice_; /** * * * <pre> * Optional. Original price of the product. If provided, this will override * the original price in Catalog for this product. * </pre> * * <code>float original_price = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The originalPrice. */ @java.lang.Override public float getOriginalPrice() { return originalPrice_; } public static final int DISPLAY_PRICE_FIELD_NUMBER = 4; private float displayPrice_; /** * * * <pre> * Optional. Display price of the product (e.g. discounted price). If * provided, this will override the display price in Catalog for this product. * </pre> * * <code>float display_price = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The displayPrice. */ @java.lang.Override public float getDisplayPrice() { return displayPrice_; } public static final int STOCK_STATE_FIELD_NUMBER = 5; private int stockState_; /** * * * <pre> * Optional. Item stock state. If provided, this overrides the stock state * in Catalog for items in this event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState stock_state = 5 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The enum numeric value on the wire for stockState. */ @java.lang.Override public int getStockStateValue() { return stockState_; } /** * * * <pre> * Optional. Item stock state. If provided, this overrides the stock state * in Catalog for items in this event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState stock_state = 5 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The stockState. */ @java.lang.Override public com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState getStockState() { @SuppressWarnings("deprecation") com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState result = com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState.valueOf( stockState_); return result == null ? com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState.UNRECOGNIZED : result; } public static final int QUANTITY_FIELD_NUMBER = 6; private int quantity_; /** * * * <pre> * Optional. Quantity of the product associated with the user event. For * example, this field will be 2 if two products are added to the shopping * cart for `add-to-cart` event. Required for `add-to-cart`, `add-to-list`, * `remove-from-cart`, `checkout-start`, `purchase-complete`, `refund` event * types. * </pre> * * <code>int32 quantity = 6 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The quantity. */ @java.lang.Override public int getQuantity() { return quantity_; } public static final int AVAILABLE_QUANTITY_FIELD_NUMBER = 7; private int availableQuantity_; /** * * * <pre> * Optional. Quantity of the products in stock when a user event happens. * Optional. If provided, this overrides the available quantity in Catalog for * this event. and can only be set if `stock_status` is set to `IN_STOCK`. * Note that if an item is out of stock, you must set the `stock_state` field * to be `OUT_OF_STOCK`. Leaving this field unspecified / as zero is not * sufficient to mark the item out of stock. * </pre> * * <code>int32 available_quantity = 7 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The availableQuantity. */ @java.lang.Override public int getAvailableQuantity() { return availableQuantity_; } public static final int ITEM_ATTRIBUTES_FIELD_NUMBER = 8; private com.google.cloud.recommendationengine.v1beta1.FeatureMap itemAttributes_; /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the itemAttributes field is set. */ @java.lang.Override public boolean hasItemAttributes() { return itemAttributes_ != null; } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The itemAttributes. */ @java.lang.Override public com.google.cloud.recommendationengine.v1beta1.FeatureMap getItemAttributes() { return itemAttributes_ == null ? com.google.cloud.recommendationengine.v1beta1.FeatureMap.getDefaultInstance() : itemAttributes_; } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.recommendationengine.v1beta1.FeatureMapOrBuilder getItemAttributesOrBuilder() { return getItemAttributes(); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(currencyCode_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, currencyCode_); } if (originalPrice_ != 0F) { output.writeFloat(3, originalPrice_); } if (displayPrice_ != 0F) { output.writeFloat(4, displayPrice_); } if (stockState_ != com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState .STOCK_STATE_UNSPECIFIED .getNumber()) { output.writeEnum(5, stockState_); } if (quantity_ != 0) { output.writeInt32(6, quantity_); } if (availableQuantity_ != 0) { output.writeInt32(7, availableQuantity_); } if (itemAttributes_ != null) { output.writeMessage(8, getItemAttributes()); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(currencyCode_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, currencyCode_); } if (originalPrice_ != 0F) { size += com.google.protobuf.CodedOutputStream.computeFloatSize(3, originalPrice_); } if (displayPrice_ != 0F) { size += com.google.protobuf.CodedOutputStream.computeFloatSize(4, displayPrice_); } if (stockState_ != com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState .STOCK_STATE_UNSPECIFIED .getNumber()) { size += com.google.protobuf.CodedOutputStream.computeEnumSize(5, stockState_); } if (quantity_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(6, quantity_); } if (availableQuantity_ != 0) { size += com.google.protobuf.CodedOutputStream.computeInt32Size(7, availableQuantity_); } if (itemAttributes_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(8, getItemAttributes()); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.recommendationengine.v1beta1.ProductDetail)) { return super.equals(obj); } com.google.cloud.recommendationengine.v1beta1.ProductDetail other = (com.google.cloud.recommendationengine.v1beta1.ProductDetail) obj; if (!getId().equals(other.getId())) return false; if (!getCurrencyCode().equals(other.getCurrencyCode())) return false; if (java.lang.Float.floatToIntBits(getOriginalPrice()) != java.lang.Float.floatToIntBits(other.getOriginalPrice())) return false; if (java.lang.Float.floatToIntBits(getDisplayPrice()) != java.lang.Float.floatToIntBits(other.getDisplayPrice())) return false; if (stockState_ != other.stockState_) return false; if (getQuantity() != other.getQuantity()) return false; if (getAvailableQuantity() != other.getAvailableQuantity()) return false; if (hasItemAttributes() != other.hasItemAttributes()) return false; if (hasItemAttributes()) { if (!getItemAttributes().equals(other.getItemAttributes())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId().hashCode(); hash = (37 * hash) + CURRENCY_CODE_FIELD_NUMBER; hash = (53 * hash) + getCurrencyCode().hashCode(); hash = (37 * hash) + ORIGINAL_PRICE_FIELD_NUMBER; hash = (53 * hash) + java.lang.Float.floatToIntBits(getOriginalPrice()); hash = (37 * hash) + DISPLAY_PRICE_FIELD_NUMBER; hash = (53 * hash) + java.lang.Float.floatToIntBits(getDisplayPrice()); hash = (37 * hash) + STOCK_STATE_FIELD_NUMBER; hash = (53 * hash) + stockState_; hash = (37 * hash) + QUANTITY_FIELD_NUMBER; hash = (53 * hash) + getQuantity(); hash = (37 * hash) + AVAILABLE_QUANTITY_FIELD_NUMBER; hash = (53 * hash) + getAvailableQuantity(); if (hasItemAttributes()) { hash = (37 * hash) + ITEM_ATTRIBUTES_FIELD_NUMBER; hash = (53 * hash) + getItemAttributes().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder( com.google.cloud.recommendationengine.v1beta1.ProductDetail prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * Detailed product information associated with a user event. * </pre> * * Protobuf type {@code google.cloud.recommendationengine.v1beta1.ProductDetail} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.recommendationengine.v1beta1.ProductDetail) com.google.cloud.recommendationengine.v1beta1.ProductDetailOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.recommendationengine.v1beta1.UserEventOuterClass .internal_static_google_cloud_recommendationengine_v1beta1_ProductDetail_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.recommendationengine.v1beta1.UserEventOuterClass .internal_static_google_cloud_recommendationengine_v1beta1_ProductDetail_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.recommendationengine.v1beta1.ProductDetail.class, com.google.cloud.recommendationengine.v1beta1.ProductDetail.Builder.class); } // Construct using com.google.cloud.recommendationengine.v1beta1.ProductDetail.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); id_ = ""; currencyCode_ = ""; originalPrice_ = 0F; displayPrice_ = 0F; stockState_ = 0; quantity_ = 0; availableQuantity_ = 0; if (itemAttributesBuilder_ == null) { itemAttributes_ = null; } else { itemAttributes_ = null; itemAttributesBuilder_ = null; } return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.recommendationengine.v1beta1.UserEventOuterClass .internal_static_google_cloud_recommendationengine_v1beta1_ProductDetail_descriptor; } @java.lang.Override public com.google.cloud.recommendationengine.v1beta1.ProductDetail getDefaultInstanceForType() { return com.google.cloud.recommendationengine.v1beta1.ProductDetail.getDefaultInstance(); } @java.lang.Override public com.google.cloud.recommendationengine.v1beta1.ProductDetail build() { com.google.cloud.recommendationengine.v1beta1.ProductDetail result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.recommendationengine.v1beta1.ProductDetail buildPartial() { com.google.cloud.recommendationengine.v1beta1.ProductDetail result = new com.google.cloud.recommendationengine.v1beta1.ProductDetail(this); result.id_ = id_; result.currencyCode_ = currencyCode_; result.originalPrice_ = originalPrice_; result.displayPrice_ = displayPrice_; result.stockState_ = stockState_; result.quantity_ = quantity_; result.availableQuantity_ = availableQuantity_; if (itemAttributesBuilder_ == null) { result.itemAttributes_ = itemAttributes_; } else { result.itemAttributes_ = itemAttributesBuilder_.build(); } onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.recommendationengine.v1beta1.ProductDetail) { return mergeFrom((com.google.cloud.recommendationengine.v1beta1.ProductDetail) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.recommendationengine.v1beta1.ProductDetail other) { if (other == com.google.cloud.recommendationengine.v1beta1.ProductDetail.getDefaultInstance()) return this; if (!other.getId().isEmpty()) { id_ = other.id_; onChanged(); } if (!other.getCurrencyCode().isEmpty()) { currencyCode_ = other.currencyCode_; onChanged(); } if (other.getOriginalPrice() != 0F) { setOriginalPrice(other.getOriginalPrice()); } if (other.getDisplayPrice() != 0F) { setDisplayPrice(other.getDisplayPrice()); } if (other.stockState_ != 0) { setStockStateValue(other.getStockStateValue()); } if (other.getQuantity() != 0) { setQuantity(other.getQuantity()); } if (other.getAvailableQuantity() != 0) { setAvailableQuantity(other.getAvailableQuantity()); } if (other.hasItemAttributes()) { mergeItemAttributes(other.getItemAttributes()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.recommendationengine.v1beta1.ProductDetail parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.recommendationengine.v1beta1.ProductDetail) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object id_ = ""; /** * * * <pre> * Required. Catalog item ID. UTF-8 encoded string with a length limit of 128 * characters. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The id. */ public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. Catalog item ID. UTF-8 encoded string with a length limit of 128 * characters. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for id. */ public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. Catalog item ID. UTF-8 encoded string with a length limit of 128 * characters. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The id to set. * @return This builder for chaining. */ public Builder setId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } id_ = value; onChanged(); return this; } /** * * * <pre> * Required. Catalog item ID. UTF-8 encoded string with a length limit of 128 * characters. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearId() { id_ = getDefaultInstance().getId(); onChanged(); return this; } /** * * * <pre> * Required. Catalog item ID. UTF-8 encoded string with a length limit of 128 * characters. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for id to set. * @return This builder for chaining. */ public Builder setIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); id_ = value; onChanged(); return this; } private java.lang.Object currencyCode_ = ""; /** * * * <pre> * Optional. Currency code for price/costs. Use three-character ISO-4217 * code. Required only if originalPrice or displayPrice is set. * </pre> * * <code>string currency_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The currencyCode. */ public java.lang.String getCurrencyCode() { java.lang.Object ref = currencyCode_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); currencyCode_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. Currency code for price/costs. Use three-character ISO-4217 * code. Required only if originalPrice or displayPrice is set. * </pre> * * <code>string currency_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for currencyCode. */ public com.google.protobuf.ByteString getCurrencyCodeBytes() { java.lang.Object ref = currencyCode_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); currencyCode_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. Currency code for price/costs. Use three-character ISO-4217 * code. Required only if originalPrice or displayPrice is set. * </pre> * * <code>string currency_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The currencyCode to set. * @return This builder for chaining. */ public Builder setCurrencyCode(java.lang.String value) { if (value == null) { throw new NullPointerException(); } currencyCode_ = value; onChanged(); return this; } /** * * * <pre> * Optional. Currency code for price/costs. Use three-character ISO-4217 * code. Required only if originalPrice or displayPrice is set. * </pre> * * <code>string currency_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearCurrencyCode() { currencyCode_ = getDefaultInstance().getCurrencyCode(); onChanged(); return this; } /** * * * <pre> * Optional. Currency code for price/costs. Use three-character ISO-4217 * code. Required only if originalPrice or displayPrice is set. * </pre> * * <code>string currency_code = 2 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for currencyCode to set. * @return This builder for chaining. */ public Builder setCurrencyCodeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); currencyCode_ = value; onChanged(); return this; } private float originalPrice_; /** * * * <pre> * Optional. Original price of the product. If provided, this will override * the original price in Catalog for this product. * </pre> * * <code>float original_price = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The originalPrice. */ @java.lang.Override public float getOriginalPrice() { return originalPrice_; } /** * * * <pre> * Optional. Original price of the product. If provided, this will override * the original price in Catalog for this product. * </pre> * * <code>float original_price = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The originalPrice to set. * @return This builder for chaining. */ public Builder setOriginalPrice(float value) { originalPrice_ = value; onChanged(); return this; } /** * * * <pre> * Optional. Original price of the product. If provided, this will override * the original price in Catalog for this product. * </pre> * * <code>float original_price = 3 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearOriginalPrice() { originalPrice_ = 0F; onChanged(); return this; } private float displayPrice_; /** * * * <pre> * Optional. Display price of the product (e.g. discounted price). If * provided, this will override the display price in Catalog for this product. * </pre> * * <code>float display_price = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The displayPrice. */ @java.lang.Override public float getDisplayPrice() { return displayPrice_; } /** * * * <pre> * Optional. Display price of the product (e.g. discounted price). If * provided, this will override the display price in Catalog for this product. * </pre> * * <code>float display_price = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The displayPrice to set. * @return This builder for chaining. */ public Builder setDisplayPrice(float value) { displayPrice_ = value; onChanged(); return this; } /** * * * <pre> * Optional. Display price of the product (e.g. discounted price). If * provided, this will override the display price in Catalog for this product. * </pre> * * <code>float display_price = 4 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearDisplayPrice() { displayPrice_ = 0F; onChanged(); return this; } private int stockState_ = 0; /** * * * <pre> * Optional. Item stock state. If provided, this overrides the stock state * in Catalog for items in this event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState stock_state = 5 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The enum numeric value on the wire for stockState. */ @java.lang.Override public int getStockStateValue() { return stockState_; } /** * * * <pre> * Optional. Item stock state. If provided, this overrides the stock state * in Catalog for items in this event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState stock_state = 5 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The enum numeric value on the wire for stockState to set. * @return This builder for chaining. */ public Builder setStockStateValue(int value) { stockState_ = value; onChanged(); return this; } /** * * * <pre> * Optional. Item stock state. If provided, this overrides the stock state * in Catalog for items in this event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState stock_state = 5 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The stockState. */ @java.lang.Override public com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState getStockState() { @SuppressWarnings("deprecation") com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState result = com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState.valueOf( stockState_); return result == null ? com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState.UNRECOGNIZED : result; } /** * * * <pre> * Optional. Item stock state. If provided, this overrides the stock state * in Catalog for items in this event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState stock_state = 5 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The stockState to set. * @return This builder for chaining. */ public Builder setStockState( com.google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState value) { if (value == null) { throw new NullPointerException(); } stockState_ = value.getNumber(); onChanged(); return this; } /** * * * <pre> * Optional. Item stock state. If provided, this overrides the stock state * in Catalog for items in this event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.ProductCatalogItem.StockState stock_state = 5 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return This builder for chaining. */ public Builder clearStockState() { stockState_ = 0; onChanged(); return this; } private int quantity_; /** * * * <pre> * Optional. Quantity of the product associated with the user event. For * example, this field will be 2 if two products are added to the shopping * cart for `add-to-cart` event. Required for `add-to-cart`, `add-to-list`, * `remove-from-cart`, `checkout-start`, `purchase-complete`, `refund` event * types. * </pre> * * <code>int32 quantity = 6 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The quantity. */ @java.lang.Override public int getQuantity() { return quantity_; } /** * * * <pre> * Optional. Quantity of the product associated with the user event. For * example, this field will be 2 if two products are added to the shopping * cart for `add-to-cart` event. Required for `add-to-cart`, `add-to-list`, * `remove-from-cart`, `checkout-start`, `purchase-complete`, `refund` event * types. * </pre> * * <code>int32 quantity = 6 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The quantity to set. * @return This builder for chaining. */ public Builder setQuantity(int value) { quantity_ = value; onChanged(); return this; } /** * * * <pre> * Optional. Quantity of the product associated with the user event. For * example, this field will be 2 if two products are added to the shopping * cart for `add-to-cart` event. Required for `add-to-cart`, `add-to-list`, * `remove-from-cart`, `checkout-start`, `purchase-complete`, `refund` event * types. * </pre> * * <code>int32 quantity = 6 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearQuantity() { quantity_ = 0; onChanged(); return this; } private int availableQuantity_; /** * * * <pre> * Optional. Quantity of the products in stock when a user event happens. * Optional. If provided, this overrides the available quantity in Catalog for * this event. and can only be set if `stock_status` is set to `IN_STOCK`. * Note that if an item is out of stock, you must set the `stock_state` field * to be `OUT_OF_STOCK`. Leaving this field unspecified / as zero is not * sufficient to mark the item out of stock. * </pre> * * <code>int32 available_quantity = 7 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The availableQuantity. */ @java.lang.Override public int getAvailableQuantity() { return availableQuantity_; } /** * * * <pre> * Optional. Quantity of the products in stock when a user event happens. * Optional. If provided, this overrides the available quantity in Catalog for * this event. and can only be set if `stock_status` is set to `IN_STOCK`. * Note that if an item is out of stock, you must set the `stock_state` field * to be `OUT_OF_STOCK`. Leaving this field unspecified / as zero is not * sufficient to mark the item out of stock. * </pre> * * <code>int32 available_quantity = 7 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The availableQuantity to set. * @return This builder for chaining. */ public Builder setAvailableQuantity(int value) { availableQuantity_ = value; onChanged(); return this; } /** * * * <pre> * Optional. Quantity of the products in stock when a user event happens. * Optional. If provided, this overrides the available quantity in Catalog for * this event. and can only be set if `stock_status` is set to `IN_STOCK`. * Note that if an item is out of stock, you must set the `stock_state` field * to be `OUT_OF_STOCK`. Leaving this field unspecified / as zero is not * sufficient to mark the item out of stock. * </pre> * * <code>int32 available_quantity = 7 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearAvailableQuantity() { availableQuantity_ = 0; onChanged(); return this; } private com.google.cloud.recommendationengine.v1beta1.FeatureMap itemAttributes_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.recommendationengine.v1beta1.FeatureMap, com.google.cloud.recommendationengine.v1beta1.FeatureMap.Builder, com.google.cloud.recommendationengine.v1beta1.FeatureMapOrBuilder> itemAttributesBuilder_; /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the itemAttributes field is set. */ public boolean hasItemAttributes() { return itemAttributesBuilder_ != null || itemAttributes_ != null; } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The itemAttributes. */ public com.google.cloud.recommendationengine.v1beta1.FeatureMap getItemAttributes() { if (itemAttributesBuilder_ == null) { return itemAttributes_ == null ? com.google.cloud.recommendationengine.v1beta1.FeatureMap.getDefaultInstance() : itemAttributes_; } else { return itemAttributesBuilder_.getMessage(); } } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setItemAttributes( com.google.cloud.recommendationengine.v1beta1.FeatureMap value) { if (itemAttributesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } itemAttributes_ = value; onChanged(); } else { itemAttributesBuilder_.setMessage(value); } return this; } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setItemAttributes( com.google.cloud.recommendationengine.v1beta1.FeatureMap.Builder builderForValue) { if (itemAttributesBuilder_ == null) { itemAttributes_ = builderForValue.build(); onChanged(); } else { itemAttributesBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder mergeItemAttributes( com.google.cloud.recommendationengine.v1beta1.FeatureMap value) { if (itemAttributesBuilder_ == null) { if (itemAttributes_ != null) { itemAttributes_ = com.google.cloud.recommendationengine.v1beta1.FeatureMap.newBuilder(itemAttributes_) .mergeFrom(value) .buildPartial(); } else { itemAttributes_ = value; } onChanged(); } else { itemAttributesBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearItemAttributes() { if (itemAttributesBuilder_ == null) { itemAttributes_ = null; onChanged(); } else { itemAttributes_ = null; itemAttributesBuilder_ = null; } return this; } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.recommendationengine.v1beta1.FeatureMap.Builder getItemAttributesBuilder() { onChanged(); return getItemAttributesFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.recommendationengine.v1beta1.FeatureMapOrBuilder getItemAttributesOrBuilder() { if (itemAttributesBuilder_ != null) { return itemAttributesBuilder_.getMessageOrBuilder(); } else { return itemAttributes_ == null ? com.google.cloud.recommendationengine.v1beta1.FeatureMap.getDefaultInstance() : itemAttributes_; } } /** * * * <pre> * Optional. Extra features associated with a product in the user event. * </pre> * * <code> * .google.cloud.recommendationengine.v1beta1.FeatureMap item_attributes = 8 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.recommendationengine.v1beta1.FeatureMap, com.google.cloud.recommendationengine.v1beta1.FeatureMap.Builder, com.google.cloud.recommendationengine.v1beta1.FeatureMapOrBuilder> getItemAttributesFieldBuilder() { if (itemAttributesBuilder_ == null) { itemAttributesBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.recommendationengine.v1beta1.FeatureMap, com.google.cloud.recommendationengine.v1beta1.FeatureMap.Builder, com.google.cloud.recommendationengine.v1beta1.FeatureMapOrBuilder>( getItemAttributes(), getParentForChildren(), isClean()); itemAttributes_ = null; } return itemAttributesBuilder_; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.recommendationengine.v1beta1.ProductDetail) } // @@protoc_insertion_point(class_scope:google.cloud.recommendationengine.v1beta1.ProductDetail) private static final com.google.cloud.recommendationengine.v1beta1.ProductDetail DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.recommendationengine.v1beta1.ProductDetail(); } public static com.google.cloud.recommendationengine.v1beta1.ProductDetail getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ProductDetail> PARSER = new com.google.protobuf.AbstractParser<ProductDetail>() { @java.lang.Override public ProductDetail parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ProductDetail(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ProductDetail> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ProductDetail> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.recommendationengine.v1beta1.ProductDetail getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
apache-2.0
coursera/courier
idea-plugin/src/org/coursera/courier/psi/CourierNamedElementReferenceBase.java
2963
/* * Copyright 2015 Coursera Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.coursera.courier.psi; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiReference; import com.intellij.psi.util.PsiTreeUtil; import org.coursera.courier.CourierResolver; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class CourierNamedElementReferenceBase extends CourierNamedElementBase { public CourierNamedElementReferenceBase(@NotNull ASTNode node) { super(node); } public TypeName getFullname() { CourierFullyQualifiedName nameNode = PsiTreeUtil.findChildOfType(this, CourierFullyQualifiedName.class); if (nameNode != null) { return toFullname(getCourierFile(), nameNode.getText()); } return null; } public static TypeName toFullname(CourierFile courieFile, String unescapedName) { if (TypeName.isPrimitive(unescapedName) || unescapedName.contains(".")) { return TypeName.escaped(unescapedName); } else { TypeName importedName = courieFile.lookupImport(TypeName.escape(unescapedName)); if (importedName != null) { return importedName; } else { CourierNamespace namespace = courieFile.getNamespace(); if (namespace != null) { return TypeName.escaped(namespace.getText(), unescapedName); } else { return TypeName.escaped(unescapedName); } } } } @Nullable @Override public PsiElement getNameIdentifier() { if (getFullname().isPrimitive()) { return null; } ASTNode qualifiedName = getNode().findChildByType(CourierTypes.FULLY_QUALIFIED_NAME); if (qualifiedName != null) { return qualifiedName.getLastChildNode().getPsi(); } return null; } @Override public PsiReference getReference() { if (getFullname().isPrimitive()) { return null; } CourierTypeNameDeclaration declaration = CourierResolver.findTypeDeclaration(getProject(), getFullname()); if (declaration != null) { // need the offsets of the declaration name within the text of this element String name = declaration.getName(); int start = getText().lastIndexOf(name); int end = start + name.length(); return new CourierReference(this, declaration, new TextRange(start, end)); } return null; } }
apache-2.0
consulo/consulo-java
jam-api/src/main/java/com/intellij/jam/reflect/JamAnnotatedChildrenQuery.java
2223
/* * Copyright 2000-2012 JetBrains s.r.o. * * 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.intellij.jam.reflect; import com.intellij.jam.JamElement; import com.intellij.psi.PsiMember; import com.intellij.psi.PsiModifierListOwner; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; /** * @author peter */ public abstract class JamAnnotatedChildrenQuery<Jam extends JamElement> extends JamChildrenQuery<Jam> { private final String myAnnoName; public JamAnnotatedChildrenQuery(@NonNls JamAnnotationMeta meta) { myAnnoName = meta.getAnnoName(); } @Nullable protected abstract JamMemberMeta<?, ? extends Jam> getMemberMeta(@Nonnull PsiModifierListOwner member); @Override public JamMemberMeta<?, ? extends Jam> getMeta(@Nonnull PsiModifierListOwner member) { final JamMemberMeta<?, ? extends Jam> memberMeta = getMemberMeta(member); return memberMeta != null && isAnnotated(member, myAnnoName) ? memberMeta : null; } public String getAnnoName() { return myAnnoName; } protected abstract PsiModifierListOwner[] getAllChildren(@Nonnull PsiMember parent); public List<Jam> findChildren(@Nonnull PsiMember parent) { final ArrayList<Jam> list = ContainerUtil.newArrayList(); for (final PsiModifierListOwner child : getAllChildren(parent)) { if (isAnnotated(child, myAnnoName)) { final JamMemberMeta meta = getMemberMeta(child); if (meta != null) { ContainerUtil.addIfNotNull((Jam)meta.getJamElement(child), list); } } } return list; } }
apache-2.0
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_4406.java
151
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_4406 { }
apache-2.0
vergilchiu/hive
ql/src/java/org/apache/hadoop/hive/ql/optimizer/listbucketingpruner/ListBucketingPrunerUtils.java
13590
/** * 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.hadoop.hive.ql.optimizer.listbucketingpruner; import java.util.List; import org.apache.hadoop.hive.ql.exec.FunctionRegistry; import org.apache.hadoop.hive.ql.metadata.Partition; import org.apache.hadoop.hive.ql.parse.ParseContext; import org.apache.hadoop.hive.ql.parse.SemanticException; import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeDesc; import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc; import org.apache.hadoop.hive.ql.udf.generic.GenericUDFOPEqual; /** * Utility for list bucketing prune. * */ public final class ListBucketingPrunerUtils { /* Default list bucketing directory name. internal use only not for client. */ public static final String HIVE_LIST_BUCKETING_DEFAULT_DIR_NAME = "HIVE_DEFAULT_LIST_BUCKETING_DIR_NAME"; /* Default list bucketing directory key. internal use only not for client. */ public static final String HIVE_LIST_BUCKETING_DEFAULT_KEY = "HIVE_DEFAULT_LIST_BUCKETING_KEY"; /** * Decide if pruner skips the skewed directory * Input: if the skewed value matches the expression tree * Ouput: if pruner should skip the directory represented by the skewed value * If match result is unknown(null) or true, pruner doesn't skip the directory * If match result is false, pruner skips the dir. * @param bool * if the skewed value matches the expression tree * @return */ public static boolean skipSkewedDirectory(Boolean bool) { if (bool == null) { return false; } return !bool.booleanValue(); } /** * or 2 Boolean operands in the context of pruning match * * Operand one|Operand another | or result * unknown | T | T * unknown | F | unknown * unknown | unknown | unknown * T | T | T * T | F | T * T | unknown | unknown * F | T | T * F | F | F * F | unknown | unknown */ public static Boolean orBoolOperand(Boolean o, Boolean a) { // pick up unknown case if (o == null) { if ((a == null) || !a) { return null; } else { return a; } } else if (a == null) { return null; } return (o || a); } /** * And 2 Boolean operands in the context of pruning match * * Operand one|Operand another | And result * unknown | T | unknown * unknown | F | F * unknown | unknown | unknown * T | T | T * T | F | F * T | unknown | unknown * F | T | F * F | F | F * F | unknown | F * @param o * one operand * @param a * another operand * @return result */ public static Boolean andBoolOperand(Boolean o, Boolean a) { // pick up unknown case and let and operator handle the rest if (o == null) { if ((a == null) || a) { return null; } else { return a; } } else if (a == null) { return o ? null : Boolean.FALSE; } return (o && a); } /** * Not a Boolean operand in the context of pruning match * * Operand | Not * T | F * F | T * unknown | unknown * @param input * match result * @return */ public static Boolean notBoolOperand(Boolean input) { if (input == null) { return null; } return input ? Boolean.FALSE : Boolean.TRUE; } /** * 1. Walk through the tree to decide value * 1.1 true means the element matches the expression tree * 1.2 false means the element doesn't match the expression tree * 1.3 unknown means not sure if the element matches the expression tree * * Example: * skewed column: C1, C2 * cell: (1,a) , (1,b) , (1,c) , (1,other), (2,a), (2,b) , (2,c), (2,other), (other,a), (other,b), * (other,c), (other,other) * * * Expression Tree : ((c1=1) and (c2=a)) or ( (c1=3) or (c2=b)) * * or * / \ * and or * / \ / \ * c1=1 c2=a c1=3 c2=b * @throws SemanticException * */ static Boolean evaluateExprOnCell(List<String> skewedCols, List<String> cell, ExprNodeDesc pruner, List<List<String>> uniqSkewedValues) throws SemanticException { return recursiveExpr(pruner, skewedCols, cell, uniqSkewedValues); } /** * Walk through expression tree recursively to evaluate. * * * @param node * @param skewedCols * @param cell * @return * @throws SemanticException */ private static Boolean recursiveExpr(final ExprNodeDesc node, final List<String> skewedCols, final List<String> cell, final List<List<String>> uniqSkewedValues) throws SemanticException { if (isUnknownState(node)) { return null; } if (node instanceof ExprNodeGenericFuncDesc) { if (((ExprNodeGenericFuncDesc) node).getGenericUDF() instanceof GenericUDFOPEqual) { return evaluateEqualNd(node, skewedCols, cell, uniqSkewedValues); } else if (FunctionRegistry.isOpAnd(node)) { return evaluateAndNode(node, skewedCols, cell, uniqSkewedValues); } else if (FunctionRegistry.isOpOr(node)) { return evaluateOrNode(node, skewedCols, cell, uniqSkewedValues); } else if (FunctionRegistry.isOpNot(node)) { return evaluateNotNode(node, skewedCols, cell, uniqSkewedValues); } else { return null; } } else { return null; } } /** * Evaluate equal node. * * * @param node * @param skewedCols * @param cell * @param uniqSkewedValues * @return * @throws SemanticException */ private static Boolean evaluateEqualNd(final ExprNodeDesc node, final List<String> skewedCols, final List<String> cell, final List<List<String>> uniqSkewedValues) throws SemanticException { Boolean result = null; List<ExprNodeDesc> children = ((ExprNodeGenericFuncDesc) node).getChildren(); assert ((children != null) && (children.size() == 2)) : "GenericUDFOPEqual should have 2 " + "ExprNodeDesc. Node name : " + node.getName(); ExprNodeDesc left = children.get(0); ExprNodeDesc right = children.get(1); assert (left instanceof ExprNodeColumnDesc && right instanceof ExprNodeConstantDesc) : "GenericUDFOPEqual should have 2 children: " + " the first is ExprNodeColumnDesc and the second is ExprNodeConstantDesc. " + "But this one, the first one is " + left.getName() + " and the second is " + right.getName(); result = startComparisonInEqualNode(skewedCols, cell, uniqSkewedValues, result, left, right); return result; } /** * Comparison in equal node * * @param skewedCols * @param cell * @param uniqSkewedValues * @param result * @param left * @param right * @return * @throws SemanticException */ private static Boolean startComparisonInEqualNode(final List<String> skewedCols, final List<String> cell, final List<List<String>> uniqSkewedValues, Boolean result, ExprNodeDesc left, ExprNodeDesc right) throws SemanticException { String columnNameInFilter = ((ExprNodeColumnDesc) left).getColumn(); String constantValueInFilter = ((ExprNodeConstantDesc) right).getValue().toString(); assert (skewedCols.contains(columnNameInFilter)) : "List bucketing pruner has a column name " + columnNameInFilter + " which is not found in the partition's skewed column list"; int index = skewedCols.indexOf(columnNameInFilter); assert (index < cell.size()) : "GenericUDFOPEqual has a ExprNodeColumnDesc (" + columnNameInFilter + ") which is " + index + "th" + "skewed column. " + " But it can't find the matching part in cell." + " Because the cell size is " + cell.size(); String cellValueInPosition = cell.get(index); assert (index < uniqSkewedValues.size()) : "GenericUDFOPEqual has a ExprNodeColumnDesc (" + columnNameInFilter + ") which is " + index + "th" + "skewed column. " + " But it can't find the matching part in uniq skewed value list." + " Because the cell size is " + uniqSkewedValues.size(); List<String> uniqSkewedValuesInPosition = uniqSkewedValues.get(index); result = coreComparisonInEqualNode(constantValueInFilter, cellValueInPosition, uniqSkewedValuesInPosition); return result; } /** * Compare * @param constantValueInFilter * @param cellValueInPosition * @param uniqSkewedValuesInPosition * @return */ private static Boolean coreComparisonInEqualNode(String constantValueInFilter, String cellValueInPosition, List<String> uniqSkewedValuesInPosition) { Boolean result; // Compare cell value with constant value in filter // 1 if they match and cell value isn't other, return true // 2 if they don't match but cell is other and value in filter is not skewed value, // return unknown. why not true? true is not enough. since not true is false, // but not unknown is unknown. // For example, skewed column C, skewed value 1, 2. clause: where not ( c =3) // cell is other, evaluate (not(c=3)). // other to (c=3), if ture. not(c=3) will be false. but it is wrong skip default dir // but, if unknown. not(c=3) will be unknown. we will choose default dir. // 3 all others, return false if (cellValueInPosition.equals(constantValueInFilter) && !cellValueInPosition.equals(ListBucketingPrunerUtils.HIVE_LIST_BUCKETING_DEFAULT_KEY)) { result = Boolean.TRUE; } else if (cellValueInPosition.equals(ListBucketingPrunerUtils.HIVE_LIST_BUCKETING_DEFAULT_KEY) && !uniqSkewedValuesInPosition.contains(constantValueInFilter)) { result = null; } else { result = Boolean.FALSE; } return result; } private static Boolean evaluateNotNode(final ExprNodeDesc node, final List<String> skewedCols, final List<String> cell, final List<List<String>> uniqSkewedValues) throws SemanticException { List<ExprNodeDesc> children = ((ExprNodeGenericFuncDesc) node).getChildren(); if ((children == null) || (children.size() != 1)) { throw new SemanticException("GenericUDFOPNot should have 1 ExprNodeDesc. Node name : " + node.getName()); } ExprNodeDesc child = children.get(0); return notBoolOperand(recursiveExpr(child, skewedCols, cell, uniqSkewedValues)); } private static Boolean evaluateOrNode(final ExprNodeDesc node, final List<String> skewedCols, final List<String> cell, final List<List<String>> uniqSkewedValues) throws SemanticException { List<ExprNodeDesc> children = ((ExprNodeGenericFuncDesc) node).getChildren(); if ((children == null) || (children.size() != 2)) { throw new SemanticException("GenericUDFOPOr should have 2 ExprNodeDesc. Node name : " + node.getName()); } ExprNodeDesc left = children.get(0); ExprNodeDesc right = children.get(1); return orBoolOperand(recursiveExpr(left, skewedCols, cell, uniqSkewedValues), recursiveExpr(right, skewedCols, cell, uniqSkewedValues)); } private static Boolean evaluateAndNode(final ExprNodeDesc node, final List<String> skewedCols, final List<String> cell, final List<List<String>> uniqSkewedValues) throws SemanticException { List<ExprNodeDesc> children = ((ExprNodeGenericFuncDesc) node).getChildren(); if ((children == null) || (children.size() != 2)) { throw new SemanticException("GenericUDFOPAnd should have 2 ExprNodeDesc. Node name : " + node.getName()); } ExprNodeDesc left = children.get(0); ExprNodeDesc right = children.get(1); return andBoolOperand(recursiveExpr(left, skewedCols, cell, uniqSkewedValues), recursiveExpr(right, skewedCols, cell, uniqSkewedValues)); } /** * Check if the node is unknown * * * unknown is marked in {@link #transform(ParseContext)} <blockquote> * * <pre> * newcd = new ExprNodeConstantDesc(cd.getTypeInfo(), null) * </pre> * * like * * 1. non-skewed column * * 2. non and/or/not ... * * * @param descNd * @return */ static boolean isUnknownState(ExprNodeDesc descNd) { boolean unknown = false; if ((descNd == null) || (descNd instanceof ExprNodeConstantDesc && ((ExprNodeConstantDesc) descNd).getValue() == null)) { unknown = true; } return unknown; } /** * check if the partition is list bucketing * * @param part * @return */ public static boolean isListBucketingPart(Partition part) { return (part.getSkewedColNames() != null) && (part.getSkewedColNames().size() > 0) && (part.getSkewedColValues() != null) && (part.getSkewedColValues().size() > 0) && (part.getSkewedColValueLocationMaps() != null) && (part.getSkewedColValueLocationMaps().size() > 0); } }
apache-2.0
barchart/fixio
core/src/main/java/fixio/netty/pipeline/client/FixSessionSettingsProvider.java
942
/* * Copyright 2014 The FIX.io Project * * The FIX.io Project 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 fixio.netty.pipeline.client; public interface FixSessionSettingsProvider { String getSenderCompID(); String getSenderSubID(); String getTargetCompID(); String getTargetSubID(); String getBeginString(); boolean isResetMsgSeqNum(); int getHeartbeatInterval(); }
apache-2.0